ffmpeg_filter.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. /*
  2. * ffmpeg filter configuration
  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. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <stdint.h>
  21. #include "ffmpeg.h"
  22. #include "libavfilter/avfilter.h"
  23. #include "libavfilter/buffersink.h"
  24. #include "libavresample/avresample.h"
  25. #include "libavutil/avassert.h"
  26. #include "libavutil/avstring.h"
  27. #include "libavutil/bprint.h"
  28. #include "libavutil/channel_layout.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/pixdesc.h"
  31. #include "libavutil/pixfmt.h"
  32. #include "libavutil/imgutils.h"
  33. #include "libavutil/samplefmt.h"
  34. enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodecContext *enc_ctx, AVCodec *codec, enum AVPixelFormat target)
  35. {
  36. if (codec && codec->pix_fmts) {
  37. const enum AVPixelFormat *p = codec->pix_fmts;
  38. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(target);
  39. int has_alpha = desc ? desc->nb_components % 2 == 0 : 0;
  40. enum AVPixelFormat best= AV_PIX_FMT_NONE;
  41. static const enum AVPixelFormat mjpeg_formats[] =
  42. { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
  43. static const enum AVPixelFormat ljpeg_formats[] =
  44. { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
  45. AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
  46. if (enc_ctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
  47. if (enc_ctx->codec_id == AV_CODEC_ID_MJPEG) {
  48. p = mjpeg_formats;
  49. } else if (enc_ctx->codec_id == AV_CODEC_ID_LJPEG) {
  50. p =ljpeg_formats;
  51. }
  52. }
  53. for (; *p != AV_PIX_FMT_NONE; p++) {
  54. best= avcodec_find_best_pix_fmt_of_2(best, *p, target, has_alpha, NULL);
  55. if (*p == target)
  56. break;
  57. }
  58. if (*p == AV_PIX_FMT_NONE) {
  59. if (target != AV_PIX_FMT_NONE)
  60. av_log(NULL, AV_LOG_WARNING,
  61. "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
  62. av_get_pix_fmt_name(target),
  63. codec->name,
  64. av_get_pix_fmt_name(best));
  65. return best;
  66. }
  67. }
  68. return target;
  69. }
  70. void choose_sample_fmt(AVStream *st, AVCodec *codec)
  71. {
  72. if (codec && codec->sample_fmts) {
  73. const enum AVSampleFormat *p = codec->sample_fmts;
  74. for (; *p != -1; p++) {
  75. if (*p == st->codec->sample_fmt)
  76. break;
  77. }
  78. if (*p == -1) {
  79. if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
  80. av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
  81. if(av_get_sample_fmt_name(st->codec->sample_fmt))
  82. av_log(NULL, AV_LOG_WARNING,
  83. "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
  84. av_get_sample_fmt_name(st->codec->sample_fmt),
  85. codec->name,
  86. av_get_sample_fmt_name(codec->sample_fmts[0]));
  87. st->codec->sample_fmt = codec->sample_fmts[0];
  88. }
  89. }
  90. }
  91. static char *choose_pix_fmts(OutputStream *ost)
  92. {
  93. AVDictionaryEntry *strict_dict = av_dict_get(ost->encoder_opts, "strict", NULL, 0);
  94. if (strict_dict)
  95. // used by choose_pixel_fmt() and below
  96. av_opt_set(ost->enc_ctx, "strict", strict_dict->value, 0);
  97. if (ost->keep_pix_fmt) {
  98. if (ost->filter)
  99. avfilter_graph_set_auto_convert(ost->filter->graph->graph,
  100. AVFILTER_AUTO_CONVERT_NONE);
  101. if (ost->enc_ctx->pix_fmt == AV_PIX_FMT_NONE)
  102. return NULL;
  103. return av_strdup(av_get_pix_fmt_name(ost->enc_ctx->pix_fmt));
  104. }
  105. if (ost->enc_ctx->pix_fmt != AV_PIX_FMT_NONE) {
  106. return av_strdup(av_get_pix_fmt_name(choose_pixel_fmt(ost->st, ost->enc_ctx, ost->enc, ost->enc_ctx->pix_fmt)));
  107. } else if (ost->enc && ost->enc->pix_fmts) {
  108. const enum AVPixelFormat *p;
  109. AVIOContext *s = NULL;
  110. uint8_t *ret;
  111. int len;
  112. if (avio_open_dyn_buf(&s) < 0)
  113. exit_program(1);
  114. p = ost->enc->pix_fmts;
  115. if (ost->enc_ctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
  116. if (ost->enc_ctx->codec_id == AV_CODEC_ID_MJPEG) {
  117. p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE };
  118. } else if (ost->enc_ctx->codec_id == AV_CODEC_ID_LJPEG) {
  119. p = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUV420P,
  120. AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
  121. }
  122. }
  123. for (; *p != AV_PIX_FMT_NONE; p++) {
  124. const char *name = av_get_pix_fmt_name(*p);
  125. avio_printf(s, "%s|", name);
  126. }
  127. len = avio_close_dyn_buf(s, &ret);
  128. ret[len - 1] = 0;
  129. return ret;
  130. } else
  131. return NULL;
  132. }
  133. /* Define a function for building a string containing a list of
  134. * allowed formats. */
  135. #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name) \
  136. static char *choose_ ## var ## s(OutputStream *ost) \
  137. { \
  138. if (ost->enc_ctx->var != none) { \
  139. get_name(ost->enc_ctx->var); \
  140. return av_strdup(name); \
  141. } else if (ost->enc && ost->enc->supported_list) { \
  142. const type *p; \
  143. AVIOContext *s = NULL; \
  144. uint8_t *ret; \
  145. int len; \
  146. \
  147. if (avio_open_dyn_buf(&s) < 0) \
  148. exit_program(1); \
  149. \
  150. for (p = ost->enc->supported_list; *p != none; p++) { \
  151. get_name(*p); \
  152. avio_printf(s, "%s|", name); \
  153. } \
  154. len = avio_close_dyn_buf(s, &ret); \
  155. ret[len - 1] = 0; \
  156. return ret; \
  157. } else \
  158. return NULL; \
  159. }
  160. // DEF_CHOOSE_FORMAT(enum AVPixelFormat, pix_fmt, pix_fmts, AV_PIX_FMT_NONE,
  161. // GET_PIX_FMT_NAME)
  162. DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
  163. AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME)
  164. DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
  165. GET_SAMPLE_RATE_NAME)
  166. DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
  167. GET_CH_LAYOUT_NAME)
  168. FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
  169. {
  170. FilterGraph *fg = av_mallocz(sizeof(*fg));
  171. if (!fg)
  172. exit_program(1);
  173. fg->index = nb_filtergraphs;
  174. GROW_ARRAY(fg->outputs, fg->nb_outputs);
  175. if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
  176. exit_program(1);
  177. fg->outputs[0]->ost = ost;
  178. fg->outputs[0]->graph = fg;
  179. ost->filter = fg->outputs[0];
  180. GROW_ARRAY(fg->inputs, fg->nb_inputs);
  181. if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
  182. exit_program(1);
  183. fg->inputs[0]->ist = ist;
  184. fg->inputs[0]->graph = fg;
  185. GROW_ARRAY(ist->filters, ist->nb_filters);
  186. ist->filters[ist->nb_filters - 1] = fg->inputs[0];
  187. GROW_ARRAY(filtergraphs, nb_filtergraphs);
  188. filtergraphs[nb_filtergraphs - 1] = fg;
  189. return fg;
  190. }
  191. static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
  192. {
  193. InputStream *ist = NULL;
  194. enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
  195. int i;
  196. // TODO: support other filter types
  197. if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
  198. av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
  199. "currently.\n");
  200. exit_program(1);
  201. }
  202. if (in->name) {
  203. AVFormatContext *s;
  204. AVStream *st = NULL;
  205. char *p;
  206. int file_idx = strtol(in->name, &p, 0);
  207. if (file_idx < 0 || file_idx >= nb_input_files) {
  208. av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
  209. file_idx, fg->graph_desc);
  210. exit_program(1);
  211. }
  212. s = input_files[file_idx]->ctx;
  213. for (i = 0; i < s->nb_streams; i++) {
  214. enum AVMediaType stream_type = s->streams[i]->codec->codec_type;
  215. if (stream_type != type &&
  216. !(stream_type == AVMEDIA_TYPE_SUBTITLE &&
  217. type == AVMEDIA_TYPE_VIDEO /* sub2video hack */))
  218. continue;
  219. if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
  220. st = s->streams[i];
  221. break;
  222. }
  223. }
  224. if (!st) {
  225. av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
  226. "matches no streams.\n", p, fg->graph_desc);
  227. exit_program(1);
  228. }
  229. ist = input_streams[input_files[file_idx]->ist_index + st->index];
  230. } else {
  231. /* find the first unused stream of corresponding type */
  232. for (i = 0; i < nb_input_streams; i++) {
  233. ist = input_streams[i];
  234. if (ist->dec_ctx->codec_type == type && ist->discard)
  235. break;
  236. }
  237. if (i == nb_input_streams) {
  238. av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
  239. "unlabeled input pad %d on filter %s\n", in->pad_idx,
  240. in->filter_ctx->name);
  241. exit_program(1);
  242. }
  243. }
  244. av_assert0(ist);
  245. ist->discard = 0;
  246. ist->decoding_needed |= DECODING_FOR_FILTER;
  247. ist->st->discard = AVDISCARD_NONE;
  248. GROW_ARRAY(fg->inputs, fg->nb_inputs);
  249. if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
  250. exit_program(1);
  251. fg->inputs[fg->nb_inputs - 1]->ist = ist;
  252. fg->inputs[fg->nb_inputs - 1]->graph = fg;
  253. GROW_ARRAY(ist->filters, ist->nb_filters);
  254. ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
  255. }
  256. static int insert_trim(int64_t start_time, int64_t duration,
  257. AVFilterContext **last_filter, int *pad_idx,
  258. const char *filter_name)
  259. {
  260. AVFilterGraph *graph = (*last_filter)->graph;
  261. AVFilterContext *ctx;
  262. const AVFilter *trim;
  263. enum AVMediaType type = avfilter_pad_get_type((*last_filter)->output_pads, *pad_idx);
  264. const char *name = (type == AVMEDIA_TYPE_VIDEO) ? "trim" : "atrim";
  265. int ret = 0;
  266. if (duration == INT64_MAX && start_time == AV_NOPTS_VALUE)
  267. return 0;
  268. trim = avfilter_get_by_name(name);
  269. if (!trim) {
  270. av_log(NULL, AV_LOG_ERROR, "%s filter not present, cannot limit "
  271. "recording time.\n", name);
  272. return AVERROR_FILTER_NOT_FOUND;
  273. }
  274. ctx = avfilter_graph_alloc_filter(graph, trim, filter_name);
  275. if (!ctx)
  276. return AVERROR(ENOMEM);
  277. if (duration != INT64_MAX) {
  278. ret = av_opt_set_int(ctx, "durationi", duration,
  279. AV_OPT_SEARCH_CHILDREN);
  280. }
  281. if (ret >= 0 && start_time != AV_NOPTS_VALUE) {
  282. ret = av_opt_set_int(ctx, "starti", start_time,
  283. AV_OPT_SEARCH_CHILDREN);
  284. }
  285. if (ret < 0) {
  286. av_log(ctx, AV_LOG_ERROR, "Error configuring the %s filter", name);
  287. return ret;
  288. }
  289. ret = avfilter_init_str(ctx, NULL);
  290. if (ret < 0)
  291. return ret;
  292. ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
  293. if (ret < 0)
  294. return ret;
  295. *last_filter = ctx;
  296. *pad_idx = 0;
  297. return 0;
  298. }
  299. static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
  300. {
  301. char *pix_fmts;
  302. OutputStream *ost = ofilter->ost;
  303. OutputFile *of = output_files[ost->file_index];
  304. AVCodecContext *codec = ost->enc_ctx;
  305. AVFilterContext *last_filter = out->filter_ctx;
  306. int pad_idx = out->pad_idx;
  307. int ret;
  308. char name[255];
  309. snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
  310. ret = avfilter_graph_create_filter(&ofilter->filter,
  311. avfilter_get_by_name("buffersink"),
  312. name, NULL, NULL, fg->graph);
  313. if (ret < 0)
  314. return ret;
  315. if (codec->width || codec->height) {
  316. char args[255];
  317. AVFilterContext *filter;
  318. snprintf(args, sizeof(args), "%d:%d:0x%X",
  319. codec->width,
  320. codec->height,
  321. (unsigned)ost->sws_flags);
  322. snprintf(name, sizeof(name), "scaler for output stream %d:%d",
  323. ost->file_index, ost->index);
  324. if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
  325. name, args, NULL, fg->graph)) < 0)
  326. return ret;
  327. if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
  328. return ret;
  329. last_filter = filter;
  330. pad_idx = 0;
  331. }
  332. if ((pix_fmts = choose_pix_fmts(ost))) {
  333. AVFilterContext *filter;
  334. snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
  335. ost->file_index, ost->index);
  336. ret = avfilter_graph_create_filter(&filter,
  337. avfilter_get_by_name("format"),
  338. "format", pix_fmts, NULL,
  339. fg->graph);
  340. av_freep(&pix_fmts);
  341. if (ret < 0)
  342. return ret;
  343. if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
  344. return ret;
  345. last_filter = filter;
  346. pad_idx = 0;
  347. }
  348. if (ost->frame_rate.num && 0) {
  349. AVFilterContext *fps;
  350. char args[255];
  351. snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
  352. ost->frame_rate.den);
  353. snprintf(name, sizeof(name), "fps for output stream %d:%d",
  354. ost->file_index, ost->index);
  355. ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
  356. name, args, NULL, fg->graph);
  357. if (ret < 0)
  358. return ret;
  359. ret = avfilter_link(last_filter, pad_idx, fps, 0);
  360. if (ret < 0)
  361. return ret;
  362. last_filter = fps;
  363. pad_idx = 0;
  364. }
  365. snprintf(name, sizeof(name), "trim for output stream %d:%d",
  366. ost->file_index, ost->index);
  367. ret = insert_trim(of->start_time, of->recording_time,
  368. &last_filter, &pad_idx, name);
  369. if (ret < 0)
  370. return ret;
  371. if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
  372. return ret;
  373. return 0;
  374. }
  375. static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
  376. {
  377. OutputStream *ost = ofilter->ost;
  378. OutputFile *of = output_files[ost->file_index];
  379. AVCodecContext *codec = ost->enc_ctx;
  380. AVFilterContext *last_filter = out->filter_ctx;
  381. int pad_idx = out->pad_idx;
  382. char *sample_fmts, *sample_rates, *channel_layouts;
  383. char name[255];
  384. int ret;
  385. snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
  386. ret = avfilter_graph_create_filter(&ofilter->filter,
  387. avfilter_get_by_name("abuffersink"),
  388. name, NULL, NULL, fg->graph);
  389. if (ret < 0)
  390. return ret;
  391. if ((ret = av_opt_set_int(ofilter->filter, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
  392. return ret;
  393. #define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do { \
  394. AVFilterContext *filt_ctx; \
  395. \
  396. av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi " \
  397. "similarly to -af " filter_name "=%s.\n", arg); \
  398. \
  399. ret = avfilter_graph_create_filter(&filt_ctx, \
  400. avfilter_get_by_name(filter_name), \
  401. filter_name, arg, NULL, fg->graph); \
  402. if (ret < 0) \
  403. return ret; \
  404. \
  405. ret = avfilter_link(last_filter, pad_idx, filt_ctx, 0); \
  406. if (ret < 0) \
  407. return ret; \
  408. \
  409. last_filter = filt_ctx; \
  410. pad_idx = 0; \
  411. } while (0)
  412. if (ost->audio_channels_mapped) {
  413. int i;
  414. AVBPrint pan_buf;
  415. av_bprint_init(&pan_buf, 256, 8192);
  416. av_bprintf(&pan_buf, "0x%"PRIx64,
  417. av_get_default_channel_layout(ost->audio_channels_mapped));
  418. for (i = 0; i < ost->audio_channels_mapped; i++)
  419. if (ost->audio_channels_map[i] != -1)
  420. av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
  421. AUTO_INSERT_FILTER("-map_channel", "pan", pan_buf.str);
  422. av_bprint_finalize(&pan_buf, NULL);
  423. }
  424. if (codec->channels && !codec->channel_layout)
  425. codec->channel_layout = av_get_default_channel_layout(codec->channels);
  426. sample_fmts = choose_sample_fmts(ost);
  427. sample_rates = choose_sample_rates(ost);
  428. channel_layouts = choose_channel_layouts(ost);
  429. if (sample_fmts || sample_rates || channel_layouts) {
  430. AVFilterContext *format;
  431. char args[256];
  432. args[0] = 0;
  433. if (sample_fmts)
  434. av_strlcatf(args, sizeof(args), "sample_fmts=%s:",
  435. sample_fmts);
  436. if (sample_rates)
  437. av_strlcatf(args, sizeof(args), "sample_rates=%s:",
  438. sample_rates);
  439. if (channel_layouts)
  440. av_strlcatf(args, sizeof(args), "channel_layouts=%s:",
  441. channel_layouts);
  442. av_freep(&sample_fmts);
  443. av_freep(&sample_rates);
  444. av_freep(&channel_layouts);
  445. snprintf(name, sizeof(name), "audio format for output stream %d:%d",
  446. ost->file_index, ost->index);
  447. ret = avfilter_graph_create_filter(&format,
  448. avfilter_get_by_name("aformat"),
  449. name, args, NULL, fg->graph);
  450. if (ret < 0)
  451. return ret;
  452. ret = avfilter_link(last_filter, pad_idx, format, 0);
  453. if (ret < 0)
  454. return ret;
  455. last_filter = format;
  456. pad_idx = 0;
  457. }
  458. if (audio_volume != 256 && 0) {
  459. char args[256];
  460. snprintf(args, sizeof(args), "%f", audio_volume / 256.);
  461. AUTO_INSERT_FILTER("-vol", "volume", args);
  462. }
  463. if (ost->apad && of->shortest) {
  464. char args[256];
  465. int i;
  466. for (i=0; i<of->ctx->nb_streams; i++)
  467. if (of->ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  468. break;
  469. if (i<of->ctx->nb_streams) {
  470. snprintf(args, sizeof(args), "%s", ost->apad);
  471. AUTO_INSERT_FILTER("-apad", "apad", args);
  472. }
  473. }
  474. snprintf(name, sizeof(name), "trim for output stream %d:%d",
  475. ost->file_index, ost->index);
  476. ret = insert_trim(of->start_time, of->recording_time,
  477. &last_filter, &pad_idx, name);
  478. if (ret < 0)
  479. return ret;
  480. if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
  481. return ret;
  482. return 0;
  483. }
  484. #define DESCRIBE_FILTER_LINK(f, inout, in) \
  485. { \
  486. AVFilterContext *ctx = inout->filter_ctx; \
  487. AVFilterPad *pads = in ? ctx->input_pads : ctx->output_pads; \
  488. int nb_pads = in ? ctx->nb_inputs : ctx->nb_outputs; \
  489. AVIOContext *pb; \
  490. \
  491. if (avio_open_dyn_buf(&pb) < 0) \
  492. exit_program(1); \
  493. \
  494. avio_printf(pb, "%s", ctx->filter->name); \
  495. if (nb_pads > 1) \
  496. avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
  497. avio_w8(pb, 0); \
  498. avio_close_dyn_buf(pb, &f->name); \
  499. }
  500. int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
  501. {
  502. av_freep(&ofilter->name);
  503. DESCRIBE_FILTER_LINK(ofilter, out, 0);
  504. switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
  505. case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
  506. case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
  507. default: av_assert0(0);
  508. }
  509. }
  510. static int sub2video_prepare(InputStream *ist)
  511. {
  512. AVFormatContext *avf = input_files[ist->file_index]->ctx;
  513. int i, w, h;
  514. /* Compute the size of the canvas for the subtitles stream.
  515. If the subtitles codec has set a size, use it. Otherwise use the
  516. maximum dimensions of the video streams in the same file. */
  517. w = ist->dec_ctx->width;
  518. h = ist->dec_ctx->height;
  519. if (!(w && h)) {
  520. for (i = 0; i < avf->nb_streams; i++) {
  521. if (avf->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  522. w = FFMAX(w, avf->streams[i]->codec->width);
  523. h = FFMAX(h, avf->streams[i]->codec->height);
  524. }
  525. }
  526. if (!(w && h)) {
  527. w = FFMAX(w, 720);
  528. h = FFMAX(h, 576);
  529. }
  530. av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h);
  531. }
  532. ist->sub2video.w = ist->dec_ctx->width = ist->resample_width = w;
  533. ist->sub2video.h = ist->dec_ctx->height = ist->resample_height = h;
  534. /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the
  535. palettes for all rectangles are identical or compatible */
  536. ist->resample_pix_fmt = ist->dec_ctx->pix_fmt = AV_PIX_FMT_RGB32;
  537. ist->sub2video.frame = av_frame_alloc();
  538. if (!ist->sub2video.frame)
  539. return AVERROR(ENOMEM);
  540. return 0;
  541. }
  542. static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
  543. AVFilterInOut *in)
  544. {
  545. AVFilterContext *last_filter;
  546. const AVFilter *buffer_filt = avfilter_get_by_name("buffer");
  547. InputStream *ist = ifilter->ist;
  548. InputFile *f = input_files[ist->file_index];
  549. AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
  550. ist->st->time_base;
  551. AVRational fr = ist->framerate;
  552. AVRational sar;
  553. AVBPrint args;
  554. char name[255];
  555. int ret, pad_idx = 0;
  556. if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  557. av_log(NULL, AV_LOG_ERROR, "Cannot connect video filter to audio input\n");
  558. return AVERROR(EINVAL);
  559. }
  560. if (!fr.num)
  561. fr = av_guess_frame_rate(input_files[ist->file_index]->ctx, ist->st, NULL);
  562. if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  563. ret = sub2video_prepare(ist);
  564. if (ret < 0)
  565. return ret;
  566. }
  567. sar = ist->st->sample_aspect_ratio.num ?
  568. ist->st->sample_aspect_ratio :
  569. ist->dec_ctx->sample_aspect_ratio;
  570. if(!sar.den)
  571. sar = (AVRational){0,1};
  572. av_bprint_init(&args, 0, 1);
  573. av_bprintf(&args,
  574. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:"
  575. "pixel_aspect=%d/%d:sws_param=flags=%d", ist->resample_width,
  576. ist->resample_height,
  577. ist->hwaccel_retrieve_data ? ist->hwaccel_retrieved_pix_fmt : ist->resample_pix_fmt,
  578. tb.num, tb.den, sar.num, sar.den,
  579. SWS_BILINEAR + ((ist->dec_ctx->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
  580. if (fr.num && fr.den)
  581. av_bprintf(&args, ":frame_rate=%d/%d", fr.num, fr.den);
  582. snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
  583. ist->file_index, ist->st->index);
  584. if ((ret = avfilter_graph_create_filter(&ifilter->filter, buffer_filt, name,
  585. args.str, NULL, fg->graph)) < 0)
  586. return ret;
  587. last_filter = ifilter->filter;
  588. if (ist->framerate.num) {
  589. AVFilterContext *setpts;
  590. snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
  591. ist->file_index, ist->st->index);
  592. if ((ret = avfilter_graph_create_filter(&setpts,
  593. avfilter_get_by_name("setpts"),
  594. name, "N", NULL,
  595. fg->graph)) < 0)
  596. return ret;
  597. if ((ret = avfilter_link(last_filter, 0, setpts, 0)) < 0)
  598. return ret;
  599. last_filter = setpts;
  600. }
  601. if (do_deinterlace) {
  602. AVFilterContext *yadif;
  603. snprintf(name, sizeof(name), "deinterlace input from stream %d:%d",
  604. ist->file_index, ist->st->index);
  605. if ((ret = avfilter_graph_create_filter(&yadif,
  606. avfilter_get_by_name("yadif"),
  607. name, "", NULL,
  608. fg->graph)) < 0)
  609. return ret;
  610. if ((ret = avfilter_link(last_filter, 0, yadif, 0)) < 0)
  611. return ret;
  612. last_filter = yadif;
  613. }
  614. snprintf(name, sizeof(name), "trim for input stream %d:%d",
  615. ist->file_index, ist->st->index);
  616. ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
  617. AV_NOPTS_VALUE : 0, f->recording_time, &last_filter, &pad_idx, name);
  618. if (ret < 0)
  619. return ret;
  620. if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
  621. return ret;
  622. return 0;
  623. }
  624. static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
  625. AVFilterInOut *in)
  626. {
  627. AVFilterContext *last_filter;
  628. const AVFilter *abuffer_filt = avfilter_get_by_name("abuffer");
  629. InputStream *ist = ifilter->ist;
  630. InputFile *f = input_files[ist->file_index];
  631. AVBPrint args;
  632. char name[255];
  633. int ret, pad_idx = 0;
  634. if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_AUDIO) {
  635. av_log(NULL, AV_LOG_ERROR, "Cannot connect audio filter to non audio input\n");
  636. return AVERROR(EINVAL);
  637. }
  638. av_bprint_init(&args, 0, AV_BPRINT_SIZE_AUTOMATIC);
  639. av_bprintf(&args, "time_base=%d/%d:sample_rate=%d:sample_fmt=%s",
  640. 1, ist->dec_ctx->sample_rate,
  641. ist->dec_ctx->sample_rate,
  642. av_get_sample_fmt_name(ist->dec_ctx->sample_fmt));
  643. if (ist->dec_ctx->channel_layout)
  644. av_bprintf(&args, ":channel_layout=0x%"PRIx64,
  645. ist->dec_ctx->channel_layout);
  646. else
  647. av_bprintf(&args, ":channels=%d", ist->dec_ctx->channels);
  648. snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
  649. ist->file_index, ist->st->index);
  650. if ((ret = avfilter_graph_create_filter(&ifilter->filter, abuffer_filt,
  651. name, args.str, NULL,
  652. fg->graph)) < 0)
  653. return ret;
  654. last_filter = ifilter->filter;
  655. #define AUTO_INSERT_FILTER_INPUT(opt_name, filter_name, arg) do { \
  656. AVFilterContext *filt_ctx; \
  657. \
  658. av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi " \
  659. "similarly to -af " filter_name "=%s.\n", arg); \
  660. \
  661. snprintf(name, sizeof(name), "graph %d %s for input stream %d:%d", \
  662. fg->index, filter_name, ist->file_index, ist->st->index); \
  663. ret = avfilter_graph_create_filter(&filt_ctx, \
  664. avfilter_get_by_name(filter_name), \
  665. name, arg, NULL, fg->graph); \
  666. if (ret < 0) \
  667. return ret; \
  668. \
  669. ret = avfilter_link(last_filter, 0, filt_ctx, 0); \
  670. if (ret < 0) \
  671. return ret; \
  672. \
  673. last_filter = filt_ctx; \
  674. } while (0)
  675. if (audio_sync_method > 0) {
  676. char args[256] = {0};
  677. av_strlcatf(args, sizeof(args), "async=%d", audio_sync_method);
  678. if (audio_drift_threshold != 0.1)
  679. av_strlcatf(args, sizeof(args), ":min_hard_comp=%f", audio_drift_threshold);
  680. if (!fg->reconfiguration)
  681. av_strlcatf(args, sizeof(args), ":first_pts=0");
  682. AUTO_INSERT_FILTER_INPUT("-async", "aresample", args);
  683. }
  684. // if (ost->audio_channels_mapped) {
  685. // int i;
  686. // AVBPrint pan_buf;
  687. // av_bprint_init(&pan_buf, 256, 8192);
  688. // av_bprintf(&pan_buf, "0x%"PRIx64,
  689. // av_get_default_channel_layout(ost->audio_channels_mapped));
  690. // for (i = 0; i < ost->audio_channels_mapped; i++)
  691. // if (ost->audio_channels_map[i] != -1)
  692. // av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
  693. // AUTO_INSERT_FILTER_INPUT("-map_channel", "pan", pan_buf.str);
  694. // av_bprint_finalize(&pan_buf, NULL);
  695. // }
  696. if (audio_volume != 256) {
  697. char args[256];
  698. av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
  699. "audio filter instead.\n");
  700. snprintf(args, sizeof(args), "%f", audio_volume / 256.);
  701. AUTO_INSERT_FILTER_INPUT("-vol", "volume", args);
  702. }
  703. snprintf(name, sizeof(name), "trim for input stream %d:%d",
  704. ist->file_index, ist->st->index);
  705. ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
  706. AV_NOPTS_VALUE : 0, f->recording_time, &last_filter, &pad_idx, name);
  707. if (ret < 0)
  708. return ret;
  709. if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
  710. return ret;
  711. return 0;
  712. }
  713. static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
  714. AVFilterInOut *in)
  715. {
  716. av_freep(&ifilter->name);
  717. DESCRIBE_FILTER_LINK(ifilter, in, 1);
  718. if (!ifilter->ist->dec) {
  719. av_log(NULL, AV_LOG_ERROR,
  720. "No decoder for stream #%d:%d, filtering impossible\n",
  721. ifilter->ist->file_index, ifilter->ist->st->index);
  722. return AVERROR_DECODER_NOT_FOUND;
  723. }
  724. switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
  725. case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
  726. case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
  727. default: av_assert0(0);
  728. }
  729. }
  730. int configure_filtergraph(FilterGraph *fg)
  731. {
  732. AVFilterInOut *inputs, *outputs, *cur;
  733. int ret, i, init = !fg->graph, simple = !fg->graph_desc;
  734. const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
  735. fg->graph_desc;
  736. avfilter_graph_free(&fg->graph);
  737. if (!(fg->graph = avfilter_graph_alloc()))
  738. return AVERROR(ENOMEM);
  739. if (simple) {
  740. OutputStream *ost = fg->outputs[0]->ost;
  741. char args[512];
  742. AVDictionaryEntry *e = NULL;
  743. snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
  744. fg->graph->scale_sws_opts = av_strdup(args);
  745. args[0] = 0;
  746. while ((e = av_dict_get(ost->swr_opts, "", e,
  747. AV_DICT_IGNORE_SUFFIX))) {
  748. av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
  749. }
  750. if (strlen(args))
  751. args[strlen(args)-1] = 0;
  752. av_opt_set(fg->graph, "aresample_swr_opts", args, 0);
  753. args[0] = '\0';
  754. while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
  755. AV_DICT_IGNORE_SUFFIX))) {
  756. av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
  757. }
  758. if (strlen(args))
  759. args[strlen(args) - 1] = '\0';
  760. fg->graph->resample_lavr_opts = av_strdup(args);
  761. e = av_dict_get(ost->encoder_opts, "threads", NULL, 0);
  762. if (e)
  763. av_opt_set(fg->graph, "threads", e->value, 0);
  764. }
  765. if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
  766. return ret;
  767. if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
  768. av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
  769. "exactly one input and output.\n", graph_desc);
  770. return AVERROR(EINVAL);
  771. }
  772. for (cur = inputs; !simple && init && cur; cur = cur->next)
  773. init_input_filter(fg, cur);
  774. for (cur = inputs, i = 0; cur; cur = cur->next, i++)
  775. if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0) {
  776. avfilter_inout_free(&inputs);
  777. avfilter_inout_free(&outputs);
  778. return ret;
  779. }
  780. avfilter_inout_free(&inputs);
  781. if (!init || simple) {
  782. /* we already know the mappings between lavfi outputs and output streams,
  783. * so we can finish the setup */
  784. for (cur = outputs, i = 0; cur; cur = cur->next, i++)
  785. configure_output_filter(fg, fg->outputs[i], cur);
  786. avfilter_inout_free(&outputs);
  787. if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
  788. return ret;
  789. } else {
  790. /* wait until output mappings are processed */
  791. for (cur = outputs; cur;) {
  792. GROW_ARRAY(fg->outputs, fg->nb_outputs);
  793. if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
  794. exit_program(1);
  795. fg->outputs[fg->nb_outputs - 1]->graph = fg;
  796. fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
  797. cur = cur->next;
  798. fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
  799. }
  800. }
  801. fg->reconfiguration = 1;
  802. for (i = 0; i < fg->nb_outputs; i++) {
  803. OutputStream *ost = fg->outputs[i]->ost;
  804. if (ost &&
  805. ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  806. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  807. av_buffersink_set_frame_size(ost->filter->filter,
  808. ost->enc_ctx->frame_size);
  809. }
  810. return 0;
  811. }
  812. int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
  813. {
  814. int i;
  815. for (i = 0; i < fg->nb_inputs; i++)
  816. if (fg->inputs[i]->ist == ist)
  817. return 1;
  818. return 0;
  819. }