ffmpeg_filter.c 35 KB

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