You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

570 lines
17KB

  1. /*
  2. * Tee pseudo-muxer
  3. * Copyright (c) 2012 Nicolas George
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public License
  9. * as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with FFmpeg; if not, write to the Free Software * Foundation, Inc.,
  19. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/avutil.h"
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/opt.h"
  24. #include "internal.h"
  25. #include "avformat.h"
  26. #include "avio_internal.h"
  27. typedef enum {
  28. ON_SLAVE_FAILURE_ABORT = 1,
  29. ON_SLAVE_FAILURE_IGNORE = 2
  30. } SlaveFailurePolicy;
  31. #define DEFAULT_SLAVE_FAILURE_POLICY ON_SLAVE_FAILURE_ABORT
  32. typedef struct {
  33. AVFormatContext *avf;
  34. AVBitStreamFilterContext **bsfs; ///< bitstream filters per stream
  35. SlaveFailurePolicy on_fail;
  36. /** map from input to output streams indexes,
  37. * disabled output streams are set to -1 */
  38. int *stream_map;
  39. int header_written;
  40. } TeeSlave;
  41. typedef struct TeeContext {
  42. const AVClass *class;
  43. unsigned nb_slaves;
  44. unsigned nb_alive;
  45. TeeSlave *slaves;
  46. } TeeContext;
  47. static const char *const slave_delim = "|";
  48. static const char *const slave_opt_open = "[";
  49. static const char *const slave_opt_close = "]";
  50. static const char *const slave_opt_delim = ":]"; /* must have the close too */
  51. static const char *const slave_bsfs_spec_sep = "/";
  52. static const char *const slave_select_sep = ",";
  53. static const AVClass tee_muxer_class = {
  54. .class_name = "Tee muxer",
  55. .item_name = av_default_item_name,
  56. .version = LIBAVUTIL_VERSION_INT,
  57. };
  58. static int parse_slave_options(void *log, char *slave,
  59. AVDictionary **options, char **filename)
  60. {
  61. const char *p;
  62. char *key, *val;
  63. int ret;
  64. if (!strspn(slave, slave_opt_open)) {
  65. *filename = slave;
  66. return 0;
  67. }
  68. p = slave + 1;
  69. if (strspn(p, slave_opt_close)) {
  70. *filename = (char *)p + 1;
  71. return 0;
  72. }
  73. while (1) {
  74. ret = av_opt_get_key_value(&p, "=", slave_opt_delim, 0, &key, &val);
  75. if (ret < 0) {
  76. av_log(log, AV_LOG_ERROR, "No option found near \"%s\"\n", p);
  77. goto fail;
  78. }
  79. ret = av_dict_set(options, key, val,
  80. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  81. if (ret < 0)
  82. goto fail;
  83. if (strspn(p, slave_opt_close))
  84. break;
  85. p++;
  86. }
  87. *filename = (char *)p + 1;
  88. return 0;
  89. fail:
  90. av_dict_free(options);
  91. return ret;
  92. }
  93. /**
  94. * Parse list of bitstream filters and add them to the list of filters
  95. * pointed to by bsfs.
  96. *
  97. * The list must be specified in the form:
  98. * BSFS ::= BSF[,BSFS]
  99. */
  100. static int parse_bsfs(void *log_ctx, const char *bsfs_spec,
  101. AVBitStreamFilterContext **bsfs)
  102. {
  103. char *bsf_name, *buf, *dup, *saveptr;
  104. int ret = 0;
  105. if (!(dup = buf = av_strdup(bsfs_spec)))
  106. return AVERROR(ENOMEM);
  107. while (bsf_name = av_strtok(buf, ",", &saveptr)) {
  108. AVBitStreamFilterContext *bsf = av_bitstream_filter_init(bsf_name);
  109. if (!bsf) {
  110. av_log(log_ctx, AV_LOG_ERROR,
  111. "Cannot initialize bitstream filter with name '%s', "
  112. "unknown filter or internal error happened\n",
  113. bsf_name);
  114. ret = AVERROR_UNKNOWN;
  115. goto end;
  116. }
  117. /* append bsf context to the list of bsf contexts */
  118. *bsfs = bsf;
  119. bsfs = &bsf->next;
  120. buf = NULL;
  121. }
  122. end:
  123. av_free(dup);
  124. return ret;
  125. }
  126. static inline int parse_slave_failure_policy_option(const char *opt, TeeSlave *tee_slave)
  127. {
  128. if (!opt) {
  129. tee_slave->on_fail = DEFAULT_SLAVE_FAILURE_POLICY;
  130. return 0;
  131. } else if (!av_strcasecmp("abort", opt)) {
  132. tee_slave->on_fail = ON_SLAVE_FAILURE_ABORT;
  133. return 0;
  134. } else if (!av_strcasecmp("ignore", opt)) {
  135. tee_slave->on_fail = ON_SLAVE_FAILURE_IGNORE;
  136. return 0;
  137. }
  138. /* Set failure behaviour to abort, so invalid option error will not be ignored */
  139. tee_slave->on_fail = ON_SLAVE_FAILURE_ABORT;
  140. return AVERROR(EINVAL);
  141. }
  142. static int close_slave(TeeSlave *tee_slave)
  143. {
  144. AVFormatContext *avf;
  145. unsigned i;
  146. int ret = 0;
  147. avf = tee_slave->avf;
  148. if (!avf)
  149. return 0;
  150. if (tee_slave->header_written)
  151. ret = av_write_trailer(avf);
  152. if (tee_slave->bsfs) {
  153. for (i = 0; i < avf->nb_streams; ++i) {
  154. AVBitStreamFilterContext *bsf_next, *bsf = tee_slave->bsfs[i];
  155. while (bsf) {
  156. bsf_next = bsf->next;
  157. av_bitstream_filter_close(bsf);
  158. bsf = bsf_next;
  159. }
  160. }
  161. }
  162. av_freep(&tee_slave->stream_map);
  163. av_freep(&tee_slave->bsfs);
  164. ff_format_io_close(avf, &avf->pb);
  165. avformat_free_context(avf);
  166. tee_slave->avf = NULL;
  167. return ret;
  168. }
  169. static void close_slaves(AVFormatContext *avf)
  170. {
  171. TeeContext *tee = avf->priv_data;
  172. unsigned i;
  173. for (i = 0; i < tee->nb_slaves; i++) {
  174. close_slave(&tee->slaves[i]);
  175. }
  176. av_freep(&tee->slaves);
  177. }
  178. static int open_slave(AVFormatContext *avf, char *slave, TeeSlave *tee_slave)
  179. {
  180. int i, ret;
  181. AVDictionary *options = NULL;
  182. AVDictionaryEntry *entry;
  183. char *filename;
  184. char *format = NULL, *select = NULL, *on_fail = NULL;
  185. AVFormatContext *avf2 = NULL;
  186. AVStream *st, *st2;
  187. int stream_count;
  188. int fullret;
  189. char *subselect = NULL, *next_subselect = NULL, *first_subselect = NULL, *tmp_select = NULL;
  190. if ((ret = parse_slave_options(avf, slave, &options, &filename)) < 0)
  191. return ret;
  192. #define STEAL_OPTION(option, field) do { \
  193. if ((entry = av_dict_get(options, option, NULL, 0))) { \
  194. field = entry->value; \
  195. entry->value = NULL; /* prevent it from being freed */ \
  196. av_dict_set(&options, option, NULL, 0); \
  197. } \
  198. } while (0)
  199. STEAL_OPTION("f", format);
  200. STEAL_OPTION("select", select);
  201. STEAL_OPTION("onfail", on_fail);
  202. ret = parse_slave_failure_policy_option(on_fail, tee_slave);
  203. if (ret < 0) {
  204. av_log(avf, AV_LOG_ERROR,
  205. "Invalid onfail option value, valid options are 'abort' and 'ignore'\n");
  206. goto end;
  207. }
  208. ret = avformat_alloc_output_context2(&avf2, NULL, format, filename);
  209. if (ret < 0)
  210. goto end;
  211. tee_slave->avf = avf2;
  212. av_dict_copy(&avf2->metadata, avf->metadata, 0);
  213. avf2->opaque = avf->opaque;
  214. avf2->io_open = avf->io_open;
  215. avf2->io_close = avf->io_close;
  216. tee_slave->stream_map = av_calloc(avf->nb_streams, sizeof(*tee_slave->stream_map));
  217. if (!tee_slave->stream_map) {
  218. ret = AVERROR(ENOMEM);
  219. goto end;
  220. }
  221. stream_count = 0;
  222. for (i = 0; i < avf->nb_streams; i++) {
  223. st = avf->streams[i];
  224. if (select) {
  225. tmp_select = av_strdup(select); // av_strtok is destructive so we regenerate it in each loop
  226. if (!tmp_select) {
  227. ret = AVERROR(ENOMEM);
  228. goto end;
  229. }
  230. fullret = 0;
  231. first_subselect = tmp_select;
  232. next_subselect = NULL;
  233. while (subselect = av_strtok(first_subselect, slave_select_sep, &next_subselect)) {
  234. first_subselect = NULL;
  235. ret = avformat_match_stream_specifier(avf, avf->streams[i], subselect);
  236. if (ret < 0) {
  237. av_log(avf, AV_LOG_ERROR,
  238. "Invalid stream specifier '%s' for output '%s'\n",
  239. subselect, slave);
  240. goto end;
  241. }
  242. if (ret != 0) {
  243. fullret = 1; // match
  244. break;
  245. }
  246. }
  247. av_freep(&tmp_select);
  248. if (fullret == 0) { /* no match */
  249. tee_slave->stream_map[i] = -1;
  250. continue;
  251. }
  252. }
  253. tee_slave->stream_map[i] = stream_count++;
  254. if (!(st2 = avformat_new_stream(avf2, NULL))) {
  255. ret = AVERROR(ENOMEM);
  256. goto end;
  257. }
  258. ret = ff_stream_encode_params_copy(st2, st);
  259. if (ret < 0)
  260. goto end;
  261. }
  262. ret = ff_format_output_open(avf2, filename, NULL);
  263. if (ret < 0) {
  264. av_log(avf, AV_LOG_ERROR, "Slave '%s': error opening: %s\n", slave,
  265. av_err2str(ret));
  266. goto end;
  267. }
  268. if ((ret = avformat_write_header(avf2, &options)) < 0) {
  269. av_log(avf, AV_LOG_ERROR, "Slave '%s': error writing header: %s\n",
  270. slave, av_err2str(ret));
  271. goto end;
  272. }
  273. tee_slave->header_written = 1;
  274. tee_slave->bsfs = av_calloc(avf2->nb_streams, sizeof(*tee_slave->bsfs));
  275. if (!tee_slave->bsfs) {
  276. ret = AVERROR(ENOMEM);
  277. goto end;
  278. }
  279. entry = NULL;
  280. while (entry = av_dict_get(options, "bsfs", NULL, AV_DICT_IGNORE_SUFFIX)) {
  281. const char *spec = entry->key + strlen("bsfs");
  282. if (*spec) {
  283. if (strspn(spec, slave_bsfs_spec_sep) != 1) {
  284. av_log(avf, AV_LOG_ERROR,
  285. "Specifier separator in '%s' is '%c', but only characters '%s' "
  286. "are allowed\n", entry->key, *spec, slave_bsfs_spec_sep);
  287. ret = AVERROR(EINVAL);
  288. goto end;
  289. }
  290. spec++; /* consume separator */
  291. }
  292. for (i = 0; i < avf2->nb_streams; i++) {
  293. ret = avformat_match_stream_specifier(avf2, avf2->streams[i], spec);
  294. if (ret < 0) {
  295. av_log(avf, AV_LOG_ERROR,
  296. "Invalid stream specifier '%s' in bsfs option '%s' for slave "
  297. "output '%s'\n", spec, entry->key, filename);
  298. goto end;
  299. }
  300. if (ret > 0) {
  301. av_log(avf, AV_LOG_DEBUG, "spec:%s bsfs:%s matches stream %d of slave "
  302. "output '%s'\n", spec, entry->value, i, filename);
  303. if (tee_slave->bsfs[i]) {
  304. av_log(avf, AV_LOG_WARNING,
  305. "Duplicate bsfs specification associated to stream %d of slave "
  306. "output '%s', filters will be ignored\n", i, filename);
  307. continue;
  308. }
  309. ret = parse_bsfs(avf, entry->value, &tee_slave->bsfs[i]);
  310. if (ret < 0) {
  311. av_log(avf, AV_LOG_ERROR,
  312. "Error parsing bitstream filter sequence '%s' associated to "
  313. "stream %d of slave output '%s'\n", entry->value, i, filename);
  314. goto end;
  315. }
  316. }
  317. }
  318. av_dict_set(&options, entry->key, NULL, 0);
  319. }
  320. if (options) {
  321. entry = NULL;
  322. while ((entry = av_dict_get(options, "", entry, AV_DICT_IGNORE_SUFFIX)))
  323. av_log(avf2, AV_LOG_ERROR, "Unknown option '%s'\n", entry->key);
  324. ret = AVERROR_OPTION_NOT_FOUND;
  325. goto end;
  326. }
  327. end:
  328. av_free(format);
  329. av_free(select);
  330. av_free(on_fail);
  331. av_dict_free(&options);
  332. av_freep(&tmp_select);
  333. return ret;
  334. }
  335. static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
  336. {
  337. int i;
  338. av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
  339. slave->avf->filename, slave->avf->oformat->name);
  340. for (i = 0; i < slave->avf->nb_streams; i++) {
  341. AVStream *st = slave->avf->streams[i];
  342. AVBitStreamFilterContext *bsf = slave->bsfs[i];
  343. av_log(log_ctx, log_level, " stream:%d codec:%s type:%s",
  344. i, avcodec_get_name(st->codecpar->codec_id),
  345. av_get_media_type_string(st->codecpar->codec_type));
  346. if (bsf) {
  347. av_log(log_ctx, log_level, " bsfs:");
  348. while (bsf) {
  349. av_log(log_ctx, log_level, "%s%s",
  350. bsf->filter->name, bsf->next ? "," : "");
  351. bsf = bsf->next;
  352. }
  353. }
  354. av_log(log_ctx, log_level, "\n");
  355. }
  356. }
  357. static int tee_process_slave_failure(AVFormatContext *avf, unsigned slave_idx, int err_n)
  358. {
  359. TeeContext *tee = avf->priv_data;
  360. TeeSlave *tee_slave = &tee->slaves[slave_idx];
  361. tee->nb_alive--;
  362. close_slave(tee_slave);
  363. if (!tee->nb_alive) {
  364. av_log(avf, AV_LOG_ERROR, "All tee outputs failed.\n");
  365. return err_n;
  366. } else if (tee_slave->on_fail == ON_SLAVE_FAILURE_ABORT) {
  367. av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed, aborting.\n", slave_idx);
  368. return err_n;
  369. } else {
  370. av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed: %s, continuing with %u/%u slaves.\n",
  371. slave_idx, av_err2str(err_n), tee->nb_alive, tee->nb_slaves);
  372. return 0;
  373. }
  374. }
  375. static int tee_write_header(AVFormatContext *avf)
  376. {
  377. TeeContext *tee = avf->priv_data;
  378. unsigned nb_slaves = 0, i;
  379. const char *filename = avf->filename;
  380. char **slaves = NULL;
  381. int ret;
  382. while (*filename) {
  383. char *slave = av_get_token(&filename, slave_delim);
  384. if (!slave) {
  385. ret = AVERROR(ENOMEM);
  386. goto fail;
  387. }
  388. ret = av_dynarray_add_nofree(&slaves, &nb_slaves, slave);
  389. if (ret < 0) {
  390. av_free(slave);
  391. goto fail;
  392. }
  393. if (strspn(filename, slave_delim))
  394. filename++;
  395. }
  396. if (!(tee->slaves = av_mallocz_array(nb_slaves, sizeof(*tee->slaves)))) {
  397. ret = AVERROR(ENOMEM);
  398. goto fail;
  399. }
  400. tee->nb_slaves = tee->nb_alive = nb_slaves;
  401. for (i = 0; i < nb_slaves; i++) {
  402. if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0) {
  403. ret = tee_process_slave_failure(avf, i, ret);
  404. if (ret < 0)
  405. goto fail;
  406. } else {
  407. log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
  408. }
  409. av_freep(&slaves[i]);
  410. }
  411. for (i = 0; i < avf->nb_streams; i++) {
  412. int j, mapped = 0;
  413. for (j = 0; j < tee->nb_slaves; j++)
  414. if (tee->slaves[j].avf)
  415. mapped += tee->slaves[j].stream_map[i] >= 0;
  416. if (!mapped)
  417. av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
  418. "to any slave.\n", i);
  419. }
  420. av_free(slaves);
  421. return 0;
  422. fail:
  423. for (i = 0; i < nb_slaves; i++)
  424. av_freep(&slaves[i]);
  425. close_slaves(avf);
  426. av_free(slaves);
  427. return ret;
  428. }
  429. static int tee_write_trailer(AVFormatContext *avf)
  430. {
  431. TeeContext *tee = avf->priv_data;
  432. int ret_all = 0, ret;
  433. unsigned i;
  434. for (i = 0; i < tee->nb_slaves; i++) {
  435. if ((ret = close_slave(&tee->slaves[i])) < 0) {
  436. ret = tee_process_slave_failure(avf, i, ret);
  437. if (!ret_all && ret < 0)
  438. ret_all = ret;
  439. }
  440. }
  441. av_freep(&tee->slaves);
  442. return ret_all;
  443. }
  444. static int tee_write_packet(AVFormatContext *avf, AVPacket *pkt)
  445. {
  446. TeeContext *tee = avf->priv_data;
  447. AVFormatContext *avf2;
  448. AVPacket pkt2;
  449. int ret_all = 0, ret;
  450. unsigned i, s;
  451. int s2;
  452. AVRational tb, tb2;
  453. for (i = 0; i < tee->nb_slaves; i++) {
  454. if (!(avf2 = tee->slaves[i].avf))
  455. continue;
  456. /* Flush slave if pkt is NULL*/
  457. if (!pkt) {
  458. ret = av_interleaved_write_frame(avf2, NULL);
  459. if (ret < 0) {
  460. ret = tee_process_slave_failure(avf, i, ret);
  461. if (!ret_all && ret < 0)
  462. ret_all = ret;
  463. }
  464. continue;
  465. }
  466. s = pkt->stream_index;
  467. s2 = tee->slaves[i].stream_map[s];
  468. if (s2 < 0)
  469. continue;
  470. memset(&pkt2, 0, sizeof(AVPacket));
  471. if ((ret = av_packet_ref(&pkt2, pkt)) < 0)
  472. if (!ret_all) {
  473. ret_all = ret;
  474. continue;
  475. }
  476. tb = avf ->streams[s ]->time_base;
  477. tb2 = avf2->streams[s2]->time_base;
  478. av_packet_rescale_ts(&pkt2, tb, tb2);
  479. pkt2.stream_index = s2;
  480. if ((ret = av_apply_bitstream_filters(avf2->streams[s2]->codec, &pkt2,
  481. tee->slaves[i].bsfs[s2])) < 0 ||
  482. (ret = av_interleaved_write_frame(avf2, &pkt2)) < 0) {
  483. ret = tee_process_slave_failure(avf, i, ret);
  484. if (!ret_all && ret < 0)
  485. ret_all = ret;
  486. }
  487. }
  488. return ret_all;
  489. }
  490. AVOutputFormat ff_tee_muxer = {
  491. .name = "tee",
  492. .long_name = NULL_IF_CONFIG_SMALL("Multiple muxer tee"),
  493. .priv_data_size = sizeof(TeeContext),
  494. .write_header = tee_write_header,
  495. .write_trailer = tee_write_trailer,
  496. .write_packet = tee_write_packet,
  497. .priv_class = &tee_muxer_class,
  498. .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
  499. };