ffmpeg_filter.c 41 KB

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