file.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Generic File Format Support.
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. */
  24. /*** MODULEINFO
  25. <support_level>core</support_level>
  26. ***/
  27. #include "asterisk.h"
  28. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  29. #include <dirent.h>
  30. #include <sys/stat.h>
  31. #include <sys/wait.h>
  32. #include <math.h>
  33. #include "asterisk/_private.h" /* declare ast_file_init() */
  34. #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
  35. #include "asterisk/mod_format.h"
  36. #include "asterisk/cli.h"
  37. #include "asterisk/channel.h"
  38. #include "asterisk/sched.h"
  39. #include "asterisk/translate.h"
  40. #include "asterisk/utils.h"
  41. #include "asterisk/lock.h"
  42. #include "asterisk/app.h"
  43. #include "asterisk/pbx.h"
  44. #include "asterisk/linkedlists.h"
  45. #include "asterisk/module.h"
  46. #include "asterisk/astobj2.h"
  47. #include "asterisk/test.h"
  48. #include "asterisk/stasis.h"
  49. #include "asterisk/json.h"
  50. #include "asterisk/stasis_system.h"
  51. /*! \brief
  52. * The following variable controls the layout of localized sound files.
  53. * If 0, use the historical layout with prefix just before the filename
  54. * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
  55. * if 1 put the prefix at the beginning of the filename
  56. * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
  57. * The latter permits a language to be entirely in one directory.
  58. *
  59. * This is settable in asterisk.conf.
  60. */
  61. int ast_language_is_prefix = 1;
  62. static AST_RWLIST_HEAD_STATIC(formats, ast_format_def);
  63. STASIS_MESSAGE_TYPE_DEFN(ast_format_register_type);
  64. STASIS_MESSAGE_TYPE_DEFN(ast_format_unregister_type);
  65. static struct ast_json *json_array_from_list(const char *list, const char *sep)
  66. {
  67. RAII_VAR(struct ast_json *, array, ast_json_array_create(), ast_json_unref);
  68. char *stringp, *ext;
  69. stringp = ast_strdupa(list); /* this is in the stack so does not need to be freed */
  70. if (!array || !stringp) {
  71. return NULL;
  72. }
  73. while ((ext = strsep(&stringp, sep))) {
  74. if (ast_json_array_append(array, ast_json_string_create(ext))) {
  75. return NULL;
  76. }
  77. }
  78. return ast_json_ref(array);
  79. }
  80. static int publish_format_update(const struct ast_format_def *f, struct stasis_message_type *type)
  81. {
  82. RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
  83. RAII_VAR(struct ast_json_payload *, json_payload, NULL, ao2_cleanup);
  84. RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
  85. if (!type) {
  86. return -1;
  87. }
  88. json_object = ast_json_pack("{s: s, s: o}",
  89. "format", f->name,
  90. "extensions", json_array_from_list(f->exts, "|"));
  91. if (!json_object) {
  92. return -1;
  93. }
  94. json_payload = ast_json_payload_create(json_object);
  95. if (!json_payload) {
  96. return -1;
  97. }
  98. msg = stasis_message_create(type, json_payload);
  99. if (!msg) {
  100. return -1;
  101. }
  102. stasis_publish(ast_system_topic(), msg);
  103. return 0;
  104. }
  105. int __ast_format_def_register(const struct ast_format_def *f, struct ast_module *mod)
  106. {
  107. struct ast_format_def *tmp;
  108. AST_RWLIST_WRLOCK(&formats);
  109. AST_RWLIST_TRAVERSE(&formats, tmp, list) {
  110. if (!strcasecmp(f->name, tmp->name)) {
  111. AST_RWLIST_UNLOCK(&formats);
  112. ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
  113. return -1;
  114. }
  115. }
  116. if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
  117. AST_RWLIST_UNLOCK(&formats);
  118. return -1;
  119. }
  120. *tmp = *f;
  121. tmp->module = mod;
  122. if (tmp->buf_size) {
  123. /*
  124. * Align buf_size properly, rounding up to the machine-specific
  125. * alignment for pointers.
  126. */
  127. struct _test_align { void *a, *b; } p;
  128. int align = (char *)&p.b - (char *)&p.a;
  129. tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
  130. }
  131. memset(&tmp->list, 0, sizeof(tmp->list));
  132. AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
  133. AST_RWLIST_UNLOCK(&formats);
  134. ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
  135. publish_format_update(f, ast_format_register_type());
  136. return 0;
  137. }
  138. int ast_format_def_unregister(const char *name)
  139. {
  140. struct ast_format_def *tmp;
  141. int res = -1;
  142. AST_RWLIST_WRLOCK(&formats);
  143. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
  144. if (!strcasecmp(name, tmp->name)) {
  145. AST_RWLIST_REMOVE_CURRENT(list);
  146. publish_format_update(tmp, ast_format_unregister_type());
  147. ast_free(tmp);
  148. res = 0;
  149. }
  150. }
  151. AST_RWLIST_TRAVERSE_SAFE_END;
  152. AST_RWLIST_UNLOCK(&formats);
  153. if (!res)
  154. ast_verb(2, "Unregistered format %s\n", name);
  155. else
  156. ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
  157. return res;
  158. }
  159. int ast_stopstream(struct ast_channel *tmp)
  160. {
  161. ast_channel_lock(tmp);
  162. /* Stop a running stream if there is one */
  163. if (ast_channel_stream(tmp)) {
  164. ast_closestream(ast_channel_stream(tmp));
  165. ast_channel_stream_set(tmp, NULL);
  166. if (ast_channel_oldwriteformat(tmp) && ast_set_write_format(tmp, ast_channel_oldwriteformat(tmp)))
  167. ast_log(LOG_WARNING, "Unable to restore format back to %s\n", ast_format_get_name(ast_channel_oldwriteformat(tmp)));
  168. }
  169. /* Stop the video stream too */
  170. if (ast_channel_vstream(tmp) != NULL) {
  171. ast_closestream(ast_channel_vstream(tmp));
  172. ast_channel_vstream_set(tmp, NULL);
  173. }
  174. ast_channel_unlock(tmp);
  175. return 0;
  176. }
  177. int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
  178. {
  179. int res = -1;
  180. if (f->frametype == AST_FRAME_VIDEO) {
  181. if (ast_format_get_type(fs->fmt->format) == AST_MEDIA_TYPE_AUDIO) {
  182. /* This is the audio portion. Call the video one... */
  183. if (!fs->vfs && fs->filename) {
  184. const char *type = ast_format_get_name(f->subclass.format);
  185. fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
  186. ast_debug(1, "Opened video output file\n");
  187. }
  188. if (fs->vfs)
  189. return ast_writestream(fs->vfs, f);
  190. /* else ignore */
  191. return 0;
  192. }
  193. } else if (f->frametype != AST_FRAME_VOICE) {
  194. ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
  195. return -1;
  196. }
  197. if (ast_format_cmp(f->subclass.format, fs->fmt->format) != AST_FORMAT_CMP_NOT_EQUAL) {
  198. res = fs->fmt->write(fs, f);
  199. if (res < 0)
  200. ast_log(LOG_WARNING, "Natural write failed\n");
  201. else if (res > 0)
  202. ast_log(LOG_WARNING, "Huh??\n");
  203. } else {
  204. /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
  205. the one we've setup a translator for, we do the "wrong thing" XXX */
  206. if (fs->trans && (ast_format_cmp(f->subclass.format, fs->lastwriteformat) != AST_FORMAT_CMP_EQUAL)) {
  207. ast_translator_free_path(fs->trans);
  208. fs->trans = NULL;
  209. }
  210. if (!fs->trans) {
  211. fs->trans = ast_translator_build_path(fs->fmt->format, f->subclass.format);
  212. }
  213. if (!fs->trans) {
  214. ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
  215. fs->fmt->name, ast_format_get_name(f->subclass.format));
  216. } else {
  217. struct ast_frame *trf;
  218. ao2_replace(fs->lastwriteformat, f->subclass.format);
  219. /* Get the translated frame but don't consume the original in case they're using it on another stream */
  220. if ((trf = ast_translate(fs->trans, f, 0))) {
  221. struct ast_frame *cur;
  222. /* the translator may have returned multiple frames, so process them */
  223. for (cur = trf; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
  224. if ((res = fs->fmt->write(fs, trf))) {
  225. ast_log(LOG_WARNING, "Translated frame write failed\n");
  226. break;
  227. }
  228. }
  229. ast_frfree(trf);
  230. } else {
  231. res = 0;
  232. }
  233. }
  234. }
  235. return res;
  236. }
  237. static int copy(const char *infile, const char *outfile)
  238. {
  239. int ifd, ofd, len;
  240. char buf[4096]; /* XXX make it lerger. */
  241. if ((ifd = open(infile, O_RDONLY)) < 0) {
  242. ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
  243. return -1;
  244. }
  245. if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
  246. ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
  247. close(ifd);
  248. return -1;
  249. }
  250. while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
  251. int res;
  252. if (len < 0) {
  253. ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
  254. break;
  255. }
  256. /* XXX handle partial writes */
  257. res = write(ofd, buf, len);
  258. if (res != len) {
  259. ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
  260. len = -1; /* error marker */
  261. break;
  262. }
  263. }
  264. close(ifd);
  265. close(ofd);
  266. if (len < 0) {
  267. unlink(outfile);
  268. return -1; /* error */
  269. }
  270. return 0; /* success */
  271. }
  272. /*!
  273. * \brief construct a filename. Absolute pathnames are preserved,
  274. * relative names are prefixed by the sounds/ directory.
  275. * The wav49 suffix is replaced by 'WAV'.
  276. * Returns a malloc'ed string to be freed by the caller.
  277. */
  278. static char *build_filename(const char *filename, const char *ext)
  279. {
  280. char *fn = NULL;
  281. if (!strcmp(ext, "wav49"))
  282. ext = "WAV";
  283. if (filename[0] == '/') {
  284. if (ast_asprintf(&fn, "%s.%s", filename, ext) < 0) {
  285. fn = NULL;
  286. }
  287. } else {
  288. if (ast_asprintf(&fn, "%s/sounds/%s.%s",
  289. ast_config_AST_DATA_DIR, filename, ext) < 0) {
  290. fn = NULL;
  291. }
  292. }
  293. return fn;
  294. }
  295. /* compare type against the list 'exts' */
  296. /* XXX need a better algorithm */
  297. static int exts_compare(const char *exts, const char *type)
  298. {
  299. char tmp[256];
  300. char *stringp = tmp, *ext;
  301. ast_copy_string(tmp, exts, sizeof(tmp));
  302. while ((ext = strsep(&stringp, "|"))) {
  303. if (!strcmp(ext, type))
  304. return 1;
  305. }
  306. return 0;
  307. }
  308. /*!
  309. * \internal
  310. * \brief Close the file stream by canceling any pending read / write callbacks
  311. */
  312. static void filestream_close(struct ast_filestream *f)
  313. {
  314. enum ast_media_type format_type = ast_format_get_type(f->fmt->format);
  315. if (!f->owner) {
  316. return;
  317. }
  318. /* Stop a running stream if there is one */
  319. switch (format_type)
  320. {
  321. case AST_MEDIA_TYPE_AUDIO:
  322. ast_channel_stream_set(f->owner, NULL);
  323. AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_streamid, ast_channel_streamid_set);
  324. ast_settimeout(f->owner, 0, NULL, NULL);
  325. break;
  326. case AST_MEDIA_TYPE_VIDEO:
  327. ast_channel_vstream_set(f->owner, NULL);
  328. AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_vstreamid, ast_channel_vstreamid_set);
  329. break;
  330. default:
  331. ast_log(AST_LOG_WARNING, "Unable to schedule deletion of filestream with unsupported type %s\n", f->fmt->name);
  332. break;
  333. }
  334. }
  335. static void filestream_destructor(void *arg)
  336. {
  337. struct ast_filestream *f = arg;
  338. int status;
  339. int pid = -1;
  340. /* Stop a running stream if there is one */
  341. filestream_close(f);
  342. /* destroy the translator on exit */
  343. if (f->trans)
  344. ast_translator_free_path(f->trans);
  345. if (f->fmt->close) {
  346. void (*closefn)(struct ast_filestream *) = f->fmt->close;
  347. closefn(f);
  348. }
  349. if (f->f) {
  350. fclose(f->f);
  351. }
  352. if (f->realfilename && f->filename) {
  353. pid = ast_safe_fork(0);
  354. if (!pid) {
  355. execl("/bin/mv", "mv", "-f", f->filename, f->realfilename, SENTINEL);
  356. _exit(1);
  357. }
  358. else if (pid > 0) {
  359. /* Block the parent until the move is complete.*/
  360. waitpid(pid, &status, 0);
  361. }
  362. }
  363. if (f->filename)
  364. free(f->filename);
  365. if (f->realfilename)
  366. free(f->realfilename);
  367. if (f->vfs)
  368. ast_closestream(f->vfs);
  369. if (f->write_buffer) {
  370. ast_free(f->write_buffer);
  371. }
  372. if (f->orig_chan_name)
  373. free((void *) f->orig_chan_name);
  374. ao2_cleanup(f->lastwriteformat);
  375. ao2_cleanup(f->fr.subclass.format);
  376. ast_module_unref(f->fmt->module);
  377. }
  378. static struct ast_filestream *get_filestream(struct ast_format_def *fmt, FILE *bfile)
  379. {
  380. struct ast_filestream *s;
  381. int l = sizeof(*s) + fmt->buf_size + fmt->desc_size; /* total allocation size */
  382. if ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
  383. return NULL;
  384. ast_module_ref(fmt->module);
  385. s->fmt = fmt;
  386. s->f = bfile;
  387. if (fmt->desc_size)
  388. s->_private = ((char *)(s + 1)) + fmt->buf_size;
  389. if (fmt->buf_size)
  390. s->buf = (char *)(s + 1);
  391. s->fr.src = fmt->name;
  392. if (ast_format_get_type(fmt->format) == AST_MEDIA_TYPE_AUDIO) {
  393. s->fr.frametype = AST_FRAME_VOICE;
  394. } else if (ast_format_get_type(fmt->format) == AST_MEDIA_TYPE_VIDEO) {
  395. s->fr.frametype = AST_FRAME_VIDEO;
  396. }
  397. s->fr.mallocd = 0;
  398. s->fr.subclass.format = ao2_bump(fmt->format);
  399. return s;
  400. }
  401. /*
  402. * Default implementations of open and rewrite.
  403. * Only use them if you don't have expensive stuff to do.
  404. */
  405. enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
  406. static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
  407. {
  408. struct ast_format_def *f = s->fmt;
  409. int ret = -1;
  410. int (*openfn)(struct ast_filestream *s);
  411. if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
  412. ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
  413. else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
  414. ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
  415. else {
  416. /* preliminary checks succeed. */
  417. ret = 0;
  418. }
  419. return ret;
  420. }
  421. static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
  422. {
  423. return fn_wrapper(s, comment, WRAP_REWRITE);
  424. }
  425. static int open_wrapper(struct ast_filestream *s)
  426. {
  427. return fn_wrapper(s, NULL, WRAP_OPEN);
  428. }
  429. enum file_action {
  430. ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
  431. ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
  432. ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
  433. ACTION_OPEN,
  434. ACTION_COPY /* copy file. return 0 on success, -1 on error */
  435. };
  436. /*!
  437. * \internal
  438. * \brief perform various actions on a file. Second argument
  439. * \note arg2 depends on the command:
  440. * unused for DELETE
  441. * optional ast_format_cap holding all the formats found for a file, for EXISTS.
  442. * destination file name (const char *) for COPY and RENAME
  443. * struct ast_channel * for OPEN
  444. * if fmt is NULL, OPEN will return the first matching entry,
  445. * whereas other functions will run on all matching entries.
  446. */
  447. static int filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
  448. {
  449. struct ast_format_def *f;
  450. int res = (action == ACTION_EXISTS) ? 0 : -1;
  451. AST_RWLIST_RDLOCK(&formats);
  452. /* Check for a specific format */
  453. AST_RWLIST_TRAVERSE(&formats, f, list) {
  454. char *stringp, *ext = NULL;
  455. if (fmt && !exts_compare(f->exts, fmt))
  456. continue;
  457. /* Look for a file matching the supported extensions.
  458. * The file must exist, and for OPEN, must match
  459. * one of the formats supported by the channel.
  460. */
  461. stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
  462. while ( (ext = strsep(&stringp, "|")) ) {
  463. struct stat st;
  464. char *fn = build_filename(filename, ext);
  465. if (fn == NULL)
  466. continue;
  467. if ( stat(fn, &st) ) { /* file not existent */
  468. ast_free(fn);
  469. continue;
  470. }
  471. /* for 'OPEN' we need to be sure that the format matches
  472. * what the channel can process
  473. */
  474. if (action == ACTION_OPEN) {
  475. struct ast_channel *chan = (struct ast_channel *)arg2;
  476. FILE *bfile;
  477. struct ast_filestream *s;
  478. if ((ast_format_cmp(ast_channel_writeformat(chan), f->format) == AST_FORMAT_CMP_NOT_EQUAL) &&
  479. !(((ast_format_get_type(f->format) == AST_MEDIA_TYPE_AUDIO) && fmt) ||
  480. ((ast_format_get_type(f->format) == AST_MEDIA_TYPE_VIDEO) && fmt))) {
  481. ast_free(fn);
  482. continue; /* not a supported format */
  483. }
  484. if ( (bfile = fopen(fn, "r")) == NULL) {
  485. ast_free(fn);
  486. continue; /* cannot open file */
  487. }
  488. s = get_filestream(f, bfile);
  489. if (!s) {
  490. fclose(bfile);
  491. ast_free(fn); /* cannot allocate descriptor */
  492. continue;
  493. }
  494. if (open_wrapper(s)) {
  495. ast_free(fn);
  496. ast_closestream(s);
  497. continue; /* cannot run open on file */
  498. }
  499. if (st.st_size == 0) {
  500. ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
  501. }
  502. /* ok this is good for OPEN */
  503. res = 1; /* found */
  504. s->lasttimeout = -1;
  505. s->fmt = f;
  506. s->trans = NULL;
  507. s->filename = NULL;
  508. if (ast_format_get_type(s->fmt->format) == AST_MEDIA_TYPE_AUDIO) {
  509. if (ast_channel_stream(chan))
  510. ast_closestream(ast_channel_stream(chan));
  511. ast_channel_stream_set(chan, s);
  512. } else {
  513. if (ast_channel_vstream(chan))
  514. ast_closestream(ast_channel_vstream(chan));
  515. ast_channel_vstream_set(chan, s);
  516. }
  517. ast_free(fn);
  518. break;
  519. }
  520. switch (action) {
  521. case ACTION_OPEN:
  522. break; /* will never get here */
  523. case ACTION_EXISTS: /* return the matching format */
  524. /* if arg2 is present, it is a format capabilities structure.
  525. * Add this format to the set of formats this file can be played in */
  526. if (arg2) {
  527. ast_format_cap_append((struct ast_format_cap *) arg2, f->format, 0);
  528. }
  529. res = 1; /* file does exist and format it exists in is returned in arg2 */
  530. break;
  531. case ACTION_DELETE:
  532. if ( (res = unlink(fn)) )
  533. ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
  534. break;
  535. case ACTION_RENAME:
  536. case ACTION_COPY: {
  537. char *nfn = build_filename((const char *)arg2, ext);
  538. if (!nfn)
  539. ast_log(LOG_WARNING, "Out of memory\n");
  540. else {
  541. res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
  542. if (res)
  543. ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
  544. action == ACTION_COPY ? "copy" : "rename",
  545. fn, nfn, strerror(errno));
  546. ast_free(nfn);
  547. }
  548. }
  549. break;
  550. default:
  551. ast_log(LOG_WARNING, "Unknown helper %u\n", action);
  552. }
  553. ast_free(fn);
  554. }
  555. }
  556. AST_RWLIST_UNLOCK(&formats);
  557. return res;
  558. }
  559. static int is_absolute_path(const char *filename)
  560. {
  561. return filename[0] == '/';
  562. }
  563. /*!
  564. * \brief test if a file exists for a given format.
  565. * \note result_cap is OPTIONAL
  566. * \retval 1, true and result_cap represents format capabilities file exists in.
  567. * \retval 0, false
  568. */
  569. static int fileexists_test(const char *filename, const char *fmt, const char *lang,
  570. char *buf, int buflen, struct ast_format_cap *result_cap)
  571. {
  572. if (buf == NULL) {
  573. return 0;
  574. }
  575. if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
  576. if (lang) {
  577. snprintf(buf, buflen, "%s/%s", lang, filename);
  578. } else {
  579. snprintf(buf, buflen, "%s", filename);
  580. }
  581. } else { /* old layout */
  582. strcpy(buf, filename); /* first copy the full string */
  583. if (lang) {
  584. /* insert the language and suffix if needed */
  585. const char *c = strrchr(filename, '/');
  586. int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
  587. snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
  588. }
  589. }
  590. return filehelper(buf, result_cap, fmt, ACTION_EXISTS);
  591. }
  592. /*!
  593. * \brief helper routine to locate a file with a given format
  594. * and language preference.
  595. *
  596. * \note Try preflang, preflang with stripped '_' suffices, or NULL.
  597. *
  598. * \note The last parameter(s) point to a buffer of sufficient size,
  599. * which on success is filled with the matching filename.
  600. *
  601. * \param filename Name of the file.
  602. * \param fmt Format to look for the file in. OPTIONAL
  603. * \param preflang The perfered language
  604. * \param buf Returns the matching filename
  605. * \param buflen Size of the buf
  606. * \param result_cap OPTIONAL format capabilities result structure
  607. * returns what formats the file was found in.
  608. *
  609. * \retval 1, true. file exists and result format is set
  610. * \retval 0, false. file does not exist.
  611. */
  612. static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
  613. char *buf, int buflen, struct ast_format_cap *result_cap)
  614. {
  615. char *lang;
  616. if (buf == NULL) {
  617. return 0;
  618. }
  619. /* We try languages in the following order:
  620. * preflang (may include dialect and style codes)
  621. * lang (preflang without dialect - if any)
  622. * <none>
  623. * default (unless the same as preflang or lang without dialect)
  624. */
  625. lang = ast_strdupa(preflang);
  626. /* Try preferred language, including removing any style or dialect codes */
  627. while (!ast_strlen_zero(lang)) {
  628. char *end;
  629. if (fileexists_test(filename, fmt, lang, buf, buflen, result_cap)) {
  630. return 1;
  631. }
  632. if ((end = strrchr(lang, '_')) != NULL) {
  633. *end = '\0';
  634. continue;
  635. }
  636. break;
  637. }
  638. /* Try without any language */
  639. if (fileexists_test(filename, fmt, NULL, buf, buflen, result_cap)) {
  640. return 1;
  641. }
  642. /* Finally try the default language unless it was already tried before */
  643. if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
  644. if ((fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen, result_cap)) > 0) {
  645. return 1;
  646. }
  647. }
  648. return 0;
  649. }
  650. struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
  651. {
  652. return ast_openstream_full(chan, filename, preflang, 0);
  653. }
  654. struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
  655. {
  656. /*
  657. * Use fileexists_core() to find a file in a compatible
  658. * language and format, set up a suitable translator,
  659. * and open the stream.
  660. */
  661. struct ast_format_cap *file_fmt_cap;
  662. int res;
  663. int buflen;
  664. char *buf;
  665. if (!asis) {
  666. /* do this first, otherwise we detect the wrong writeformat */
  667. ast_stopstream(chan);
  668. if (ast_channel_generator(chan))
  669. ast_deactivate_generator(chan);
  670. }
  671. if (preflang == NULL)
  672. preflang = "";
  673. buflen = strlen(preflang) + strlen(filename) + 4;
  674. buf = ast_alloca(buflen);
  675. if (!(file_fmt_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  676. return NULL;
  677. }
  678. if (!fileexists_core(filename, NULL, preflang, buf, buflen, file_fmt_cap) ||
  679. !ast_format_cap_has_type(file_fmt_cap, AST_MEDIA_TYPE_AUDIO)) {
  680. ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
  681. ao2_ref(file_fmt_cap, -1);
  682. return NULL;
  683. }
  684. /* Set the channel to a format we can work with and save off the previous format. */
  685. ast_channel_lock(chan);
  686. ast_channel_set_oldwriteformat(chan, ast_channel_writeformat(chan));
  687. /* Set the channel to the best format that exists for the file. */
  688. res = ast_set_write_format_from_cap(chan, file_fmt_cap);
  689. ast_channel_unlock(chan);
  690. /* don't need this anymore now that the channel's write format is set. */
  691. ao2_ref(file_fmt_cap, -1);
  692. if (res == -1) { /* No format available that works with this channel */
  693. return NULL;
  694. }
  695. res = filehelper(buf, chan, NULL, ACTION_OPEN);
  696. if (res >= 0)
  697. return ast_channel_stream(chan);
  698. return NULL;
  699. }
  700. struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
  701. {
  702. /* As above, but for video. But here we don't have translators
  703. * so we must enforce a format.
  704. */
  705. struct ast_format_cap *tmp_cap;
  706. char *buf;
  707. int buflen;
  708. int i, fd;
  709. if (preflang == NULL) {
  710. preflang = "";
  711. }
  712. buflen = strlen(preflang) + strlen(filename) + 4;
  713. buf = ast_alloca(buflen);
  714. /* is the channel capable of video without translation ?*/
  715. if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_MEDIA_TYPE_VIDEO)) {
  716. return NULL;
  717. }
  718. if (!(tmp_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  719. return NULL;
  720. }
  721. /* Video is supported, so see what video formats exist for this file */
  722. if (!fileexists_core(filename, NULL, preflang, buf, buflen, tmp_cap)) {
  723. ao2_ref(tmp_cap, -1);
  724. return NULL;
  725. }
  726. /* iterate over file formats and pick the first one compatible with the channel's native formats */
  727. for (i = 0; i < ast_format_cap_count(tmp_cap); ++i) {
  728. struct ast_format *format = ast_format_cap_get_format(tmp_cap, i);
  729. if ((ast_format_get_type(format) != AST_MEDIA_TYPE_VIDEO) ||
  730. !ast_format_cap_iscompatible(ast_channel_nativeformats(chan), tmp_cap)) {
  731. ao2_ref(format, -1);
  732. continue;
  733. }
  734. fd = filehelper(buf, chan, ast_format_get_name(format), ACTION_OPEN);
  735. if (fd >= 0) {
  736. ao2_ref(format, -1);
  737. ao2_ref(tmp_cap, -1);
  738. return ast_channel_vstream(chan);
  739. }
  740. ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
  741. ao2_ref(format, -1);
  742. }
  743. ao2_ref(tmp_cap, -1);
  744. return NULL;
  745. }
  746. static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
  747. {
  748. struct ast_frame *fr, *new_fr;
  749. if (!s || !s->fmt) {
  750. return NULL;
  751. }
  752. if (!(fr = s->fmt->read(s, whennext))) {
  753. return NULL;
  754. }
  755. if (!(new_fr = ast_frisolate(fr))) {
  756. ast_frfree(fr);
  757. return NULL;
  758. }
  759. if (new_fr != fr) {
  760. ast_frfree(fr);
  761. fr = new_fr;
  762. }
  763. return fr;
  764. }
  765. struct ast_frame *ast_readframe(struct ast_filestream *s)
  766. {
  767. int whennext = 0;
  768. return read_frame(s, &whennext);
  769. }
  770. enum fsread_res {
  771. FSREAD_FAILURE,
  772. FSREAD_SUCCESS_SCHED,
  773. FSREAD_SUCCESS_NOSCHED,
  774. };
  775. static int ast_fsread_audio(const void *data);
  776. static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
  777. {
  778. int whennext = 0;
  779. while (!whennext) {
  780. struct ast_frame *fr;
  781. if (s->orig_chan_name && strcasecmp(ast_channel_name(s->owner), s->orig_chan_name)) {
  782. goto return_failure;
  783. }
  784. fr = read_frame(s, &whennext);
  785. if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
  786. if (fr) {
  787. ast_log(LOG_WARNING, "Failed to write frame\n");
  788. ast_frfree(fr);
  789. }
  790. goto return_failure;
  791. }
  792. if (fr) {
  793. ast_frfree(fr);
  794. }
  795. }
  796. if (whennext != s->lasttimeout) {
  797. if (ast_channel_timingfd(s->owner) > -1) {
  798. float samp_rate = (float) ast_format_get_sample_rate(s->fmt->format);
  799. unsigned int rate;
  800. rate = (unsigned int) roundf(samp_rate / ((float) whennext));
  801. ast_settimeout_full(s->owner, rate, ast_fsread_audio, s, 1);
  802. } else {
  803. ast_channel_streamid_set(s->owner, ast_sched_add(ast_channel_sched(s->owner), whennext / (ast_format_get_sample_rate(s->fmt->format) / 1000), ast_fsread_audio, s));
  804. }
  805. s->lasttimeout = whennext;
  806. return FSREAD_SUCCESS_NOSCHED;
  807. }
  808. return FSREAD_SUCCESS_SCHED;
  809. return_failure:
  810. ast_channel_streamid_set(s->owner, -1);
  811. ast_settimeout(s->owner, 0, NULL, NULL);
  812. return FSREAD_FAILURE;
  813. }
  814. static int ast_fsread_audio(const void *data)
  815. {
  816. struct ast_filestream *fs = (struct ast_filestream *)data;
  817. enum fsread_res res;
  818. res = ast_readaudio_callback(fs);
  819. if (res == FSREAD_SUCCESS_SCHED)
  820. return 1;
  821. return 0;
  822. }
  823. static int ast_fsread_video(const void *data);
  824. static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
  825. {
  826. int whennext = 0;
  827. while (!whennext) {
  828. struct ast_frame *fr = read_frame(s, &whennext);
  829. if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
  830. if (fr) {
  831. ast_log(LOG_WARNING, "Failed to write frame\n");
  832. ast_frfree(fr);
  833. }
  834. ast_channel_vstreamid_set(s->owner, -1);
  835. return FSREAD_FAILURE;
  836. }
  837. if (fr) {
  838. ast_frfree(fr);
  839. }
  840. }
  841. if (whennext != s->lasttimeout) {
  842. ast_channel_vstreamid_set(s->owner, ast_sched_add(ast_channel_sched(s->owner), whennext / (ast_format_get_sample_rate(s->fmt->format) / 1000), ast_fsread_video, s));
  843. s->lasttimeout = whennext;
  844. return FSREAD_SUCCESS_NOSCHED;
  845. }
  846. return FSREAD_SUCCESS_SCHED;
  847. }
  848. static int ast_fsread_video(const void *data)
  849. {
  850. struct ast_filestream *fs = (struct ast_filestream *)data;
  851. enum fsread_res res;
  852. res = ast_readvideo_callback(fs);
  853. if (res == FSREAD_SUCCESS_SCHED)
  854. return 1;
  855. return 0;
  856. }
  857. int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
  858. {
  859. s->owner = chan;
  860. return 0;
  861. }
  862. int ast_playstream(struct ast_filestream *s)
  863. {
  864. enum fsread_res res;
  865. if (ast_format_get_type(s->fmt->format) == AST_MEDIA_TYPE_AUDIO)
  866. res = ast_readaudio_callback(s);
  867. else
  868. res = ast_readvideo_callback(s);
  869. return (res == FSREAD_FAILURE) ? -1 : 0;
  870. }
  871. int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
  872. {
  873. return fs->fmt->seek(fs, sample_offset, whence);
  874. }
  875. int ast_truncstream(struct ast_filestream *fs)
  876. {
  877. return fs->fmt->trunc(fs);
  878. }
  879. off_t ast_tellstream(struct ast_filestream *fs)
  880. {
  881. return fs->fmt->tell(fs);
  882. }
  883. int ast_ratestream(struct ast_filestream *fs)
  884. {
  885. return ast_format_get_sample_rate(fs->fmt->format);
  886. }
  887. int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
  888. {
  889. return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
  890. }
  891. int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
  892. {
  893. return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
  894. }
  895. int ast_closestream(struct ast_filestream *f)
  896. {
  897. /* This used to destroy the filestream, but it now just decrements a refcount.
  898. * We close the stream in order to quit queuing frames now, because we might
  899. * change the writeformat, which could result in a subsequent write error, if
  900. * the format is different. */
  901. if (f == NULL) {
  902. return 0;
  903. }
  904. filestream_close(f);
  905. ao2_ref(f, -1);
  906. return 0;
  907. }
  908. /*
  909. * Look the various language-specific places where a file could exist.
  910. */
  911. int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
  912. {
  913. char *buf;
  914. int buflen;
  915. if (preflang == NULL)
  916. preflang = "";
  917. buflen = strlen(preflang) + strlen(filename) + 4; /* room for everything */
  918. buf = ast_alloca(buflen);
  919. return fileexists_core(filename, fmt, preflang, buf, buflen, NULL) ? 1 : 0;
  920. }
  921. int ast_filedelete(const char *filename, const char *fmt)
  922. {
  923. return filehelper(filename, NULL, fmt, ACTION_DELETE);
  924. }
  925. int ast_filerename(const char *filename, const char *filename2, const char *fmt)
  926. {
  927. return filehelper(filename, filename2, fmt, ACTION_RENAME);
  928. }
  929. int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
  930. {
  931. return filehelper(filename, filename2, fmt, ACTION_COPY);
  932. }
  933. int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
  934. {
  935. struct ast_filestream *fs;
  936. struct ast_filestream *vfs=NULL;
  937. off_t pos;
  938. int seekattempt;
  939. int res;
  940. fs = ast_openstream(chan, filename, preflang);
  941. if (!fs) {
  942. struct ast_str *codec_buf = ast_str_alloca(64);
  943. ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n",
  944. filename, ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf), strerror(errno));
  945. return -1;
  946. }
  947. /* check to see if there is any data present (not a zero length file),
  948. * done this way because there is no where for ast_openstream_full to
  949. * return the file had no data. */
  950. pos = ftello(fs->f);
  951. seekattempt = fseeko(fs->f, -1, SEEK_END);
  952. if (seekattempt) {
  953. if (errno == EINVAL) {
  954. /* Zero-length file, as opposed to a pipe */
  955. return 0;
  956. } else {
  957. ast_seekstream(fs, 0, SEEK_SET);
  958. }
  959. } else {
  960. fseeko(fs->f, pos, SEEK_SET);
  961. }
  962. vfs = ast_openvstream(chan, filename, preflang);
  963. if (vfs) {
  964. ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_format_get_name(vfs->fmt->format));
  965. }
  966. if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_MASQ_NOSTREAM))
  967. fs->orig_chan_name = ast_strdup(ast_channel_name(chan));
  968. if (ast_applystream(chan, fs))
  969. return -1;
  970. if (vfs && ast_applystream(chan, vfs))
  971. return -1;
  972. ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", filename, ast_channel_name(chan));
  973. res = ast_playstream(fs);
  974. if (!res && vfs)
  975. res = ast_playstream(vfs);
  976. ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", ast_channel_name(chan), filename, ast_format_get_name(ast_channel_writeformat(chan)), preflang ? preflang : "default");
  977. return res;
  978. }
  979. struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
  980. {
  981. FILE *bfile;
  982. struct ast_format_def *f;
  983. struct ast_filestream *fs = NULL;
  984. char *fn;
  985. int format_found = 0;
  986. AST_RWLIST_RDLOCK(&formats);
  987. AST_RWLIST_TRAVERSE(&formats, f, list) {
  988. fs = NULL;
  989. if (!exts_compare(f->exts, type))
  990. continue;
  991. else
  992. format_found = 1;
  993. fn = build_filename(filename, type);
  994. if (!fn) {
  995. continue;
  996. }
  997. errno = 0;
  998. bfile = fopen(fn, "r");
  999. if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
  1000. ast_log(LOG_WARNING, "Unable to open %s\n", fn);
  1001. if (fs) {
  1002. ast_closestream(fs);
  1003. }
  1004. fs = NULL;
  1005. bfile = NULL;
  1006. ast_free(fn);
  1007. break;
  1008. }
  1009. /* found it */
  1010. fs->trans = NULL;
  1011. fs->fmt = f;
  1012. fs->flags = flags;
  1013. fs->mode = mode;
  1014. fs->filename = ast_strdup(filename);
  1015. fs->vfs = NULL;
  1016. ast_free(fn);
  1017. break;
  1018. }
  1019. AST_RWLIST_UNLOCK(&formats);
  1020. if (!format_found)
  1021. ast_log(LOG_WARNING, "No such format '%s'\n", type);
  1022. return fs;
  1023. }
  1024. struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
  1025. {
  1026. int fd, myflags = 0;
  1027. /* compiler claims this variable can be used before initialization... */
  1028. FILE *bfile = NULL;
  1029. struct ast_format_def *f;
  1030. struct ast_filestream *fs = NULL;
  1031. char *buf = NULL;
  1032. size_t size = 0;
  1033. int format_found = 0;
  1034. AST_RWLIST_RDLOCK(&formats);
  1035. /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
  1036. /* We really can't use O_APPEND as it will break WAV header updates */
  1037. if (flags & O_APPEND) {
  1038. flags &= ~O_APPEND;
  1039. } else {
  1040. myflags = O_TRUNC;
  1041. }
  1042. myflags |= O_WRONLY | O_CREAT;
  1043. /* XXX need to fix this - we should just do the fopen,
  1044. * not open followed by fdopen()
  1045. */
  1046. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1047. char *fn, *orig_fn = NULL;
  1048. if (fs)
  1049. break;
  1050. if (!exts_compare(f->exts, type))
  1051. continue;
  1052. else
  1053. format_found = 1;
  1054. fn = build_filename(filename, type);
  1055. if (!fn) {
  1056. continue;
  1057. }
  1058. fd = open(fn, flags | myflags, mode);
  1059. if (fd > -1) {
  1060. /* fdopen() the resulting file stream */
  1061. bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
  1062. if (!bfile) {
  1063. ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
  1064. close(fd);
  1065. fd = -1;
  1066. }
  1067. }
  1068. if (ast_opt_cache_record_files && (fd > -1)) {
  1069. char *c;
  1070. fclose(bfile); /* this also closes fd */
  1071. /*
  1072. We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
  1073. What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
  1074. */
  1075. orig_fn = ast_strdupa(fn);
  1076. for (c = fn; *c; c++)
  1077. if (*c == '/')
  1078. *c = '_';
  1079. size = strlen(fn) + strlen(record_cache_dir) + 2;
  1080. buf = ast_alloca(size);
  1081. strcpy(buf, record_cache_dir);
  1082. strcat(buf, "/");
  1083. strcat(buf, fn);
  1084. ast_free(fn);
  1085. fn = buf;
  1086. fd = open(fn, flags | myflags, mode);
  1087. if (fd > -1) {
  1088. /* fdopen() the resulting file stream */
  1089. bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
  1090. if (!bfile) {
  1091. ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
  1092. close(fd);
  1093. fd = -1;
  1094. }
  1095. }
  1096. }
  1097. if (fd > -1) {
  1098. errno = 0;
  1099. fs = get_filestream(f, bfile);
  1100. if (fs) {
  1101. if ((fs->write_buffer = ast_malloc(32768))) {
  1102. setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
  1103. }
  1104. }
  1105. if (!fs || rewrite_wrapper(fs, comment)) {
  1106. ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
  1107. close(fd);
  1108. if (orig_fn) {
  1109. unlink(fn);
  1110. unlink(orig_fn);
  1111. }
  1112. if (fs) {
  1113. ast_closestream(fs);
  1114. fs = NULL;
  1115. }
  1116. if (!buf) {
  1117. ast_free(fn);
  1118. }
  1119. continue;
  1120. }
  1121. fs->trans = NULL;
  1122. fs->fmt = f;
  1123. fs->flags = flags;
  1124. fs->mode = mode;
  1125. if (orig_fn) {
  1126. fs->realfilename = ast_strdup(orig_fn);
  1127. fs->filename = ast_strdup(fn);
  1128. } else {
  1129. fs->realfilename = NULL;
  1130. fs->filename = ast_strdup(filename);
  1131. }
  1132. fs->vfs = NULL;
  1133. /* If truncated, we'll be at the beginning; if not truncated, then append */
  1134. f->seek(fs, 0, SEEK_END);
  1135. } else if (errno != EEXIST) {
  1136. ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
  1137. if (orig_fn)
  1138. unlink(orig_fn);
  1139. }
  1140. /* if buf != NULL then fn is already free and pointing to it */
  1141. if (!buf)
  1142. ast_free(fn);
  1143. }
  1144. AST_RWLIST_UNLOCK(&formats);
  1145. if (!format_found)
  1146. ast_log(LOG_WARNING, "No such format '%s'\n", type);
  1147. return fs;
  1148. }
  1149. static void waitstream_control(struct ast_channel *c,
  1150. enum ast_waitstream_fr_cb_values type,
  1151. ast_waitstream_fr_cb cb,
  1152. int skip_ms)
  1153. {
  1154. switch (type)
  1155. {
  1156. case AST_WAITSTREAM_CB_FASTFORWARD:
  1157. {
  1158. int eoftest;
  1159. ast_stream_fastforward(ast_channel_stream(c), skip_ms);
  1160. eoftest = fgetc(ast_channel_stream(c)->f);
  1161. if (feof(ast_channel_stream(c)->f)) {
  1162. ast_stream_rewind(ast_channel_stream(c), skip_ms);
  1163. } else {
  1164. ungetc(eoftest, ast_channel_stream(c)->f);
  1165. }
  1166. }
  1167. break;
  1168. case AST_WAITSTREAM_CB_REWIND:
  1169. ast_stream_rewind(ast_channel_stream(c), skip_ms);
  1170. break;
  1171. default:
  1172. break;
  1173. }
  1174. if (cb) {
  1175. long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_get_sample_rate(ast_channel_stream(c)->fmt->format) / 1000);
  1176. cb(c, ms_len, type);
  1177. }
  1178. ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
  1179. "Control: %s\r\n"
  1180. "SkipMs: %d\r\n",
  1181. ast_channel_name(c),
  1182. (type == AST_WAITSTREAM_CB_FASTFORWARD) ? "FastForward" : "Rewind",
  1183. skip_ms);
  1184. }
  1185. /*!
  1186. * \brief the core of all waitstream() functions
  1187. */
  1188. static int waitstream_core(struct ast_channel *c,
  1189. const char *breakon,
  1190. const char *forward,
  1191. const char *reverse,
  1192. int skip_ms,
  1193. int audiofd,
  1194. int cmdfd,
  1195. const char *context,
  1196. ast_waitstream_fr_cb cb)
  1197. {
  1198. const char *orig_chan_name = NULL;
  1199. int err = 0;
  1200. if (!breakon)
  1201. breakon = "";
  1202. if (!forward)
  1203. forward = "";
  1204. if (!reverse)
  1205. reverse = "";
  1206. /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
  1207. ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1208. if (ast_test_flag(ast_channel_flags(c), AST_FLAG_MASQ_NOSTREAM))
  1209. orig_chan_name = ast_strdupa(ast_channel_name(c));
  1210. if (ast_channel_stream(c) && cb) {
  1211. long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_get_sample_rate(ast_channel_stream(c)->fmt->format) / 1000);
  1212. cb(c, ms_len, AST_WAITSTREAM_CB_START);
  1213. }
  1214. while (ast_channel_stream(c)) {
  1215. int res;
  1216. int ms;
  1217. if (orig_chan_name && strcasecmp(orig_chan_name, ast_channel_name(c))) {
  1218. ast_stopstream(c);
  1219. err = 1;
  1220. break;
  1221. }
  1222. ms = ast_sched_wait(ast_channel_sched(c));
  1223. if (ms < 0 && !ast_channel_timingfunc(c)) {
  1224. ast_stopstream(c);
  1225. break;
  1226. }
  1227. if (ms < 0)
  1228. ms = 1000;
  1229. if (cmdfd < 0) {
  1230. res = ast_waitfor(c, ms);
  1231. if (res < 0) {
  1232. ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
  1233. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1234. return res;
  1235. }
  1236. } else {
  1237. int outfd;
  1238. struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
  1239. if (!rchan && (outfd < 0) && (ms)) {
  1240. /* Continue */
  1241. if (errno == EINTR)
  1242. continue;
  1243. ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
  1244. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1245. return -1;
  1246. } else if (outfd > -1) { /* this requires cmdfd set */
  1247. /* The FD we were watching has something waiting */
  1248. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1249. return 1;
  1250. }
  1251. /* if rchan is set, it is 'c' */
  1252. res = rchan ? 1 : 0; /* map into 'res' values */
  1253. }
  1254. if (res > 0) {
  1255. struct ast_frame *fr = ast_read(c);
  1256. if (!fr) {
  1257. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1258. return -1;
  1259. }
  1260. switch (fr->frametype) {
  1261. case AST_FRAME_DTMF_END:
  1262. if (context) {
  1263. const char exten[2] = { fr->subclass.integer, '\0' };
  1264. if (ast_exists_extension(c, context, exten, 1,
  1265. S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, NULL))) {
  1266. res = fr->subclass.integer;
  1267. ast_frfree(fr);
  1268. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1269. return res;
  1270. }
  1271. } else {
  1272. res = fr->subclass.integer;
  1273. if (strchr(forward, res)) {
  1274. waitstream_control(c, AST_WAITSTREAM_CB_FASTFORWARD, cb, skip_ms);
  1275. } else if (strchr(reverse, res)) {
  1276. waitstream_control(c, AST_WAITSTREAM_CB_REWIND, cb, skip_ms);
  1277. } else if (strchr(breakon, res)) {
  1278. ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
  1279. "Control: %s\r\n",
  1280. ast_channel_name(c),
  1281. "Break");
  1282. ast_frfree(fr);
  1283. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1284. return res;
  1285. }
  1286. }
  1287. break;
  1288. case AST_FRAME_CONTROL:
  1289. switch (fr->subclass.integer) {
  1290. case AST_CONTROL_STREAM_STOP:
  1291. case AST_CONTROL_STREAM_SUSPEND:
  1292. case AST_CONTROL_STREAM_RESTART:
  1293. /* Fall-through and break out */
  1294. ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
  1295. "Control: %s\r\n",
  1296. ast_channel_name(c),
  1297. "Break");
  1298. res = fr->subclass.integer;
  1299. ast_frfree(fr);
  1300. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1301. return res;
  1302. case AST_CONTROL_STREAM_REVERSE:
  1303. if (!skip_ms) {
  1304. skip_ms = 3000;
  1305. }
  1306. waitstream_control(c, AST_WAITSTREAM_CB_REWIND, cb, skip_ms);
  1307. break;
  1308. case AST_CONTROL_STREAM_FORWARD:
  1309. if (!skip_ms) {
  1310. skip_ms = 3000;
  1311. }
  1312. waitstream_control(c, AST_WAITSTREAM_CB_FASTFORWARD, cb, skip_ms);
  1313. break;
  1314. case AST_CONTROL_HANGUP:
  1315. case AST_CONTROL_BUSY:
  1316. case AST_CONTROL_CONGESTION:
  1317. ast_frfree(fr);
  1318. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1319. return -1;
  1320. case AST_CONTROL_RINGING:
  1321. case AST_CONTROL_ANSWER:
  1322. case AST_CONTROL_VIDUPDATE:
  1323. case AST_CONTROL_SRCUPDATE:
  1324. case AST_CONTROL_SRCCHANGE:
  1325. case AST_CONTROL_HOLD:
  1326. case AST_CONTROL_UNHOLD:
  1327. case AST_CONTROL_CONNECTED_LINE:
  1328. case AST_CONTROL_REDIRECTING:
  1329. case AST_CONTROL_AOC:
  1330. case AST_CONTROL_UPDATE_RTP_PEER:
  1331. case AST_CONTROL_PVT_CAUSE_CODE:
  1332. case -1:
  1333. /* Unimportant */
  1334. break;
  1335. default:
  1336. ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass.integer);
  1337. }
  1338. break;
  1339. case AST_FRAME_VOICE:
  1340. /* Write audio if appropriate */
  1341. if (audiofd > -1) {
  1342. if (write(audiofd, fr->data.ptr, fr->datalen) < 0) {
  1343. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  1344. }
  1345. }
  1346. default:
  1347. /* Ignore all others */
  1348. break;
  1349. }
  1350. ast_frfree(fr);
  1351. }
  1352. ast_sched_runq(ast_channel_sched(c));
  1353. }
  1354. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1355. return (err || ast_channel_softhangup_internal_flag(c)) ? -1 : 0;
  1356. }
  1357. int ast_waitstream_fr_w_cb(struct ast_channel *c,
  1358. const char *breakon,
  1359. const char *forward,
  1360. const char *reverse,
  1361. int ms,
  1362. ast_waitstream_fr_cb cb)
  1363. {
  1364. return waitstream_core(c, breakon, forward, reverse, ms,
  1365. -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, cb);
  1366. }
  1367. int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
  1368. {
  1369. return waitstream_core(c, breakon, forward, reverse, ms,
  1370. -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, NULL /* no callback */);
  1371. }
  1372. /*! \internal
  1373. * \brief Clean up the return value of a waitstream call
  1374. *
  1375. * It's possible for a control frame to come in from an external source and break the
  1376. * playback. From a consumer of most ast_waitstream_* function callers, this should
  1377. * appear like normal playback termination, i.e., return 0 and not the value of the
  1378. * control frame.
  1379. */
  1380. static int sanitize_waitstream_return(int return_value)
  1381. {
  1382. switch (return_value) {
  1383. case AST_CONTROL_STREAM_STOP:
  1384. case AST_CONTROL_STREAM_SUSPEND:
  1385. case AST_CONTROL_STREAM_RESTART:
  1386. /* Fall through and set return_value to 0 */
  1387. return_value = 0;
  1388. break;
  1389. default:
  1390. /* Do nothing */
  1391. break;
  1392. }
  1393. return return_value;
  1394. }
  1395. int ast_waitstream(struct ast_channel *c, const char *breakon)
  1396. {
  1397. int res;
  1398. res = waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL, NULL /* no callback */);
  1399. return sanitize_waitstream_return(res);
  1400. }
  1401. int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
  1402. {
  1403. int res;
  1404. res = waitstream_core(c, breakon, NULL, NULL, 0,
  1405. audiofd, cmdfd, NULL /* no context */, NULL /* no callback */);
  1406. return sanitize_waitstream_return(res);
  1407. }
  1408. int ast_waitstream_exten(struct ast_channel *c, const char *context)
  1409. {
  1410. int res;
  1411. /* Waitstream, with return in the case of a valid 1 digit extension */
  1412. /* in the current or specified context being pressed */
  1413. if (!context)
  1414. context = ast_channel_context(c);
  1415. res = waitstream_core(c, NULL, NULL, NULL, 0,
  1416. -1, -1, context, NULL /* no callback */);
  1417. return sanitize_waitstream_return(res);
  1418. }
  1419. /*
  1420. * if the file name is non-empty, try to play it.
  1421. * Return 0 if success, -1 if error, digit if interrupted by a digit.
  1422. * If digits == "" then we can simply check for non-zero.
  1423. */
  1424. int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
  1425. {
  1426. int res = 0;
  1427. if (!ast_strlen_zero(file)) {
  1428. res = ast_streamfile(chan, file, ast_channel_language(chan));
  1429. if (!res) {
  1430. res = ast_waitstream(chan, digits);
  1431. }
  1432. }
  1433. return res;
  1434. }
  1435. char *ast_format_str_reduce(char *fmts)
  1436. {
  1437. struct ast_format_def *f;
  1438. struct ast_format_def *fmts_ptr[AST_MAX_FORMATS];
  1439. char *fmts_str[AST_MAX_FORMATS];
  1440. char *stringp, *type;
  1441. char *orig = fmts;
  1442. int i, j, x, first, found = 0;
  1443. int len = strlen(fmts) + 1;
  1444. int res;
  1445. if (AST_RWLIST_RDLOCK(&formats)) {
  1446. ast_log(LOG_WARNING, "Unable to lock format list\n");
  1447. return NULL;
  1448. }
  1449. stringp = ast_strdupa(fmts);
  1450. for (x = 0; (type = strsep(&stringp, "|")) && x < AST_MAX_FORMATS; x++) {
  1451. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1452. if (exts_compare(f->exts, type)) {
  1453. found = 1;
  1454. break;
  1455. }
  1456. }
  1457. fmts_str[x] = type;
  1458. if (found) {
  1459. fmts_ptr[x] = f;
  1460. } else {
  1461. fmts_ptr[x] = NULL;
  1462. }
  1463. }
  1464. AST_RWLIST_UNLOCK(&formats);
  1465. first = 1;
  1466. for (i = 0; i < x; i++) {
  1467. /* ignore invalid entries */
  1468. if (!fmts_ptr[i]) {
  1469. ast_log(LOG_WARNING, "ignoring unknown format '%s'\n", fmts_str[i]);
  1470. continue;
  1471. }
  1472. /* special handling for the first entry */
  1473. if (first) {
  1474. res = snprintf(fmts, len, "%s", fmts_str[i]);
  1475. fmts += res;
  1476. len -= res;
  1477. first = 0;
  1478. continue;
  1479. }
  1480. found = 0;
  1481. for (j = 0; j < i; j++) {
  1482. /* this is a duplicate */
  1483. if (fmts_ptr[j] == fmts_ptr[i]) {
  1484. found = 1;
  1485. break;
  1486. }
  1487. }
  1488. if (!found) {
  1489. res = snprintf(fmts, len, "|%s", fmts_str[i]);
  1490. fmts += res;
  1491. len -= res;
  1492. }
  1493. }
  1494. if (first) {
  1495. ast_log(LOG_WARNING, "no known formats found in format list (%s)\n", orig);
  1496. return NULL;
  1497. }
  1498. return orig;
  1499. }
  1500. static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1501. {
  1502. #define FORMAT "%-10s %-10s %-20s\n"
  1503. #define FORMAT2 "%-10s %-10s %-20s\n"
  1504. struct ast_format_def *f;
  1505. int count_fmt = 0;
  1506. switch (cmd) {
  1507. case CLI_INIT:
  1508. e->command = "core show file formats";
  1509. e->usage =
  1510. "Usage: core show file formats\n"
  1511. " Displays currently registered file formats (if any).\n";
  1512. return NULL;
  1513. case CLI_GENERATE:
  1514. return NULL;
  1515. }
  1516. if (a->argc != 4)
  1517. return CLI_SHOWUSAGE;
  1518. ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
  1519. ast_cli(a->fd, FORMAT, "------", "----", "----------");
  1520. AST_RWLIST_RDLOCK(&formats);
  1521. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1522. ast_cli(a->fd, FORMAT2, ast_format_get_name(f->format), f->name, f->exts);
  1523. count_fmt++;
  1524. }
  1525. AST_RWLIST_UNLOCK(&formats);
  1526. ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
  1527. return CLI_SUCCESS;
  1528. #undef FORMAT
  1529. #undef FORMAT2
  1530. }
  1531. struct ast_format *ast_get_format_for_file_ext(const char *file_ext)
  1532. {
  1533. struct ast_format_def *f;
  1534. SCOPED_RDLOCK(lock, &formats.lock);
  1535. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1536. if (exts_compare(f->exts, file_ext)) {
  1537. return f->format;
  1538. }
  1539. }
  1540. return NULL;
  1541. }
  1542. static struct ast_cli_entry cli_file[] = {
  1543. AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
  1544. };
  1545. static void file_shutdown(void)
  1546. {
  1547. ast_cli_unregister_multiple(cli_file, ARRAY_LEN(cli_file));
  1548. STASIS_MESSAGE_TYPE_CLEANUP(ast_format_register_type);
  1549. STASIS_MESSAGE_TYPE_CLEANUP(ast_format_unregister_type);
  1550. }
  1551. int ast_file_init(void)
  1552. {
  1553. STASIS_MESSAGE_TYPE_INIT(ast_format_register_type);
  1554. STASIS_MESSAGE_TYPE_INIT(ast_format_unregister_type);
  1555. ast_cli_register_multiple(cli_file, ARRAY_LEN(cli_file));
  1556. ast_register_cleanup(file_shutdown);
  1557. return 0;
  1558. }