ffmpeg_filter.c 36 KB

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