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.

627 lines
20KB

  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. #include "tee_common.h"
  28. typedef enum {
  29. ON_SLAVE_FAILURE_ABORT = 1,
  30. ON_SLAVE_FAILURE_IGNORE = 2
  31. } SlaveFailurePolicy;
  32. #define DEFAULT_SLAVE_FAILURE_POLICY ON_SLAVE_FAILURE_ABORT
  33. typedef struct {
  34. AVFormatContext *avf;
  35. AVBSFContext **bsfs; ///< bitstream filters per stream
  36. SlaveFailurePolicy on_fail;
  37. int use_fifo;
  38. AVDictionary *fifo_options;
  39. /** map from input to output streams indexes,
  40. * disabled output streams are set to -1 */
  41. int *stream_map;
  42. int header_written;
  43. } TeeSlave;
  44. typedef struct TeeContext {
  45. const AVClass *class;
  46. unsigned nb_slaves;
  47. unsigned nb_alive;
  48. TeeSlave *slaves;
  49. int use_fifo;
  50. AVDictionary *fifo_options;
  51. char *fifo_options_str;
  52. } TeeContext;
  53. static const char *const slave_delim = "|";
  54. static const char *const slave_bsfs_spec_sep = "/";
  55. static const char *const slave_select_sep = ",";
  56. #define OFFSET(x) offsetof(TeeContext, x)
  57. static const AVOption options[] = {
  58. {"use_fifo", "Use fifo pseudo-muxer to separate actual muxers from encoder",
  59. OFFSET(use_fifo), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  60. {"fifo_options", "fifo pseudo-muxer options", OFFSET(fifo_options_str),
  61. AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM},
  62. {NULL}
  63. };
  64. static const AVClass tee_muxer_class = {
  65. .class_name = "Tee muxer",
  66. .item_name = av_default_item_name,
  67. .option = options,
  68. .version = LIBAVUTIL_VERSION_INT,
  69. };
  70. static inline int parse_slave_failure_policy_option(const char *opt, TeeSlave *tee_slave)
  71. {
  72. if (!opt) {
  73. tee_slave->on_fail = DEFAULT_SLAVE_FAILURE_POLICY;
  74. return 0;
  75. } else if (!av_strcasecmp("abort", opt)) {
  76. tee_slave->on_fail = ON_SLAVE_FAILURE_ABORT;
  77. return 0;
  78. } else if (!av_strcasecmp("ignore", opt)) {
  79. tee_slave->on_fail = ON_SLAVE_FAILURE_IGNORE;
  80. return 0;
  81. }
  82. /* Set failure behaviour to abort, so invalid option error will not be ignored */
  83. tee_slave->on_fail = ON_SLAVE_FAILURE_ABORT;
  84. return AVERROR(EINVAL);
  85. }
  86. static int parse_slave_fifo_options(const char *use_fifo,
  87. const char *fifo_options, TeeSlave *tee_slave)
  88. {
  89. int ret = 0;
  90. if (use_fifo) {
  91. /*TODO - change this to use proper function for parsing boolean
  92. * options when there is one */
  93. if (av_match_name(use_fifo, "true,y,yes,enable,enabled,on,1")) {
  94. tee_slave->use_fifo = 1;
  95. } else if (av_match_name(use_fifo, "false,n,no,disable,disabled,off,0")) {
  96. tee_slave->use_fifo = 0;
  97. } else {
  98. return AVERROR(EINVAL);
  99. }
  100. }
  101. if (fifo_options)
  102. ret = av_dict_parse_string(&tee_slave->fifo_options, fifo_options, "=", ":", 0);
  103. return ret;
  104. }
  105. static int close_slave(TeeSlave *tee_slave)
  106. {
  107. AVFormatContext *avf;
  108. unsigned i;
  109. int ret = 0;
  110. avf = tee_slave->avf;
  111. if (!avf)
  112. return 0;
  113. if (tee_slave->header_written)
  114. ret = av_write_trailer(avf);
  115. if (tee_slave->bsfs) {
  116. for (i = 0; i < avf->nb_streams; ++i)
  117. av_bsf_free(&tee_slave->bsfs[i]);
  118. }
  119. av_freep(&tee_slave->stream_map);
  120. av_freep(&tee_slave->bsfs);
  121. ff_format_io_close(avf, &avf->pb);
  122. avformat_free_context(avf);
  123. tee_slave->avf = NULL;
  124. return ret;
  125. }
  126. static void close_slaves(AVFormatContext *avf)
  127. {
  128. TeeContext *tee = avf->priv_data;
  129. unsigned i;
  130. for (i = 0; i < tee->nb_slaves; i++) {
  131. close_slave(&tee->slaves[i]);
  132. }
  133. av_freep(&tee->slaves);
  134. }
  135. static int open_slave(AVFormatContext *avf, char *slave, TeeSlave *tee_slave)
  136. {
  137. int i, ret;
  138. AVDictionary *options = NULL, *bsf_options = NULL;
  139. AVDictionaryEntry *entry;
  140. char *filename;
  141. char *format = NULL, *select = NULL, *on_fail = NULL;
  142. char *use_fifo = NULL, *fifo_options_str = NULL;
  143. AVFormatContext *avf2 = NULL;
  144. AVStream *st, *st2;
  145. int stream_count;
  146. int fullret;
  147. char *subselect = NULL, *next_subselect = NULL, *first_subselect = NULL, *tmp_select = NULL;
  148. if ((ret = ff_tee_parse_slave_options(avf, slave, &options, &filename)) < 0)
  149. return ret;
  150. #define STEAL_OPTION(option, field) do { \
  151. if ((entry = av_dict_get(options, option, NULL, 0))) { \
  152. field = entry->value; \
  153. entry->value = NULL; /* prevent it from being freed */ \
  154. av_dict_set(&options, option, NULL, 0); \
  155. } \
  156. } while (0)
  157. STEAL_OPTION("f", format);
  158. STEAL_OPTION("select", select);
  159. STEAL_OPTION("onfail", on_fail);
  160. STEAL_OPTION("use_fifo", use_fifo);
  161. STEAL_OPTION("fifo_options", fifo_options_str);
  162. entry = NULL;
  163. while ((entry = av_dict_get(options, "bsfs", entry, AV_DICT_IGNORE_SUFFIX))) {
  164. /* trim out strlen("bsfs") characters from key */
  165. av_dict_set(&bsf_options, entry->key + 4, entry->value, 0);
  166. av_dict_set(&options, entry->key, NULL, 0);
  167. }
  168. ret = parse_slave_failure_policy_option(on_fail, tee_slave);
  169. if (ret < 0) {
  170. av_log(avf, AV_LOG_ERROR,
  171. "Invalid onfail option value, valid options are 'abort' and 'ignore'\n");
  172. goto end;
  173. }
  174. ret = parse_slave_fifo_options(use_fifo, fifo_options_str, tee_slave);
  175. if (ret < 0) {
  176. av_log(avf, AV_LOG_ERROR, "Error parsing fifo options: %s\n", av_err2str(ret));
  177. goto end;
  178. }
  179. if (tee_slave->use_fifo) {
  180. if (options) {
  181. char *format_options_str = NULL;
  182. ret = av_dict_get_string(options, &format_options_str, '=', ':');
  183. if (ret < 0)
  184. goto end;
  185. ret = av_dict_set(&tee_slave->fifo_options, "format_opts", format_options_str,
  186. AV_DICT_DONT_STRDUP_VAL);
  187. if (ret < 0)
  188. goto end;
  189. }
  190. if (format) {
  191. ret = av_dict_set(&tee_slave->fifo_options, "fifo_format", format,
  192. AV_DICT_DONT_STRDUP_VAL);
  193. format = NULL;
  194. if (ret < 0)
  195. goto end;
  196. }
  197. av_dict_free(&options);
  198. options = tee_slave->fifo_options;
  199. }
  200. ret = avformat_alloc_output_context2(&avf2, NULL,
  201. tee_slave->use_fifo ? "fifo" :format, filename);
  202. if (ret < 0)
  203. goto end;
  204. tee_slave->avf = avf2;
  205. av_dict_copy(&avf2->metadata, avf->metadata, 0);
  206. avf2->opaque = avf->opaque;
  207. avf2->io_open = avf->io_open;
  208. avf2->io_close = avf->io_close;
  209. avf2->interrupt_callback = avf->interrupt_callback;
  210. avf2->flags = avf->flags;
  211. avf2->strict_std_compliance = avf->strict_std_compliance;
  212. tee_slave->stream_map = av_calloc(avf->nb_streams, sizeof(*tee_slave->stream_map));
  213. if (!tee_slave->stream_map) {
  214. ret = AVERROR(ENOMEM);
  215. goto end;
  216. }
  217. stream_count = 0;
  218. for (i = 0; i < avf->nb_streams; i++) {
  219. st = avf->streams[i];
  220. if (select) {
  221. tmp_select = av_strdup(select); // av_strtok is destructive so we regenerate it in each loop
  222. if (!tmp_select) {
  223. ret = AVERROR(ENOMEM);
  224. goto end;
  225. }
  226. fullret = 0;
  227. first_subselect = tmp_select;
  228. next_subselect = NULL;
  229. while (subselect = av_strtok(first_subselect, slave_select_sep, &next_subselect)) {
  230. first_subselect = NULL;
  231. ret = avformat_match_stream_specifier(avf, avf->streams[i], subselect);
  232. if (ret < 0) {
  233. av_log(avf, AV_LOG_ERROR,
  234. "Invalid stream specifier '%s' for output '%s'\n",
  235. subselect, slave);
  236. goto end;
  237. }
  238. if (ret != 0) {
  239. fullret = 1; // match
  240. break;
  241. }
  242. }
  243. av_freep(&tmp_select);
  244. if (fullret == 0) { /* no match */
  245. tee_slave->stream_map[i] = -1;
  246. continue;
  247. }
  248. }
  249. tee_slave->stream_map[i] = stream_count++;
  250. if (!(st2 = avformat_new_stream(avf2, NULL))) {
  251. ret = AVERROR(ENOMEM);
  252. goto end;
  253. }
  254. ret = ff_stream_encode_params_copy(st2, st);
  255. if (ret < 0)
  256. goto end;
  257. }
  258. ret = ff_format_output_open(avf2, filename, NULL);
  259. if (ret < 0) {
  260. av_log(avf, AV_LOG_ERROR, "Slave '%s': error opening: %s\n", slave,
  261. av_err2str(ret));
  262. goto end;
  263. }
  264. if ((ret = avformat_write_header(avf2, &options)) < 0) {
  265. av_log(avf, AV_LOG_ERROR, "Slave '%s': error writing header: %s\n",
  266. slave, av_err2str(ret));
  267. goto end;
  268. }
  269. tee_slave->header_written = 1;
  270. tee_slave->bsfs = av_calloc(avf2->nb_streams, sizeof(*tee_slave->bsfs));
  271. if (!tee_slave->bsfs) {
  272. ret = AVERROR(ENOMEM);
  273. goto end;
  274. }
  275. entry = NULL;
  276. while (entry = av_dict_get(bsf_options, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
  277. const char *spec = entry->key;
  278. if (*spec) {
  279. if (strspn(spec, slave_bsfs_spec_sep) != 1) {
  280. av_log(avf, AV_LOG_ERROR,
  281. "Specifier separator in '%s' is '%c', but only characters '%s' "
  282. "are allowed\n", entry->key, *spec, slave_bsfs_spec_sep);
  283. ret = AVERROR(EINVAL);
  284. goto end;
  285. }
  286. spec++; /* consume separator */
  287. }
  288. for (i = 0; i < avf2->nb_streams; i++) {
  289. ret = avformat_match_stream_specifier(avf2, avf2->streams[i], spec);
  290. if (ret < 0) {
  291. av_log(avf, AV_LOG_ERROR,
  292. "Invalid stream specifier '%s' in bsfs option '%s' for slave "
  293. "output '%s'\n", spec, entry->key, filename);
  294. goto end;
  295. }
  296. if (ret > 0) {
  297. av_log(avf, AV_LOG_DEBUG, "spec:%s bsfs:%s matches stream %d of slave "
  298. "output '%s'\n", spec, entry->value, i, filename);
  299. if (tee_slave->bsfs[i]) {
  300. av_log(avf, AV_LOG_WARNING,
  301. "Duplicate bsfs specification associated to stream %d of slave "
  302. "output '%s', filters will be ignored\n", i, filename);
  303. continue;
  304. }
  305. ret = av_bsf_list_parse_str(entry->value, &tee_slave->bsfs[i]);
  306. if (ret < 0) {
  307. av_log(avf, AV_LOG_ERROR,
  308. "Error parsing bitstream filter sequence '%s' associated to "
  309. "stream %d of slave output '%s'\n", entry->value, i, filename);
  310. goto end;
  311. }
  312. }
  313. }
  314. av_dict_set(&bsf_options, entry->key, NULL, 0);
  315. }
  316. for (i = 0; i < avf->nb_streams; i++){
  317. int target_stream = tee_slave->stream_map[i];
  318. if (target_stream < 0)
  319. continue;
  320. if (!tee_slave->bsfs[target_stream]) {
  321. /* Add pass-through bitstream filter */
  322. ret = av_bsf_get_null_filter(&tee_slave->bsfs[target_stream]);
  323. if (ret < 0) {
  324. av_log(avf, AV_LOG_ERROR,
  325. "Failed to create pass-through bitstream filter: %s\n",
  326. av_err2str(ret));
  327. goto end;
  328. }
  329. }
  330. tee_slave->bsfs[target_stream]->time_base_in = avf->streams[i]->time_base;
  331. ret = avcodec_parameters_copy(tee_slave->bsfs[target_stream]->par_in,
  332. avf->streams[i]->codecpar);
  333. if (ret < 0)
  334. goto end;
  335. ret = av_bsf_init(tee_slave->bsfs[target_stream]);
  336. if (ret < 0) {
  337. av_log(avf, AV_LOG_ERROR,
  338. "Failed to initialize bitstream filter(s): %s\n",
  339. av_err2str(ret));
  340. goto end;
  341. }
  342. }
  343. if (options) {
  344. entry = NULL;
  345. while ((entry = av_dict_get(options, "", entry, AV_DICT_IGNORE_SUFFIX)))
  346. av_log(avf2, AV_LOG_ERROR, "Unknown option '%s'\n", entry->key);
  347. ret = AVERROR_OPTION_NOT_FOUND;
  348. goto end;
  349. }
  350. end:
  351. av_free(format);
  352. av_free(select);
  353. av_free(on_fail);
  354. av_dict_free(&options);
  355. av_dict_free(&bsf_options);
  356. av_freep(&tmp_select);
  357. return ret;
  358. }
  359. static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
  360. {
  361. int i;
  362. av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
  363. slave->avf->url, slave->avf->oformat->name);
  364. for (i = 0; i < slave->avf->nb_streams; i++) {
  365. AVStream *st = slave->avf->streams[i];
  366. AVBSFContext *bsf = slave->bsfs[i];
  367. const char *bsf_name;
  368. av_log(log_ctx, log_level, " stream:%d codec:%s type:%s",
  369. i, avcodec_get_name(st->codecpar->codec_id),
  370. av_get_media_type_string(st->codecpar->codec_type));
  371. bsf_name = bsf->filter->priv_class ?
  372. bsf->filter->priv_class->item_name(bsf) : bsf->filter->name;
  373. av_log(log_ctx, log_level, " bsfs: %s\n", bsf_name);
  374. }
  375. }
  376. static int tee_process_slave_failure(AVFormatContext *avf, unsigned slave_idx, int err_n)
  377. {
  378. TeeContext *tee = avf->priv_data;
  379. TeeSlave *tee_slave = &tee->slaves[slave_idx];
  380. tee->nb_alive--;
  381. close_slave(tee_slave);
  382. if (!tee->nb_alive) {
  383. av_log(avf, AV_LOG_ERROR, "All tee outputs failed.\n");
  384. return err_n;
  385. } else if (tee_slave->on_fail == ON_SLAVE_FAILURE_ABORT) {
  386. av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed, aborting.\n", slave_idx);
  387. return err_n;
  388. } else {
  389. av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed: %s, continuing with %u/%u slaves.\n",
  390. slave_idx, av_err2str(err_n), tee->nb_alive, tee->nb_slaves);
  391. return 0;
  392. }
  393. }
  394. static int tee_write_header(AVFormatContext *avf)
  395. {
  396. TeeContext *tee = avf->priv_data;
  397. unsigned nb_slaves = 0, i;
  398. const char *filename = avf->url;
  399. char **slaves = NULL;
  400. int ret;
  401. while (*filename) {
  402. char *slave = av_get_token(&filename, slave_delim);
  403. if (!slave) {
  404. ret = AVERROR(ENOMEM);
  405. goto fail;
  406. }
  407. ret = av_dynarray_add_nofree(&slaves, &nb_slaves, slave);
  408. if (ret < 0) {
  409. av_free(slave);
  410. goto fail;
  411. }
  412. if (strspn(filename, slave_delim))
  413. filename++;
  414. }
  415. if (tee->fifo_options_str) {
  416. ret = av_dict_parse_string(&tee->fifo_options, tee->fifo_options_str, "=", ":", 0);
  417. if (ret < 0)
  418. goto fail;
  419. }
  420. if (!(tee->slaves = av_mallocz_array(nb_slaves, sizeof(*tee->slaves)))) {
  421. ret = AVERROR(ENOMEM);
  422. goto fail;
  423. }
  424. tee->nb_slaves = tee->nb_alive = nb_slaves;
  425. for (i = 0; i < nb_slaves; i++) {
  426. tee->slaves[i].use_fifo = tee->use_fifo;
  427. ret = av_dict_copy(&tee->slaves[i].fifo_options, tee->fifo_options, 0);
  428. if (ret < 0)
  429. goto fail;
  430. if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0) {
  431. ret = tee_process_slave_failure(avf, i, ret);
  432. if (ret < 0)
  433. goto fail;
  434. } else {
  435. log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
  436. }
  437. av_freep(&slaves[i]);
  438. }
  439. for (i = 0; i < avf->nb_streams; i++) {
  440. int j, mapped = 0;
  441. for (j = 0; j < tee->nb_slaves; j++)
  442. if (tee->slaves[j].avf)
  443. mapped += tee->slaves[j].stream_map[i] >= 0;
  444. if (!mapped)
  445. av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
  446. "to any slave.\n", i);
  447. }
  448. av_free(slaves);
  449. return 0;
  450. fail:
  451. for (i = 0; i < nb_slaves; i++)
  452. av_freep(&slaves[i]);
  453. close_slaves(avf);
  454. av_free(slaves);
  455. return ret;
  456. }
  457. static int tee_write_trailer(AVFormatContext *avf)
  458. {
  459. TeeContext *tee = avf->priv_data;
  460. int ret_all = 0, ret;
  461. unsigned i;
  462. for (i = 0; i < tee->nb_slaves; i++) {
  463. if ((ret = close_slave(&tee->slaves[i])) < 0) {
  464. ret = tee_process_slave_failure(avf, i, ret);
  465. if (!ret_all && ret < 0)
  466. ret_all = ret;
  467. }
  468. }
  469. av_freep(&tee->slaves);
  470. return ret_all;
  471. }
  472. static int tee_write_packet(AVFormatContext *avf, AVPacket *pkt)
  473. {
  474. TeeContext *tee = avf->priv_data;
  475. AVFormatContext *avf2;
  476. AVBSFContext *bsfs;
  477. AVPacket pkt2;
  478. int ret_all = 0, ret;
  479. unsigned i, s;
  480. int s2;
  481. for (i = 0; i < tee->nb_slaves; i++) {
  482. if (!(avf2 = tee->slaves[i].avf))
  483. continue;
  484. /* Flush slave if pkt is NULL*/
  485. if (!pkt) {
  486. ret = av_interleaved_write_frame(avf2, NULL);
  487. if (ret < 0) {
  488. ret = tee_process_slave_failure(avf, i, ret);
  489. if (!ret_all && ret < 0)
  490. ret_all = ret;
  491. }
  492. continue;
  493. }
  494. s = pkt->stream_index;
  495. s2 = tee->slaves[i].stream_map[s];
  496. if (s2 < 0)
  497. continue;
  498. memset(&pkt2, 0, sizeof(AVPacket));
  499. if ((ret = av_packet_ref(&pkt2, pkt)) < 0)
  500. if (!ret_all) {
  501. ret_all = ret;
  502. continue;
  503. }
  504. bsfs = tee->slaves[i].bsfs[s2];
  505. pkt2.stream_index = s2;
  506. ret = av_bsf_send_packet(bsfs, &pkt2);
  507. if (ret < 0) {
  508. av_log(avf, AV_LOG_ERROR, "Error while sending packet to bitstream filter: %s\n",
  509. av_err2str(ret));
  510. ret = tee_process_slave_failure(avf, i, ret);
  511. if (!ret_all && ret < 0)
  512. ret_all = ret;
  513. }
  514. while(1) {
  515. ret = av_bsf_receive_packet(bsfs, &pkt2);
  516. if (ret == AVERROR(EAGAIN)) {
  517. ret = 0;
  518. break;
  519. } else if (ret < 0) {
  520. break;
  521. }
  522. av_packet_rescale_ts(&pkt2, bsfs->time_base_out,
  523. avf2->streams[s2]->time_base);
  524. ret = av_interleaved_write_frame(avf2, &pkt2);
  525. if (ret < 0)
  526. break;
  527. };
  528. if (ret < 0) {
  529. ret = tee_process_slave_failure(avf, i, ret);
  530. if (!ret_all && ret < 0)
  531. ret_all = ret;
  532. }
  533. }
  534. return ret_all;
  535. }
  536. AVOutputFormat ff_tee_muxer = {
  537. .name = "tee",
  538. .long_name = NULL_IF_CONFIG_SMALL("Multiple muxer tee"),
  539. .priv_data_size = sizeof(TeeContext),
  540. .write_header = tee_write_header,
  541. .write_trailer = tee_write_trailer,
  542. .write_packet = tee_write_packet,
  543. .priv_class = &tee_muxer_class,
  544. .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
  545. };