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.

911 lines
35KB

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