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.

530 lines
16KB

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