You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

926 lines
36KB

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