ffmpeg_filter.c 37 KB

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