ffmpeg_filter.c 36 KB

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