ffmpeg_filter.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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 "libavfilter/buffersrc.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. // FIXME: YUV420P etc. are actually supported with full color range,
  36. // yet the latter information isn't available here.
  37. static const enum AVPixelFormat *get_compliance_normal_pix_fmts(const AVCodec *codec, const enum AVPixelFormat default_formats[])
  38. {
  39. static const enum AVPixelFormat mjpeg_formats[] =
  40. { AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P,
  41. AV_PIX_FMT_NONE };
  42. if (!strcmp(codec->name, "mjpeg")) {
  43. return mjpeg_formats;
  44. } else {
  45. return default_formats;
  46. }
  47. }
  48. static enum AVPixelFormat
  49. choose_pixel_fmt(const AVCodec *codec, enum AVPixelFormat target,
  50. int strict_std_compliance)
  51. {
  52. if (codec && codec->pix_fmts) {
  53. const enum AVPixelFormat *p = codec->pix_fmts;
  54. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(target);
  55. //FIXME: This should check for AV_PIX_FMT_FLAG_ALPHA after PAL8 pixel format without alpha is implemented
  56. int has_alpha = desc ? desc->nb_components % 2 == 0 : 0;
  57. enum AVPixelFormat best= AV_PIX_FMT_NONE;
  58. if (strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL) {
  59. p = get_compliance_normal_pix_fmts(codec, p);
  60. }
  61. for (; *p != AV_PIX_FMT_NONE; p++) {
  62. best = av_find_best_pix_fmt_of_2(best, *p, target, has_alpha, NULL);
  63. if (*p == target)
  64. break;
  65. }
  66. if (*p == AV_PIX_FMT_NONE) {
  67. if (target != AV_PIX_FMT_NONE)
  68. av_log(NULL, AV_LOG_WARNING,
  69. "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
  70. av_get_pix_fmt_name(target),
  71. codec->name,
  72. av_get_pix_fmt_name(best));
  73. return best;
  74. }
  75. }
  76. return target;
  77. }
  78. /* May return NULL (no pixel format found), a static string or a string
  79. * backed by the bprint. Nothing has been written to the AVBPrint in case
  80. * NULL is returned. The AVBPrint provided should be clean. */
  81. static const char *choose_pix_fmts(OutputFilter *ofilter, AVBPrint *bprint)
  82. {
  83. OutputStream *ost = ofilter->ost;
  84. AVCodecContext *enc = ost->enc_ctx;
  85. const AVDictionaryEntry *strict_dict = av_dict_get(ost->encoder_opts, "strict", NULL, 0);
  86. if (strict_dict)
  87. // used by choose_pixel_fmt() and below
  88. av_opt_set(ost->enc_ctx, "strict", strict_dict->value, 0);
  89. if (ost->keep_pix_fmt) {
  90. avfilter_graph_set_auto_convert(ofilter->graph->graph,
  91. AVFILTER_AUTO_CONVERT_NONE);
  92. if (ost->enc_ctx->pix_fmt == AV_PIX_FMT_NONE)
  93. return NULL;
  94. return av_get_pix_fmt_name(ost->enc_ctx->pix_fmt);
  95. }
  96. if (ost->enc_ctx->pix_fmt != AV_PIX_FMT_NONE) {
  97. return av_get_pix_fmt_name(choose_pixel_fmt(enc->codec, enc->pix_fmt,
  98. ost->enc_ctx->strict_std_compliance));
  99. } else if (enc->codec->pix_fmts) {
  100. const enum AVPixelFormat *p;
  101. p = enc->codec->pix_fmts;
  102. if (ost->enc_ctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL) {
  103. p = get_compliance_normal_pix_fmts(enc->codec, p);
  104. }
  105. for (; *p != AV_PIX_FMT_NONE; p++) {
  106. const char *name = av_get_pix_fmt_name(*p);
  107. av_bprintf(bprint, "%s%c", name, p[1] == AV_PIX_FMT_NONE ? '\0' : '|');
  108. }
  109. if (!av_bprint_is_complete(bprint))
  110. report_and_exit(AVERROR(ENOMEM));
  111. return bprint->str;
  112. } else
  113. return NULL;
  114. }
  115. /* Define a function for appending a list of allowed formats
  116. * to an AVBPrint. If nonempty, the list will have a header. */
  117. #define DEF_CHOOSE_FORMAT(name, type, var, supported_list, none, printf_format, get_name) \
  118. static void choose_ ## name (OutputFilter *ofilter, AVBPrint *bprint) \
  119. { \
  120. if (ofilter->var == none && !ofilter->supported_list) \
  121. return; \
  122. av_bprintf(bprint, #name "="); \
  123. if (ofilter->var != none) { \
  124. av_bprintf(bprint, printf_format, get_name(ofilter->var)); \
  125. } else { \
  126. const type *p; \
  127. \
  128. for (p = ofilter->supported_list; *p != none; p++) { \
  129. av_bprintf(bprint, printf_format "|", get_name(*p)); \
  130. } \
  131. if (bprint->len > 0) \
  132. bprint->str[--bprint->len] = '\0'; \
  133. } \
  134. av_bprint_chars(bprint, ':', 1); \
  135. }
  136. //DEF_CHOOSE_FORMAT(pix_fmts, enum AVPixelFormat, format, formats, AV_PIX_FMT_NONE,
  137. // GET_PIX_FMT_NAME)
  138. DEF_CHOOSE_FORMAT(sample_fmts, enum AVSampleFormat, format, formats,
  139. AV_SAMPLE_FMT_NONE, "%s", av_get_sample_fmt_name)
  140. DEF_CHOOSE_FORMAT(sample_rates, int, sample_rate, sample_rates, 0,
  141. "%d", )
  142. static void choose_channel_layouts(OutputFilter *ofilter, AVBPrint *bprint)
  143. {
  144. if (av_channel_layout_check(&ofilter->ch_layout)) {
  145. av_bprintf(bprint, "channel_layouts=");
  146. av_channel_layout_describe_bprint(&ofilter->ch_layout, bprint);
  147. } else if (ofilter->ch_layouts) {
  148. const AVChannelLayout *p;
  149. av_bprintf(bprint, "channel_layouts=");
  150. for (p = ofilter->ch_layouts; p->nb_channels; p++) {
  151. av_channel_layout_describe_bprint(p, bprint);
  152. av_bprintf(bprint, "|");
  153. }
  154. if (bprint->len > 0)
  155. bprint->str[--bprint->len] = '\0';
  156. } else
  157. return;
  158. av_bprint_chars(bprint, ':', 1);
  159. }
  160. int init_simple_filtergraph(InputStream *ist, OutputStream *ost)
  161. {
  162. FilterGraph *fg = av_mallocz(sizeof(*fg));
  163. OutputFilter *ofilter;
  164. InputFilter *ifilter;
  165. if (!fg)
  166. report_and_exit(AVERROR(ENOMEM));
  167. fg->index = nb_filtergraphs;
  168. ofilter = ALLOC_ARRAY_ELEM(fg->outputs, fg->nb_outputs);
  169. ofilter->ost = ost;
  170. ofilter->graph = fg;
  171. ofilter->format = -1;
  172. ost->filter = ofilter;
  173. ifilter = ALLOC_ARRAY_ELEM(fg->inputs, fg->nb_inputs);
  174. ifilter->ist = ist;
  175. ifilter->graph = fg;
  176. ifilter->format = -1;
  177. ifilter->frame_queue = av_fifo_alloc2(8, sizeof(AVFrame*), AV_FIFO_FLAG_AUTO_GROW);
  178. if (!ifilter->frame_queue)
  179. report_and_exit(AVERROR(ENOMEM));
  180. GROW_ARRAY(ist->filters, ist->nb_filters);
  181. ist->filters[ist->nb_filters - 1] = ifilter;
  182. GROW_ARRAY(filtergraphs, nb_filtergraphs);
  183. filtergraphs[nb_filtergraphs - 1] = fg;
  184. return 0;
  185. }
  186. static char *describe_filter_link(FilterGraph *fg, AVFilterInOut *inout, int in)
  187. {
  188. AVFilterContext *ctx = inout->filter_ctx;
  189. AVFilterPad *pads = in ? ctx->input_pads : ctx->output_pads;
  190. int nb_pads = in ? ctx->nb_inputs : ctx->nb_outputs;
  191. char *res;
  192. if (nb_pads > 1)
  193. res = av_strdup(ctx->filter->name);
  194. else
  195. res = av_asprintf("%s:%s", ctx->filter->name,
  196. avfilter_pad_get_name(pads, inout->pad_idx));
  197. if (!res)
  198. report_and_exit(AVERROR(ENOMEM));
  199. return res;
  200. }
  201. static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
  202. {
  203. InputStream *ist = NULL;
  204. enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
  205. InputFilter *ifilter;
  206. int i;
  207. // TODO: support other filter types
  208. if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
  209. av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
  210. "currently.\n");
  211. exit_program(1);
  212. }
  213. if (in->name) {
  214. AVFormatContext *s;
  215. AVStream *st = NULL;
  216. char *p;
  217. int file_idx = strtol(in->name, &p, 0);
  218. if (file_idx < 0 || file_idx >= nb_input_files) {
  219. av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
  220. file_idx, fg->graph_desc);
  221. exit_program(1);
  222. }
  223. s = input_files[file_idx]->ctx;
  224. for (i = 0; i < s->nb_streams; i++) {
  225. enum AVMediaType stream_type = s->streams[i]->codecpar->codec_type;
  226. if (stream_type != type &&
  227. !(stream_type == AVMEDIA_TYPE_SUBTITLE &&
  228. type == AVMEDIA_TYPE_VIDEO /* sub2video hack */))
  229. continue;
  230. if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
  231. st = s->streams[i];
  232. break;
  233. }
  234. }
  235. if (!st) {
  236. av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
  237. "matches no streams.\n", p, fg->graph_desc);
  238. exit_program(1);
  239. }
  240. ist = input_files[file_idx]->streams[st->index];
  241. if (ist->user_set_discard == AVDISCARD_ALL) {
  242. av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
  243. "matches a disabled input stream.\n", p, fg->graph_desc);
  244. exit_program(1);
  245. }
  246. } else {
  247. /* find the first unused stream of corresponding type */
  248. for (ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
  249. if (ist->user_set_discard == AVDISCARD_ALL)
  250. continue;
  251. if (ist->dec_ctx->codec_type == type && ist->discard)
  252. break;
  253. }
  254. if (!ist) {
  255. av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
  256. "unlabeled input pad %d on filter %s\n", in->pad_idx,
  257. in->filter_ctx->name);
  258. exit_program(1);
  259. }
  260. }
  261. av_assert0(ist);
  262. ist->discard = 0;
  263. ist->decoding_needed |= DECODING_FOR_FILTER;
  264. ist->processing_needed = 1;
  265. ist->st->discard = AVDISCARD_NONE;
  266. ifilter = ALLOC_ARRAY_ELEM(fg->inputs, fg->nb_inputs);
  267. ifilter->ist = ist;
  268. ifilter->graph = fg;
  269. ifilter->format = -1;
  270. ifilter->type = ist->st->codecpar->codec_type;
  271. ifilter->name = describe_filter_link(fg, in, 1);
  272. ifilter->frame_queue = av_fifo_alloc2(8, sizeof(AVFrame*), AV_FIFO_FLAG_AUTO_GROW);
  273. if (!ifilter->frame_queue)
  274. report_and_exit(AVERROR(ENOMEM));
  275. GROW_ARRAY(ist->filters, ist->nb_filters);
  276. ist->filters[ist->nb_filters - 1] = ifilter;
  277. }
  278. static int read_binary(const char *path, uint8_t **data, int *len)
  279. {
  280. AVIOContext *io = NULL;
  281. int64_t fsize;
  282. int ret;
  283. *data = NULL;
  284. *len = 0;
  285. ret = avio_open2(&io, path, AVIO_FLAG_READ, &int_cb, NULL);
  286. if (ret < 0) {
  287. av_log(NULL, AV_LOG_ERROR, "Cannot open file '%s': %s\n",
  288. path, av_err2str(ret));
  289. return ret;
  290. }
  291. fsize = avio_size(io);
  292. if (fsize < 0 || fsize > INT_MAX) {
  293. av_log(NULL, AV_LOG_ERROR, "Cannot obtain size of file %s\n", path);
  294. ret = AVERROR(EIO);
  295. goto fail;
  296. }
  297. *data = av_malloc(fsize);
  298. if (!*data) {
  299. ret = AVERROR(ENOMEM);
  300. goto fail;
  301. }
  302. ret = avio_read(io, *data, fsize);
  303. if (ret != fsize) {
  304. av_log(NULL, AV_LOG_ERROR, "Error reading file %s\n", path);
  305. ret = ret < 0 ? ret : AVERROR(EIO);
  306. goto fail;
  307. }
  308. *len = fsize;
  309. ret = 0;
  310. fail:
  311. avio_close(io);
  312. if (ret < 0) {
  313. av_freep(data);
  314. *len = 0;
  315. }
  316. return ret;
  317. }
  318. static int filter_opt_apply(AVFilterContext *f, const char *key, const char *val)
  319. {
  320. const AVOption *o;
  321. int ret;
  322. ret = av_opt_set(f, key, val, AV_OPT_SEARCH_CHILDREN);
  323. if (ret >= 0)
  324. return 0;
  325. if (ret == AVERROR_OPTION_NOT_FOUND && key[0] == '/')
  326. o = av_opt_find(f, key + 1, NULL, 0, AV_OPT_SEARCH_CHILDREN);
  327. if (!o)
  328. goto err_apply;
  329. // key is a valid option name prefixed with '/'
  330. // interpret value as a path from which to load the actual option value
  331. key++;
  332. if (o->type == AV_OPT_TYPE_BINARY) {
  333. uint8_t *data;
  334. int len;
  335. ret = read_binary(val, &data, &len);
  336. if (ret < 0)
  337. goto err_load;
  338. ret = av_opt_set_bin(f, key, data, len, AV_OPT_SEARCH_CHILDREN);
  339. av_freep(&data);
  340. } else {
  341. char *data = file_read(val);
  342. if (!data) {
  343. ret = AVERROR(EIO);
  344. goto err_load;
  345. }
  346. ret = av_opt_set(f, key, data, AV_OPT_SEARCH_CHILDREN);
  347. av_freep(&data);
  348. }
  349. if (ret < 0)
  350. goto err_apply;
  351. return 0;
  352. err_apply:
  353. av_log(NULL, AV_LOG_ERROR,
  354. "Error applying option '%s' to filter '%s': %s\n",
  355. key, f->filter->name, av_err2str(ret));
  356. return ret;
  357. err_load:
  358. av_log(NULL, AV_LOG_ERROR,
  359. "Error loading value for option '%s' from file '%s'\n",
  360. key, val);
  361. return ret;
  362. }
  363. static int graph_opts_apply(AVFilterGraphSegment *seg)
  364. {
  365. for (size_t i = 0; i < seg->nb_chains; i++) {
  366. AVFilterChain *ch = seg->chains[i];
  367. for (size_t j = 0; j < ch->nb_filters; j++) {
  368. AVFilterParams *p = ch->filters[j];
  369. const AVDictionaryEntry *e = NULL;
  370. av_assert0(p->filter);
  371. while ((e = av_dict_iterate(p->opts, e))) {
  372. int ret = filter_opt_apply(p->filter, e->key, e->value);
  373. if (ret < 0)
  374. return ret;
  375. }
  376. av_dict_free(&p->opts);
  377. }
  378. }
  379. return 0;
  380. }
  381. static int graph_parse(AVFilterGraph *graph, const char *desc,
  382. AVFilterInOut **inputs, AVFilterInOut **outputs)
  383. {
  384. AVFilterGraphSegment *seg;
  385. int ret;
  386. ret = avfilter_graph_segment_parse(graph, desc, 0, &seg);
  387. if (ret < 0)
  388. return ret;
  389. ret = avfilter_graph_segment_create_filters(seg, 0);
  390. if (ret < 0)
  391. goto fail;
  392. ret = graph_opts_apply(seg);
  393. if (ret < 0)
  394. goto fail;
  395. ret = avfilter_graph_segment_apply(seg, 0, inputs, outputs);
  396. fail:
  397. avfilter_graph_segment_free(&seg);
  398. return ret;
  399. }
  400. int init_complex_filtergraph(FilterGraph *fg)
  401. {
  402. AVFilterInOut *inputs, *outputs, *cur;
  403. AVFilterGraph *graph;
  404. int ret = 0;
  405. /* this graph is only used for determining the kinds of inputs
  406. * and outputs we have, and is discarded on exit from this function */
  407. graph = avfilter_graph_alloc();
  408. if (!graph)
  409. return AVERROR(ENOMEM);
  410. graph->nb_threads = 1;
  411. ret = graph_parse(graph, fg->graph_desc, &inputs, &outputs);
  412. if (ret < 0)
  413. goto fail;
  414. for (cur = inputs; cur; cur = cur->next)
  415. init_input_filter(fg, cur);
  416. for (cur = outputs; cur;) {
  417. OutputFilter *const ofilter = ALLOC_ARRAY_ELEM(fg->outputs, fg->nb_outputs);
  418. ofilter->graph = fg;
  419. ofilter->out_tmp = cur;
  420. ofilter->type = avfilter_pad_get_type(cur->filter_ctx->output_pads,
  421. cur->pad_idx);
  422. ofilter->name = describe_filter_link(fg, cur, 0);
  423. cur = cur->next;
  424. ofilter->out_tmp->next = NULL;
  425. }
  426. fail:
  427. avfilter_inout_free(&inputs);
  428. avfilter_graph_free(&graph);
  429. return ret;
  430. }
  431. static int insert_trim(int64_t start_time, int64_t duration,
  432. AVFilterContext **last_filter, int *pad_idx,
  433. const char *filter_name)
  434. {
  435. AVFilterGraph *graph = (*last_filter)->graph;
  436. AVFilterContext *ctx;
  437. const AVFilter *trim;
  438. enum AVMediaType type = avfilter_pad_get_type((*last_filter)->output_pads, *pad_idx);
  439. const char *name = (type == AVMEDIA_TYPE_VIDEO) ? "trim" : "atrim";
  440. int ret = 0;
  441. if (duration == INT64_MAX && start_time == AV_NOPTS_VALUE)
  442. return 0;
  443. trim = avfilter_get_by_name(name);
  444. if (!trim) {
  445. av_log(NULL, AV_LOG_ERROR, "%s filter not present, cannot limit "
  446. "recording time.\n", name);
  447. return AVERROR_FILTER_NOT_FOUND;
  448. }
  449. ctx = avfilter_graph_alloc_filter(graph, trim, filter_name);
  450. if (!ctx)
  451. return AVERROR(ENOMEM);
  452. if (duration != INT64_MAX) {
  453. ret = av_opt_set_int(ctx, "durationi", duration,
  454. AV_OPT_SEARCH_CHILDREN);
  455. }
  456. if (ret >= 0 && start_time != AV_NOPTS_VALUE) {
  457. ret = av_opt_set_int(ctx, "starti", start_time,
  458. AV_OPT_SEARCH_CHILDREN);
  459. }
  460. if (ret < 0) {
  461. av_log(ctx, AV_LOG_ERROR, "Error configuring the %s filter", name);
  462. return ret;
  463. }
  464. ret = avfilter_init_str(ctx, NULL);
  465. if (ret < 0)
  466. return ret;
  467. ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
  468. if (ret < 0)
  469. return ret;
  470. *last_filter = ctx;
  471. *pad_idx = 0;
  472. return 0;
  473. }
  474. static int insert_filter(AVFilterContext **last_filter, int *pad_idx,
  475. const char *filter_name, const char *args)
  476. {
  477. AVFilterGraph *graph = (*last_filter)->graph;
  478. AVFilterContext *ctx;
  479. int ret;
  480. ret = avfilter_graph_create_filter(&ctx,
  481. avfilter_get_by_name(filter_name),
  482. filter_name, args, NULL, graph);
  483. if (ret < 0)
  484. return ret;
  485. ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
  486. if (ret < 0)
  487. return ret;
  488. *last_filter = ctx;
  489. *pad_idx = 0;
  490. return 0;
  491. }
  492. static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
  493. {
  494. OutputStream *ost = ofilter->ost;
  495. OutputFile *of = output_files[ost->file_index];
  496. AVFilterContext *last_filter = out->filter_ctx;
  497. AVBPrint bprint;
  498. int pad_idx = out->pad_idx;
  499. int ret;
  500. const char *pix_fmts;
  501. char name[255];
  502. snprintf(name, sizeof(name), "out_%d_%d", ost->file_index, ost->index);
  503. ret = avfilter_graph_create_filter(&ofilter->filter,
  504. avfilter_get_by_name("buffersink"),
  505. name, NULL, NULL, fg->graph);
  506. if (ret < 0)
  507. return ret;
  508. if ((ofilter->width || ofilter->height) && ofilter->ost->autoscale) {
  509. char args[255];
  510. AVFilterContext *filter;
  511. const AVDictionaryEntry *e = NULL;
  512. snprintf(args, sizeof(args), "%d:%d",
  513. ofilter->width, ofilter->height);
  514. while ((e = av_dict_iterate(ost->sws_dict, e))) {
  515. av_strlcatf(args, sizeof(args), ":%s=%s", e->key, e->value);
  516. }
  517. snprintf(name, sizeof(name), "scaler_out_%d_%d",
  518. ost->file_index, ost->index);
  519. if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
  520. name, args, NULL, fg->graph)) < 0)
  521. return ret;
  522. if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
  523. return ret;
  524. last_filter = filter;
  525. pad_idx = 0;
  526. }
  527. av_bprint_init(&bprint, 0, AV_BPRINT_SIZE_UNLIMITED);
  528. if ((pix_fmts = choose_pix_fmts(ofilter, &bprint))) {
  529. AVFilterContext *filter;
  530. ret = avfilter_graph_create_filter(&filter,
  531. avfilter_get_by_name("format"),
  532. "format", pix_fmts, NULL, fg->graph);
  533. av_bprint_finalize(&bprint, NULL);
  534. if (ret < 0)
  535. return ret;
  536. if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
  537. return ret;
  538. last_filter = filter;
  539. pad_idx = 0;
  540. }
  541. if (ost->frame_rate.num && 0) {
  542. AVFilterContext *fps;
  543. char args[255];
  544. snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
  545. ost->frame_rate.den);
  546. snprintf(name, sizeof(name), "fps_out_%d_%d",
  547. ost->file_index, ost->index);
  548. ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
  549. name, args, NULL, fg->graph);
  550. if (ret < 0)
  551. return ret;
  552. ret = avfilter_link(last_filter, pad_idx, fps, 0);
  553. if (ret < 0)
  554. return ret;
  555. last_filter = fps;
  556. pad_idx = 0;
  557. }
  558. snprintf(name, sizeof(name), "trim_out_%d_%d",
  559. ost->file_index, ost->index);
  560. ret = insert_trim(of->start_time, of->recording_time,
  561. &last_filter, &pad_idx, name);
  562. if (ret < 0)
  563. return ret;
  564. if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
  565. return ret;
  566. return 0;
  567. }
  568. static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
  569. {
  570. OutputStream *ost = ofilter->ost;
  571. OutputFile *of = output_files[ost->file_index];
  572. AVCodecContext *codec = ost->enc_ctx;
  573. AVFilterContext *last_filter = out->filter_ctx;
  574. int pad_idx = out->pad_idx;
  575. AVBPrint args;
  576. char name[255];
  577. int ret;
  578. snprintf(name, sizeof(name), "out_%d_%d", ost->file_index, ost->index);
  579. ret = avfilter_graph_create_filter(&ofilter->filter,
  580. avfilter_get_by_name("abuffersink"),
  581. name, NULL, NULL, fg->graph);
  582. if (ret < 0)
  583. return ret;
  584. if ((ret = av_opt_set_int(ofilter->filter, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
  585. return ret;
  586. #define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do { \
  587. AVFilterContext *filt_ctx; \
  588. \
  589. av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi " \
  590. "similarly to -af " filter_name "=%s.\n", arg); \
  591. \
  592. ret = avfilter_graph_create_filter(&filt_ctx, \
  593. avfilter_get_by_name(filter_name), \
  594. filter_name, arg, NULL, fg->graph); \
  595. if (ret < 0) \
  596. goto fail; \
  597. \
  598. ret = avfilter_link(last_filter, pad_idx, filt_ctx, 0); \
  599. if (ret < 0) \
  600. goto fail; \
  601. \
  602. last_filter = filt_ctx; \
  603. pad_idx = 0; \
  604. } while (0)
  605. av_bprint_init(&args, 0, AV_BPRINT_SIZE_UNLIMITED);
  606. #if FFMPEG_OPT_MAP_CHANNEL
  607. if (ost->audio_channels_mapped) {
  608. AVChannelLayout mapped_layout = { 0 };
  609. int i;
  610. av_channel_layout_default(&mapped_layout, ost->audio_channels_mapped);
  611. av_channel_layout_describe_bprint(&mapped_layout, &args);
  612. for (i = 0; i < ost->audio_channels_mapped; i++)
  613. if (ost->audio_channels_map[i] != -1)
  614. av_bprintf(&args, "|c%d=c%d", i, ost->audio_channels_map[i]);
  615. AUTO_INSERT_FILTER("-map_channel", "pan", args.str);
  616. av_bprint_clear(&args);
  617. }
  618. #endif
  619. if (codec->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC)
  620. av_channel_layout_default(&codec->ch_layout, codec->ch_layout.nb_channels);
  621. choose_sample_fmts(ofilter, &args);
  622. choose_sample_rates(ofilter, &args);
  623. choose_channel_layouts(ofilter, &args);
  624. if (!av_bprint_is_complete(&args)) {
  625. ret = AVERROR(ENOMEM);
  626. goto fail;
  627. }
  628. if (args.len) {
  629. AVFilterContext *format;
  630. snprintf(name, sizeof(name), "format_out_%d_%d",
  631. ost->file_index, ost->index);
  632. ret = avfilter_graph_create_filter(&format,
  633. avfilter_get_by_name("aformat"),
  634. name, args.str, NULL, fg->graph);
  635. if (ret < 0)
  636. goto fail;
  637. ret = avfilter_link(last_filter, pad_idx, format, 0);
  638. if (ret < 0)
  639. goto fail;
  640. last_filter = format;
  641. pad_idx = 0;
  642. }
  643. if (ost->apad && of->shortest) {
  644. int i;
  645. for (i = 0; i < of->nb_streams; i++)
  646. if (of->streams[i]->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  647. break;
  648. if (i < of->nb_streams) {
  649. AUTO_INSERT_FILTER("-apad", "apad", ost->apad);
  650. }
  651. }
  652. snprintf(name, sizeof(name), "trim for output stream %d:%d",
  653. ost->file_index, ost->index);
  654. ret = insert_trim(of->start_time, of->recording_time,
  655. &last_filter, &pad_idx, name);
  656. if (ret < 0)
  657. goto fail;
  658. if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
  659. goto fail;
  660. fail:
  661. av_bprint_finalize(&args, NULL);
  662. return ret;
  663. }
  664. static int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter,
  665. AVFilterInOut *out)
  666. {
  667. if (!ofilter->ost) {
  668. av_log(NULL, AV_LOG_FATAL, "Filter %s has an unconnected output\n", ofilter->name);
  669. exit_program(1);
  670. }
  671. switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
  672. case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
  673. case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
  674. default: av_assert0(0); return 0;
  675. }
  676. }
  677. void check_filter_outputs(void)
  678. {
  679. int i;
  680. for (i = 0; i < nb_filtergraphs; i++) {
  681. int n;
  682. for (n = 0; n < filtergraphs[i]->nb_outputs; n++) {
  683. OutputFilter *output = filtergraphs[i]->outputs[n];
  684. if (!output->ost) {
  685. av_log(NULL, AV_LOG_FATAL, "Filter %s has an unconnected output\n", output->name);
  686. exit_program(1);
  687. }
  688. }
  689. }
  690. }
  691. static int sub2video_prepare(InputStream *ist, InputFilter *ifilter)
  692. {
  693. AVFormatContext *avf = input_files[ist->file_index]->ctx;
  694. int i, w, h;
  695. /* Compute the size of the canvas for the subtitles stream.
  696. If the subtitles codecpar has set a size, use it. Otherwise use the
  697. maximum dimensions of the video streams in the same file. */
  698. w = ifilter->width;
  699. h = ifilter->height;
  700. if (!(w && h)) {
  701. for (i = 0; i < avf->nb_streams; i++) {
  702. if (avf->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  703. w = FFMAX(w, avf->streams[i]->codecpar->width);
  704. h = FFMAX(h, avf->streams[i]->codecpar->height);
  705. }
  706. }
  707. if (!(w && h)) {
  708. w = FFMAX(w, 720);
  709. h = FFMAX(h, 576);
  710. }
  711. av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h);
  712. }
  713. ist->sub2video.w = ifilter->width = w;
  714. ist->sub2video.h = ifilter->height = h;
  715. ifilter->width = ist->dec_ctx->width ? ist->dec_ctx->width : ist->sub2video.w;
  716. ifilter->height = ist->dec_ctx->height ? ist->dec_ctx->height : ist->sub2video.h;
  717. /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the
  718. palettes for all rectangles are identical or compatible */
  719. ifilter->format = AV_PIX_FMT_RGB32;
  720. ist->sub2video.frame = av_frame_alloc();
  721. if (!ist->sub2video.frame)
  722. return AVERROR(ENOMEM);
  723. ist->sub2video.last_pts = INT64_MIN;
  724. ist->sub2video.end_pts = INT64_MIN;
  725. /* sub2video structure has been (re-)initialized.
  726. Mark it as such so that the system will be
  727. initialized with the first received heartbeat. */
  728. ist->sub2video.initialize = 1;
  729. return 0;
  730. }
  731. static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
  732. AVFilterInOut *in)
  733. {
  734. AVFilterContext *last_filter;
  735. const AVFilter *buffer_filt = avfilter_get_by_name("buffer");
  736. const AVPixFmtDescriptor *desc;
  737. InputStream *ist = ifilter->ist;
  738. InputFile *f = input_files[ist->file_index];
  739. AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
  740. ist->st->time_base;
  741. AVRational fr = ist->framerate;
  742. AVRational sar;
  743. AVBPrint args;
  744. char name[255];
  745. int ret, pad_idx = 0;
  746. int64_t tsoffset = 0;
  747. AVBufferSrcParameters *par = av_buffersrc_parameters_alloc();
  748. if (!par)
  749. return AVERROR(ENOMEM);
  750. memset(par, 0, sizeof(*par));
  751. par->format = AV_PIX_FMT_NONE;
  752. if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  753. av_log(NULL, AV_LOG_ERROR, "Cannot connect video filter to audio input\n");
  754. ret = AVERROR(EINVAL);
  755. goto fail;
  756. }
  757. if (!fr.num)
  758. fr = ist->framerate_guessed;
  759. if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  760. ret = sub2video_prepare(ist, ifilter);
  761. if (ret < 0)
  762. goto fail;
  763. }
  764. sar = ifilter->sample_aspect_ratio;
  765. if(!sar.den)
  766. sar = (AVRational){0,1};
  767. av_bprint_init(&args, 0, AV_BPRINT_SIZE_AUTOMATIC);
  768. av_bprintf(&args,
  769. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:"
  770. "pixel_aspect=%d/%d",
  771. ifilter->width, ifilter->height, ifilter->format,
  772. tb.num, tb.den, sar.num, sar.den);
  773. if (fr.num && fr.den)
  774. av_bprintf(&args, ":frame_rate=%d/%d", fr.num, fr.den);
  775. snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
  776. ist->file_index, ist->st->index);
  777. if ((ret = avfilter_graph_create_filter(&ifilter->filter, buffer_filt, name,
  778. args.str, NULL, fg->graph)) < 0)
  779. goto fail;
  780. par->hw_frames_ctx = ifilter->hw_frames_ctx;
  781. ret = av_buffersrc_parameters_set(ifilter->filter, par);
  782. if (ret < 0)
  783. goto fail;
  784. av_freep(&par);
  785. last_filter = ifilter->filter;
  786. desc = av_pix_fmt_desc_get(ifilter->format);
  787. av_assert0(desc);
  788. // TODO: insert hwaccel enabled filters like transpose_vaapi into the graph
  789. if (ist->autorotate && !(desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) {
  790. int32_t *displaymatrix = ifilter->displaymatrix;
  791. double theta;
  792. if (!displaymatrix)
  793. displaymatrix = (int32_t *)av_stream_get_side_data(ist->st, AV_PKT_DATA_DISPLAYMATRIX, NULL);
  794. theta = get_rotation(displaymatrix);
  795. if (fabs(theta - 90) < 1.0) {
  796. ret = insert_filter(&last_filter, &pad_idx, "transpose",
  797. displaymatrix[3] > 0 ? "cclock_flip" : "clock");
  798. } else if (fabs(theta - 180) < 1.0) {
  799. if (displaymatrix[0] < 0) {
  800. ret = insert_filter(&last_filter, &pad_idx, "hflip", NULL);
  801. if (ret < 0)
  802. return ret;
  803. }
  804. if (displaymatrix[4] < 0) {
  805. ret = insert_filter(&last_filter, &pad_idx, "vflip", NULL);
  806. }
  807. } else if (fabs(theta - 270) < 1.0) {
  808. ret = insert_filter(&last_filter, &pad_idx, "transpose",
  809. displaymatrix[3] < 0 ? "clock_flip" : "cclock");
  810. } else if (fabs(theta) > 1.0) {
  811. char rotate_buf[64];
  812. snprintf(rotate_buf, sizeof(rotate_buf), "%f*PI/180", theta);
  813. ret = insert_filter(&last_filter, &pad_idx, "rotate", rotate_buf);
  814. } else if (fabs(theta) < 1.0) {
  815. if (displaymatrix && displaymatrix[4] < 0) {
  816. ret = insert_filter(&last_filter, &pad_idx, "vflip", NULL);
  817. }
  818. }
  819. if (ret < 0)
  820. return ret;
  821. }
  822. snprintf(name, sizeof(name), "trim_in_%d_%d",
  823. ist->file_index, ist->st->index);
  824. if (copy_ts) {
  825. tsoffset = f->start_time == AV_NOPTS_VALUE ? 0 : f->start_time;
  826. if (!start_at_zero && f->ctx->start_time != AV_NOPTS_VALUE)
  827. tsoffset += f->ctx->start_time;
  828. }
  829. ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
  830. AV_NOPTS_VALUE : tsoffset, f->recording_time,
  831. &last_filter, &pad_idx, name);
  832. if (ret < 0)
  833. return ret;
  834. if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
  835. return ret;
  836. return 0;
  837. fail:
  838. av_freep(&par);
  839. return ret;
  840. }
  841. static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
  842. AVFilterInOut *in)
  843. {
  844. AVFilterContext *last_filter;
  845. const AVFilter *abuffer_filt = avfilter_get_by_name("abuffer");
  846. InputStream *ist = ifilter->ist;
  847. InputFile *f = input_files[ist->file_index];
  848. AVBPrint args;
  849. char name[255];
  850. int ret, pad_idx = 0;
  851. int64_t tsoffset = 0;
  852. if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_AUDIO) {
  853. av_log(NULL, AV_LOG_ERROR, "Cannot connect audio filter to non audio input\n");
  854. return AVERROR(EINVAL);
  855. }
  856. av_bprint_init(&args, 0, AV_BPRINT_SIZE_AUTOMATIC);
  857. av_bprintf(&args, "time_base=%d/%d:sample_rate=%d:sample_fmt=%s",
  858. 1, ifilter->sample_rate,
  859. ifilter->sample_rate,
  860. av_get_sample_fmt_name(ifilter->format));
  861. if (av_channel_layout_check(&ifilter->ch_layout) &&
  862. ifilter->ch_layout.order != AV_CHANNEL_ORDER_UNSPEC) {
  863. av_bprintf(&args, ":channel_layout=");
  864. av_channel_layout_describe_bprint(&ifilter->ch_layout, &args);
  865. } else
  866. av_bprintf(&args, ":channels=%d", ifilter->ch_layout.nb_channels);
  867. snprintf(name, sizeof(name), "graph_%d_in_%d_%d", fg->index,
  868. ist->file_index, ist->st->index);
  869. if ((ret = avfilter_graph_create_filter(&ifilter->filter, abuffer_filt,
  870. name, args.str, NULL,
  871. fg->graph)) < 0)
  872. return ret;
  873. last_filter = ifilter->filter;
  874. #define AUTO_INSERT_FILTER_INPUT(opt_name, filter_name, arg) do { \
  875. AVFilterContext *filt_ctx; \
  876. \
  877. av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi " \
  878. "similarly to -af " filter_name "=%s.\n", arg); \
  879. \
  880. snprintf(name, sizeof(name), "graph_%d_%s_in_%d_%d", \
  881. fg->index, filter_name, ist->file_index, ist->st->index); \
  882. ret = avfilter_graph_create_filter(&filt_ctx, \
  883. avfilter_get_by_name(filter_name), \
  884. name, arg, NULL, fg->graph); \
  885. if (ret < 0) \
  886. return ret; \
  887. \
  888. ret = avfilter_link(last_filter, 0, filt_ctx, 0); \
  889. if (ret < 0) \
  890. return ret; \
  891. \
  892. last_filter = filt_ctx; \
  893. } while (0)
  894. snprintf(name, sizeof(name), "trim for input stream %d:%d",
  895. ist->file_index, ist->st->index);
  896. if (copy_ts) {
  897. tsoffset = f->start_time == AV_NOPTS_VALUE ? 0 : f->start_time;
  898. if (!start_at_zero && f->ctx->start_time != AV_NOPTS_VALUE)
  899. tsoffset += f->ctx->start_time;
  900. }
  901. ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
  902. AV_NOPTS_VALUE : tsoffset, f->recording_time,
  903. &last_filter, &pad_idx, name);
  904. if (ret < 0)
  905. return ret;
  906. if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
  907. return ret;
  908. return 0;
  909. }
  910. static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
  911. AVFilterInOut *in)
  912. {
  913. if (!ifilter->ist->dec) {
  914. av_log(NULL, AV_LOG_ERROR,
  915. "No decoder for stream #%d:%d, filtering impossible\n",
  916. ifilter->ist->file_index, ifilter->ist->st->index);
  917. return AVERROR_DECODER_NOT_FOUND;
  918. }
  919. switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
  920. case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
  921. case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
  922. default: av_assert0(0); return 0;
  923. }
  924. }
  925. static void cleanup_filtergraph(FilterGraph *fg)
  926. {
  927. int i;
  928. for (i = 0; i < fg->nb_outputs; i++)
  929. fg->outputs[i]->filter = (AVFilterContext *)NULL;
  930. for (i = 0; i < fg->nb_inputs; i++)
  931. fg->inputs[i]->filter = (AVFilterContext *)NULL;
  932. avfilter_graph_free(&fg->graph);
  933. }
  934. static int filter_is_buffersrc(const AVFilterContext *f)
  935. {
  936. return f->nb_inputs == 0 &&
  937. (!strcmp(f->filter->name, "buffer") ||
  938. !strcmp(f->filter->name, "abuffer"));
  939. }
  940. static int graph_is_meta(AVFilterGraph *graph)
  941. {
  942. for (unsigned i = 0; i < graph->nb_filters; i++) {
  943. const AVFilterContext *f = graph->filters[i];
  944. /* in addition to filters flagged as meta, also
  945. * disregard sinks and buffersources (but not other sources,
  946. * since they introduce data we are not aware of)
  947. */
  948. if (!((f->filter->flags & AVFILTER_FLAG_METADATA_ONLY) ||
  949. f->nb_outputs == 0 ||
  950. filter_is_buffersrc(f)))
  951. return 0;
  952. }
  953. return 1;
  954. }
  955. int configure_filtergraph(FilterGraph *fg)
  956. {
  957. AVFilterInOut *inputs, *outputs, *cur;
  958. int ret, i, simple = filtergraph_is_simple(fg);
  959. const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
  960. fg->graph_desc;
  961. cleanup_filtergraph(fg);
  962. if (!(fg->graph = avfilter_graph_alloc()))
  963. return AVERROR(ENOMEM);
  964. if (simple) {
  965. OutputStream *ost = fg->outputs[0]->ost;
  966. if (filter_nbthreads) {
  967. ret = av_opt_set(fg->graph, "threads", filter_nbthreads, 0);
  968. if (ret < 0)
  969. goto fail;
  970. } else {
  971. const AVDictionaryEntry *e = NULL;
  972. e = av_dict_get(ost->encoder_opts, "threads", NULL, 0);
  973. if (e)
  974. av_opt_set(fg->graph, "threads", e->value, 0);
  975. }
  976. if (av_dict_count(ost->sws_dict)) {
  977. ret = av_dict_get_string(ost->sws_dict,
  978. &fg->graph->scale_sws_opts,
  979. '=', ':');
  980. if (ret < 0)
  981. goto fail;
  982. }
  983. if (av_dict_count(ost->swr_opts)) {
  984. char *args;
  985. ret = av_dict_get_string(ost->swr_opts, &args, '=', ':');
  986. if (ret < 0)
  987. goto fail;
  988. av_opt_set(fg->graph, "aresample_swr_opts", args, 0);
  989. av_free(args);
  990. }
  991. } else {
  992. fg->graph->nb_threads = filter_complex_nbthreads;
  993. }
  994. if ((ret = graph_parse(fg->graph, graph_desc, &inputs, &outputs)) < 0)
  995. goto fail;
  996. ret = hw_device_setup_for_filter(fg);
  997. if (ret < 0)
  998. goto fail;
  999. if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
  1000. const char *num_inputs;
  1001. const char *num_outputs;
  1002. if (!outputs) {
  1003. num_outputs = "0";
  1004. } else if (outputs->next) {
  1005. num_outputs = ">1";
  1006. } else {
  1007. num_outputs = "1";
  1008. }
  1009. if (!inputs) {
  1010. num_inputs = "0";
  1011. } else if (inputs->next) {
  1012. num_inputs = ">1";
  1013. } else {
  1014. num_inputs = "1";
  1015. }
  1016. av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' was expected "
  1017. "to have exactly 1 input and 1 output."
  1018. " However, it had %s input(s) and %s output(s)."
  1019. " Please adjust, or use a complex filtergraph (-filter_complex) instead.\n",
  1020. graph_desc, num_inputs, num_outputs);
  1021. ret = AVERROR(EINVAL);
  1022. goto fail;
  1023. }
  1024. for (cur = inputs, i = 0; cur; cur = cur->next, i++)
  1025. if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0) {
  1026. avfilter_inout_free(&inputs);
  1027. avfilter_inout_free(&outputs);
  1028. goto fail;
  1029. }
  1030. avfilter_inout_free(&inputs);
  1031. for (cur = outputs, i = 0; cur; cur = cur->next, i++)
  1032. configure_output_filter(fg, fg->outputs[i], cur);
  1033. avfilter_inout_free(&outputs);
  1034. if (!auto_conversion_filters)
  1035. avfilter_graph_set_auto_convert(fg->graph, AVFILTER_AUTO_CONVERT_NONE);
  1036. if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
  1037. goto fail;
  1038. fg->is_meta = graph_is_meta(fg->graph);
  1039. /* limit the lists of allowed formats to the ones selected, to
  1040. * make sure they stay the same if the filtergraph is reconfigured later */
  1041. for (i = 0; i < fg->nb_outputs; i++) {
  1042. OutputFilter *ofilter = fg->outputs[i];
  1043. AVFilterContext *sink = ofilter->filter;
  1044. ofilter->format = av_buffersink_get_format(sink);
  1045. ofilter->width = av_buffersink_get_w(sink);
  1046. ofilter->height = av_buffersink_get_h(sink);
  1047. ofilter->sample_rate = av_buffersink_get_sample_rate(sink);
  1048. av_channel_layout_uninit(&ofilter->ch_layout);
  1049. ret = av_buffersink_get_ch_layout(sink, &ofilter->ch_layout);
  1050. if (ret < 0)
  1051. goto fail;
  1052. }
  1053. fg->reconfiguration = 1;
  1054. for (i = 0; i < fg->nb_outputs; i++) {
  1055. OutputStream *ost = fg->outputs[i]->ost;
  1056. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO &&
  1057. !(ost->enc_ctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
  1058. av_buffersink_set_frame_size(ost->filter->filter,
  1059. ost->enc_ctx->frame_size);
  1060. }
  1061. for (i = 0; i < fg->nb_inputs; i++) {
  1062. AVFrame *tmp;
  1063. while (av_fifo_read(fg->inputs[i]->frame_queue, &tmp, 1) >= 0) {
  1064. ret = av_buffersrc_add_frame(fg->inputs[i]->filter, tmp);
  1065. av_frame_free(&tmp);
  1066. if (ret < 0)
  1067. goto fail;
  1068. }
  1069. }
  1070. /* send the EOFs for the finished inputs */
  1071. for (i = 0; i < fg->nb_inputs; i++) {
  1072. if (fg->inputs[i]->eof) {
  1073. ret = av_buffersrc_add_frame(fg->inputs[i]->filter, NULL);
  1074. if (ret < 0)
  1075. goto fail;
  1076. }
  1077. }
  1078. /* process queued up subtitle packets */
  1079. for (i = 0; i < fg->nb_inputs; i++) {
  1080. InputStream *ist = fg->inputs[i]->ist;
  1081. if (ist->sub2video.sub_queue && ist->sub2video.frame) {
  1082. AVSubtitle tmp;
  1083. while (av_fifo_read(ist->sub2video.sub_queue, &tmp, 1) >= 0) {
  1084. sub2video_update(ist, INT64_MIN, &tmp);
  1085. avsubtitle_free(&tmp);
  1086. }
  1087. }
  1088. }
  1089. return 0;
  1090. fail:
  1091. cleanup_filtergraph(fg);
  1092. return ret;
  1093. }
  1094. int ifilter_parameters_from_frame(InputFilter *ifilter, const AVFrame *frame)
  1095. {
  1096. AVFrameSideData *sd;
  1097. int ret;
  1098. av_buffer_unref(&ifilter->hw_frames_ctx);
  1099. ifilter->format = frame->format;
  1100. ifilter->width = frame->width;
  1101. ifilter->height = frame->height;
  1102. ifilter->sample_aspect_ratio = frame->sample_aspect_ratio;
  1103. ifilter->sample_rate = frame->sample_rate;
  1104. ret = av_channel_layout_copy(&ifilter->ch_layout, &frame->ch_layout);
  1105. if (ret < 0)
  1106. return ret;
  1107. av_freep(&ifilter->displaymatrix);
  1108. sd = av_frame_get_side_data(frame, AV_FRAME_DATA_DISPLAYMATRIX);
  1109. if (sd)
  1110. ifilter->displaymatrix = av_memdup(sd->data, sizeof(int32_t) * 9);
  1111. if (frame->hw_frames_ctx) {
  1112. ifilter->hw_frames_ctx = av_buffer_ref(frame->hw_frames_ctx);
  1113. if (!ifilter->hw_frames_ctx)
  1114. return AVERROR(ENOMEM);
  1115. }
  1116. return 0;
  1117. }
  1118. int filtergraph_is_simple(FilterGraph *fg)
  1119. {
  1120. return !fg->graph_desc;
  1121. }