avf_concat.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /*
  2. * Copyright (c) 2012 Nicolas George
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  14. * See the GNU Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with FFmpeg; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * concat audio-video filter
  23. */
  24. #include "libavutil/audioconvert.h"
  25. #include "libavutil/avassert.h"
  26. #include "libavutil/opt.h"
  27. #include "avfilter.h"
  28. #define FF_BUFQUEUE_SIZE 256
  29. #include "bufferqueue.h"
  30. #include "internal.h"
  31. #include "video.h"
  32. #include "audio.h"
  33. #define TYPE_ALL 2
  34. typedef struct {
  35. const AVClass *class;
  36. unsigned nb_streams[TYPE_ALL]; /**< number of out streams of each type */
  37. unsigned nb_segments;
  38. unsigned cur_idx; /**< index of the first input of current segment */
  39. int64_t delta_ts; /**< timestamp to add to produce output timestamps */
  40. unsigned nb_in_active; /**< number of active inputs in current segment */
  41. struct concat_in {
  42. int64_t pts;
  43. int64_t nb_frames;
  44. unsigned eof;
  45. struct FFBufQueue queue;
  46. } *in;
  47. } ConcatContext;
  48. #define OFFSET(x) offsetof(ConcatContext, x)
  49. #define A AV_OPT_FLAG_AUDIO_PARAM
  50. #define F AV_OPT_FLAG_FILTERING_PARAM
  51. #define V AV_OPT_FLAG_VIDEO_PARAM
  52. static const AVOption concat_options[] = {
  53. { "n", "specify the number of segments", OFFSET(nb_segments),
  54. AV_OPT_TYPE_INT, { .i64 = 2 }, 2, INT_MAX, V|A|F},
  55. { "v", "specify the number of video streams",
  56. OFFSET(nb_streams[AVMEDIA_TYPE_VIDEO]),
  57. AV_OPT_TYPE_INT, { .i64 = 1 }, 0, INT_MAX, V|F },
  58. { "a", "specify the number of audio streams",
  59. OFFSET(nb_streams[AVMEDIA_TYPE_AUDIO]),
  60. AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, A|F},
  61. { 0 }
  62. };
  63. AVFILTER_DEFINE_CLASS(concat);
  64. static int query_formats(AVFilterContext *ctx)
  65. {
  66. ConcatContext *cat = ctx->priv;
  67. unsigned type, nb_str, idx0 = 0, idx, str, seg;
  68. AVFilterFormats *formats, *rates;
  69. AVFilterChannelLayouts *layouts;
  70. for (type = 0; type < TYPE_ALL; type++) {
  71. nb_str = cat->nb_streams[type];
  72. for (str = 0; str < nb_str; str++) {
  73. idx = idx0;
  74. /* Set the output formats */
  75. formats = ff_all_formats(type);
  76. if (!formats)
  77. return AVERROR(ENOMEM);
  78. ff_formats_ref(formats, &ctx->outputs[idx]->in_formats);
  79. if (type == AVMEDIA_TYPE_AUDIO) {
  80. rates = ff_all_samplerates();
  81. if (!rates)
  82. return AVERROR(ENOMEM);
  83. ff_formats_ref(rates, &ctx->outputs[idx]->in_samplerates);
  84. layouts = ff_all_channel_layouts();
  85. if (!layouts)
  86. return AVERROR(ENOMEM);
  87. ff_channel_layouts_ref(layouts, &ctx->outputs[idx]->in_channel_layouts);
  88. }
  89. /* Set the same formats for each corresponding input */
  90. for (seg = 0; seg < cat->nb_segments; seg++) {
  91. ff_formats_ref(formats, &ctx->inputs[idx]->out_formats);
  92. if (type == AVMEDIA_TYPE_AUDIO) {
  93. ff_formats_ref(rates, &ctx->inputs[idx]->out_samplerates);
  94. ff_channel_layouts_ref(layouts, &ctx->inputs[idx]->out_channel_layouts);
  95. }
  96. idx += ctx->nb_outputs;
  97. }
  98. idx0++;
  99. }
  100. }
  101. return 0;
  102. }
  103. static int config_output(AVFilterLink *outlink)
  104. {
  105. AVFilterContext *ctx = outlink->src;
  106. ConcatContext *cat = ctx->priv;
  107. unsigned out_no = FF_OUTLINK_IDX(outlink);
  108. unsigned in_no = out_no, seg;
  109. AVFilterLink *inlink = ctx->inputs[in_no];
  110. /* enhancement: find a common one */
  111. outlink->time_base = AV_TIME_BASE_Q;
  112. outlink->w = inlink->w;
  113. outlink->h = inlink->h;
  114. outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
  115. outlink->format = inlink->format;
  116. for (seg = 1; seg < cat->nb_segments; seg++) {
  117. inlink = ctx->inputs[in_no += ctx->nb_outputs];
  118. /* possible enhancement: unsafe mode, do not check */
  119. if (outlink->w != inlink->w ||
  120. outlink->h != inlink->h ||
  121. outlink->sample_aspect_ratio.num != inlink->sample_aspect_ratio.num ||
  122. outlink->sample_aspect_ratio.den != inlink->sample_aspect_ratio.den) {
  123. av_log(ctx, AV_LOG_ERROR, "Input link %s parameters "
  124. "(size %dx%d, SAR %d:%d) do not match the corresponding "
  125. "output link %s parameters (%dx%d, SAR %d:%d)\n",
  126. ctx->input_pads[in_no].name, inlink->w, inlink->h,
  127. inlink->sample_aspect_ratio.num,
  128. inlink->sample_aspect_ratio.den,
  129. ctx->input_pads[out_no].name, outlink->w, outlink->h,
  130. outlink->sample_aspect_ratio.num,
  131. outlink->sample_aspect_ratio.den);
  132. return AVERROR(EINVAL);
  133. }
  134. }
  135. return 0;
  136. }
  137. static void push_frame(AVFilterContext *ctx, unsigned in_no,
  138. AVFilterBufferRef *buf)
  139. {
  140. ConcatContext *cat = ctx->priv;
  141. unsigned out_no = in_no % ctx->nb_outputs;
  142. AVFilterLink * inlink = ctx-> inputs[ in_no];
  143. AVFilterLink *outlink = ctx->outputs[out_no];
  144. struct concat_in *in = &cat->in[in_no];
  145. buf->pts = av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
  146. in->pts = buf->pts;
  147. in->nb_frames++;
  148. /* add duration to input PTS */
  149. if (inlink->sample_rate)
  150. /* use number of audio samples */
  151. in->pts += av_rescale_q(buf->audio->nb_samples,
  152. (AVRational){ 1, inlink->sample_rate },
  153. outlink->time_base);
  154. else if (in->nb_frames >= 2)
  155. /* use mean duration */
  156. in->pts = av_rescale(in->pts, in->nb_frames, in->nb_frames - 1);
  157. buf->pts += cat->delta_ts;
  158. switch (buf->type) {
  159. case AVMEDIA_TYPE_VIDEO:
  160. ff_start_frame(outlink, buf);
  161. ff_draw_slice(outlink, 0, outlink->h, 1);
  162. ff_end_frame(outlink);
  163. break;
  164. case AVMEDIA_TYPE_AUDIO:
  165. ff_filter_samples(outlink, buf);
  166. break;
  167. }
  168. }
  169. static void process_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
  170. {
  171. AVFilterContext *ctx = inlink->dst;
  172. ConcatContext *cat = ctx->priv;
  173. unsigned in_no = FF_INLINK_IDX(inlink);
  174. if (in_no < cat->cur_idx) {
  175. av_log(ctx, AV_LOG_ERROR, "Frame after EOF on input %s\n",
  176. ctx->input_pads[in_no].name);
  177. avfilter_unref_buffer(buf);
  178. } else if (in_no >= cat->cur_idx + ctx->nb_outputs) {
  179. ff_bufqueue_add(ctx, &cat->in[in_no].queue, buf);
  180. } else {
  181. push_frame(ctx, in_no, buf);
  182. }
  183. }
  184. static AVFilterBufferRef *get_video_buffer(AVFilterLink *inlink, int perms,
  185. int w, int h)
  186. {
  187. AVFilterContext *ctx = inlink->dst;
  188. unsigned in_no = FF_INLINK_IDX(inlink);
  189. AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
  190. return ff_get_video_buffer(outlink, perms, w, h);
  191. }
  192. static AVFilterBufferRef *get_audio_buffer(AVFilterLink *inlink, int perms,
  193. int nb_samples)
  194. {
  195. AVFilterContext *ctx = inlink->dst;
  196. unsigned in_no = FF_INLINK_IDX(inlink);
  197. AVFilterLink *outlink = ctx->outputs[in_no % ctx->nb_outputs];
  198. return ff_get_audio_buffer(outlink, perms, nb_samples);
  199. }
  200. static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
  201. {
  202. return 0;
  203. }
  204. static int draw_slice(AVFilterLink *inlink, int y, int h, int dir)
  205. {
  206. return 0;
  207. }
  208. static int end_frame(AVFilterLink *inlink)
  209. {
  210. process_frame(inlink, inlink->cur_buf);
  211. inlink->cur_buf = NULL;
  212. return 0;
  213. }
  214. static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
  215. {
  216. process_frame(inlink, buf);
  217. return 0; /* enhancement: handle error return */
  218. }
  219. static void close_input(AVFilterContext *ctx, unsigned in_no)
  220. {
  221. ConcatContext *cat = ctx->priv;
  222. cat->in[in_no].eof = 1;
  223. cat->nb_in_active--;
  224. av_log(ctx, AV_LOG_VERBOSE, "EOF on %s, %d streams left in segment.\n",
  225. ctx->input_pads[in_no].name, cat->nb_in_active);
  226. }
  227. static void find_next_delta_ts(AVFilterContext *ctx)
  228. {
  229. ConcatContext *cat = ctx->priv;
  230. unsigned i = cat->cur_idx;
  231. unsigned imax = i + ctx->nb_outputs;
  232. int64_t pts;
  233. pts = cat->in[i++].pts;
  234. for (; i < imax; i++)
  235. pts = FFMAX(pts, cat->in[i].pts);
  236. cat->delta_ts += pts;
  237. }
  238. static void send_silence(AVFilterContext *ctx, unsigned in_no, unsigned out_no)
  239. {
  240. ConcatContext *cat = ctx->priv;
  241. AVFilterLink *outlink = ctx->outputs[out_no];
  242. int64_t base_pts = cat->in[in_no].pts + cat->delta_ts;
  243. int64_t nb_samples, sent = 0;
  244. int frame_nb_samples;
  245. AVRational rate_tb = { 1, ctx->inputs[in_no]->sample_rate };
  246. AVFilterBufferRef *buf;
  247. int nb_channels = av_get_channel_layout_nb_channels(outlink->channel_layout);
  248. if (!rate_tb.den)
  249. return;
  250. nb_samples = av_rescale_q(cat->delta_ts - base_pts,
  251. outlink->time_base, rate_tb);
  252. frame_nb_samples = FFMAX(9600, rate_tb.den / 5); /* arbitrary */
  253. while (nb_samples) {
  254. frame_nb_samples = FFMIN(frame_nb_samples, nb_samples);
  255. buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, frame_nb_samples);
  256. if (!buf)
  257. return;
  258. av_samples_set_silence(buf->extended_data, 0, frame_nb_samples,
  259. nb_channels, outlink->format);
  260. buf->pts = base_pts + av_rescale_q(sent, rate_tb, outlink->time_base);
  261. ff_filter_samples(outlink, buf);
  262. sent += frame_nb_samples;
  263. nb_samples -= frame_nb_samples;
  264. }
  265. }
  266. static void flush_segment(AVFilterContext *ctx)
  267. {
  268. ConcatContext *cat = ctx->priv;
  269. unsigned str, str_max;
  270. find_next_delta_ts(ctx);
  271. cat->cur_idx += ctx->nb_outputs;
  272. cat->nb_in_active = ctx->nb_outputs;
  273. av_log(ctx, AV_LOG_VERBOSE, "Segment finished at pts=%"PRId64"\n",
  274. cat->delta_ts);
  275. if (cat->cur_idx < ctx->nb_inputs) {
  276. /* pad audio streams with silence */
  277. str = cat->nb_streams[AVMEDIA_TYPE_VIDEO];
  278. str_max = str + cat->nb_streams[AVMEDIA_TYPE_AUDIO];
  279. for (; str < str_max; str++)
  280. send_silence(ctx, cat->cur_idx - ctx->nb_outputs + str, str);
  281. /* flush queued buffers */
  282. /* possible enhancement: flush in PTS order */
  283. str_max = cat->cur_idx + ctx->nb_outputs;
  284. for (str = cat->cur_idx; str < str_max; str++)
  285. while (cat->in[str].queue.available)
  286. push_frame(ctx, str, ff_bufqueue_get(&cat->in[str].queue));
  287. }
  288. }
  289. static int request_frame(AVFilterLink *outlink)
  290. {
  291. AVFilterContext *ctx = outlink->src;
  292. ConcatContext *cat = ctx->priv;
  293. unsigned out_no = FF_OUTLINK_IDX(outlink);
  294. unsigned in_no = out_no + cat->cur_idx;
  295. unsigned str, str_max;
  296. int ret;
  297. while (1) {
  298. if (in_no >= ctx->nb_inputs)
  299. return AVERROR_EOF;
  300. if (!cat->in[in_no].eof) {
  301. ret = ff_request_frame(ctx->inputs[in_no]);
  302. if (ret != AVERROR_EOF)
  303. return ret;
  304. close_input(ctx, in_no);
  305. }
  306. /* cycle on all inputs to finish the segment */
  307. /* possible enhancement: request in PTS order */
  308. str_max = cat->cur_idx + ctx->nb_outputs - 1;
  309. for (str = cat->cur_idx; cat->nb_in_active;
  310. str = str == str_max ? cat->cur_idx : str + 1) {
  311. if (cat->in[str].eof)
  312. continue;
  313. ret = ff_request_frame(ctx->inputs[str]);
  314. if (ret == AVERROR_EOF)
  315. close_input(ctx, str);
  316. else if (ret < 0)
  317. return ret;
  318. }
  319. flush_segment(ctx);
  320. in_no += ctx->nb_outputs;
  321. }
  322. }
  323. static av_cold int init(AVFilterContext *ctx, const char *args)
  324. {
  325. ConcatContext *cat = ctx->priv;
  326. int ret;
  327. unsigned seg, type, str;
  328. char name[32];
  329. cat->class = &concat_class;
  330. av_opt_set_defaults(cat);
  331. ret = av_set_options_string(cat, args, "=", ":");
  332. if (ret < 0) {
  333. av_log(ctx, AV_LOG_ERROR, "Error parsing options: '%s'\n", args);
  334. return ret;
  335. }
  336. /* create input pads */
  337. for (seg = 0; seg < cat->nb_segments; seg++) {
  338. for (type = 0; type < TYPE_ALL; type++) {
  339. for (str = 0; str < cat->nb_streams[type]; str++) {
  340. AVFilterPad pad = {
  341. .type = type,
  342. .min_perms = AV_PERM_READ | AV_PERM_PRESERVE,
  343. .get_video_buffer = get_video_buffer,
  344. .get_audio_buffer = get_audio_buffer,
  345. };
  346. snprintf(name, sizeof(name), "in%d:%c%d", seg, "va"[type], str);
  347. pad.name = av_strdup(name);
  348. if (type == AVMEDIA_TYPE_VIDEO) {
  349. pad.start_frame = start_frame;
  350. pad.draw_slice = draw_slice;
  351. pad.end_frame = end_frame;
  352. } else {
  353. pad.filter_samples = filter_samples;
  354. }
  355. ff_insert_inpad(ctx, ctx->nb_inputs, &pad);
  356. }
  357. }
  358. }
  359. /* create output pads */
  360. for (type = 0; type < TYPE_ALL; type++) {
  361. for (str = 0; str < cat->nb_streams[type]; str++) {
  362. AVFilterPad pad = {
  363. .type = type,
  364. .config_props = config_output,
  365. .request_frame = request_frame,
  366. };
  367. snprintf(name, sizeof(name), "out:%c%d", "va"[type], str);
  368. pad.name = av_strdup(name);
  369. ff_insert_outpad(ctx, ctx->nb_outputs, &pad);
  370. }
  371. }
  372. cat->in = av_calloc(ctx->nb_inputs, sizeof(*cat->in));
  373. if (!cat->in)
  374. return AVERROR(ENOMEM);
  375. cat->nb_in_active = ctx->nb_outputs;
  376. return 0;
  377. }
  378. static av_cold void uninit(AVFilterContext *ctx)
  379. {
  380. ConcatContext *cat = ctx->priv;
  381. unsigned i;
  382. for (i = 0; i < ctx->nb_inputs; i++) {
  383. av_freep(&ctx->input_pads[i].name);
  384. ff_bufqueue_discard_all(&cat->in[i].queue);
  385. }
  386. for (i = 0; i < ctx->nb_outputs; i++)
  387. av_freep(&ctx->output_pads[i].name);
  388. av_free(cat->in);
  389. }
  390. AVFilter avfilter_avf_concat = {
  391. .name = "concat",
  392. .description = NULL_IF_CONFIG_SMALL("Concatenate audio and video streams."),
  393. .init = init,
  394. .uninit = uninit,
  395. .query_formats = query_formats,
  396. .priv_size = sizeof(ConcatContext),
  397. .inputs = (const AVFilterPad[]) { { .name = NULL } },
  398. .outputs = (const AVFilterPad[]) { { .name = NULL } },
  399. .priv_class = &concat_class,
  400. };