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.

452 lines
15KB

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