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