ffmpeg_filter.c 36 KB

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