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.

418 lines
14KB

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