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.

573 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. if (!(avf2->oformat->flags & AVFMT_NOFILE)) {
  263. if ((ret = avf2->io_open(avf2, &avf2->pb, filename, AVIO_FLAG_WRITE, NULL)) < 0) {
  264. av_log(avf, AV_LOG_ERROR, "Slave '%s': error opening: %s\n",
  265. slave, av_err2str(ret));
  266. goto end;
  267. }
  268. }
  269. if ((ret = avformat_write_header(avf2, &options)) < 0) {
  270. av_log(avf, AV_LOG_ERROR, "Slave '%s': error writing header: %s\n",
  271. slave, av_err2str(ret));
  272. goto end;
  273. }
  274. tee_slave->header_written = 1;
  275. tee_slave->bsfs = av_calloc(avf2->nb_streams, sizeof(*tee_slave->bsfs));
  276. if (!tee_slave->bsfs) {
  277. ret = AVERROR(ENOMEM);
  278. goto end;
  279. }
  280. entry = NULL;
  281. while (entry = av_dict_get(options, "bsfs", NULL, AV_DICT_IGNORE_SUFFIX)) {
  282. const char *spec = entry->key + strlen("bsfs");
  283. if (*spec) {
  284. if (strspn(spec, slave_bsfs_spec_sep) != 1) {
  285. av_log(avf, AV_LOG_ERROR,
  286. "Specifier separator in '%s' is '%c', but only characters '%s' "
  287. "are allowed\n", entry->key, *spec, slave_bsfs_spec_sep);
  288. ret = AVERROR(EINVAL);
  289. goto end;
  290. }
  291. spec++; /* consume separator */
  292. }
  293. for (i = 0; i < avf2->nb_streams; i++) {
  294. ret = avformat_match_stream_specifier(avf2, avf2->streams[i], spec);
  295. if (ret < 0) {
  296. av_log(avf, AV_LOG_ERROR,
  297. "Invalid stream specifier '%s' in bsfs option '%s' for slave "
  298. "output '%s'\n", spec, entry->key, filename);
  299. goto end;
  300. }
  301. if (ret > 0) {
  302. av_log(avf, AV_LOG_DEBUG, "spec:%s bsfs:%s matches stream %d of slave "
  303. "output '%s'\n", spec, entry->value, i, filename);
  304. if (tee_slave->bsfs[i]) {
  305. av_log(avf, AV_LOG_WARNING,
  306. "Duplicate bsfs specification associated to stream %d of slave "
  307. "output '%s', filters will be ignored\n", i, filename);
  308. continue;
  309. }
  310. ret = parse_bsfs(avf, entry->value, &tee_slave->bsfs[i]);
  311. if (ret < 0) {
  312. av_log(avf, AV_LOG_ERROR,
  313. "Error parsing bitstream filter sequence '%s' associated to "
  314. "stream %d of slave output '%s'\n", entry->value, i, filename);
  315. goto end;
  316. }
  317. }
  318. }
  319. av_dict_set(&options, entry->key, NULL, 0);
  320. }
  321. if (options) {
  322. entry = NULL;
  323. while ((entry = av_dict_get(options, "", entry, AV_DICT_IGNORE_SUFFIX)))
  324. av_log(avf2, AV_LOG_ERROR, "Unknown option '%s'\n", entry->key);
  325. ret = AVERROR_OPTION_NOT_FOUND;
  326. goto end;
  327. }
  328. end:
  329. av_free(format);
  330. av_free(select);
  331. av_free(on_fail);
  332. av_dict_free(&options);
  333. av_freep(&tmp_select);
  334. return ret;
  335. }
  336. static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
  337. {
  338. int i;
  339. av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
  340. slave->avf->filename, slave->avf->oformat->name);
  341. for (i = 0; i < slave->avf->nb_streams; i++) {
  342. AVStream *st = slave->avf->streams[i];
  343. AVBitStreamFilterContext *bsf = slave->bsfs[i];
  344. av_log(log_ctx, log_level, " stream:%d codec:%s type:%s",
  345. i, avcodec_get_name(st->codecpar->codec_id),
  346. av_get_media_type_string(st->codecpar->codec_type));
  347. if (bsf) {
  348. av_log(log_ctx, log_level, " bsfs:");
  349. while (bsf) {
  350. av_log(log_ctx, log_level, "%s%s",
  351. bsf->filter->name, bsf->next ? "," : "");
  352. bsf = bsf->next;
  353. }
  354. }
  355. av_log(log_ctx, log_level, "\n");
  356. }
  357. }
  358. static int tee_process_slave_failure(AVFormatContext *avf, unsigned slave_idx, int err_n)
  359. {
  360. TeeContext *tee = avf->priv_data;
  361. TeeSlave *tee_slave = &tee->slaves[slave_idx];
  362. tee->nb_alive--;
  363. close_slave(tee_slave);
  364. if (!tee->nb_alive) {
  365. av_log(avf, AV_LOG_ERROR, "All tee outputs failed.\n");
  366. return err_n;
  367. } else if (tee_slave->on_fail == ON_SLAVE_FAILURE_ABORT) {
  368. av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed, aborting.\n", slave_idx);
  369. return err_n;
  370. } else {
  371. av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed: %s, continuing with %u/%u slaves.\n",
  372. slave_idx, av_err2str(err_n), tee->nb_alive, tee->nb_slaves);
  373. return 0;
  374. }
  375. }
  376. static int tee_write_header(AVFormatContext *avf)
  377. {
  378. TeeContext *tee = avf->priv_data;
  379. unsigned nb_slaves = 0, i;
  380. const char *filename = avf->filename;
  381. char **slaves = NULL;
  382. int ret;
  383. while (*filename) {
  384. char *slave = av_get_token(&filename, slave_delim);
  385. if (!slave) {
  386. ret = AVERROR(ENOMEM);
  387. goto fail;
  388. }
  389. ret = av_dynarray_add_nofree(&slaves, &nb_slaves, slave);
  390. if (ret < 0) {
  391. av_free(slave);
  392. goto fail;
  393. }
  394. if (strspn(filename, slave_delim))
  395. filename++;
  396. }
  397. if (!(tee->slaves = av_mallocz_array(nb_slaves, sizeof(*tee->slaves)))) {
  398. ret = AVERROR(ENOMEM);
  399. goto fail;
  400. }
  401. tee->nb_slaves = tee->nb_alive = nb_slaves;
  402. for (i = 0; i < nb_slaves; i++) {
  403. if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0) {
  404. ret = tee_process_slave_failure(avf, i, ret);
  405. if (ret < 0)
  406. goto fail;
  407. } else {
  408. log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
  409. }
  410. av_freep(&slaves[i]);
  411. }
  412. for (i = 0; i < avf->nb_streams; i++) {
  413. int j, mapped = 0;
  414. for (j = 0; j < tee->nb_slaves; j++)
  415. if (tee->slaves[j].avf)
  416. mapped += tee->slaves[j].stream_map[i] >= 0;
  417. if (!mapped)
  418. av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
  419. "to any slave.\n", i);
  420. }
  421. av_free(slaves);
  422. return 0;
  423. fail:
  424. for (i = 0; i < nb_slaves; i++)
  425. av_freep(&slaves[i]);
  426. close_slaves(avf);
  427. av_free(slaves);
  428. return ret;
  429. }
  430. static int tee_write_trailer(AVFormatContext *avf)
  431. {
  432. TeeContext *tee = avf->priv_data;
  433. int ret_all = 0, ret;
  434. unsigned i;
  435. for (i = 0; i < tee->nb_slaves; i++) {
  436. if ((ret = close_slave(&tee->slaves[i])) < 0) {
  437. ret = tee_process_slave_failure(avf, i, ret);
  438. if (!ret_all && ret < 0)
  439. ret_all = ret;
  440. }
  441. }
  442. av_freep(&tee->slaves);
  443. return ret_all;
  444. }
  445. static int tee_write_packet(AVFormatContext *avf, AVPacket *pkt)
  446. {
  447. TeeContext *tee = avf->priv_data;
  448. AVFormatContext *avf2;
  449. AVPacket pkt2;
  450. int ret_all = 0, ret;
  451. unsigned i, s;
  452. int s2;
  453. AVRational tb, tb2;
  454. for (i = 0; i < tee->nb_slaves; i++) {
  455. if (!(avf2 = tee->slaves[i].avf))
  456. continue;
  457. /* Flush slave if pkt is NULL*/
  458. if (!pkt) {
  459. ret = av_interleaved_write_frame(avf2, NULL);
  460. if (ret < 0) {
  461. ret = tee_process_slave_failure(avf, i, ret);
  462. if (!ret_all && ret < 0)
  463. ret_all = ret;
  464. }
  465. continue;
  466. }
  467. s = pkt->stream_index;
  468. s2 = tee->slaves[i].stream_map[s];
  469. if (s2 < 0)
  470. continue;
  471. memset(&pkt2, 0, sizeof(AVPacket));
  472. if ((ret = av_packet_ref(&pkt2, pkt)) < 0)
  473. if (!ret_all) {
  474. ret_all = ret;
  475. continue;
  476. }
  477. tb = avf ->streams[s ]->time_base;
  478. tb2 = avf2->streams[s2]->time_base;
  479. pkt2.pts = av_rescale_q(pkt->pts, tb, tb2);
  480. pkt2.dts = av_rescale_q(pkt->dts, tb, tb2);
  481. pkt2.duration = av_rescale_q(pkt->duration, tb, tb2);
  482. pkt2.stream_index = s2;
  483. if ((ret = av_apply_bitstream_filters(avf2->streams[s2]->codec, &pkt2,
  484. tee->slaves[i].bsfs[s2])) < 0 ||
  485. (ret = av_interleaved_write_frame(avf2, &pkt2)) < 0) {
  486. ret = tee_process_slave_failure(avf, i, ret);
  487. if (!ret_all && ret < 0)
  488. ret_all = ret;
  489. }
  490. }
  491. return ret_all;
  492. }
  493. AVOutputFormat ff_tee_muxer = {
  494. .name = "tee",
  495. .long_name = NULL_IF_CONFIG_SMALL("Multiple muxer tee"),
  496. .priv_data_size = sizeof(TeeContext),
  497. .write_header = tee_write_header,
  498. .write_trailer = tee_write_trailer,
  499. .write_packet = tee_write_packet,
  500. .priv_class = &tee_muxer_class,
  501. .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
  502. };