ffmpeg_filter.c 39 KB

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