ffmpeg_filter.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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 & AV_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. int init_complex_filtergraph(FilterGraph *fg)
  258. {
  259. AVFilterInOut *inputs, *outputs, *cur;
  260. AVFilterGraph *graph;
  261. int ret = 0;
  262. /* this graph is only used for determining the kinds of inputs
  263. * and outputs we have, and is discarded on exit from this function */
  264. graph = avfilter_graph_alloc();
  265. if (!graph)
  266. return AVERROR(ENOMEM);
  267. ret = avfilter_graph_parse2(graph, fg->graph_desc, &inputs, &outputs);
  268. if (ret < 0)
  269. goto fail;
  270. for (cur = inputs; cur; cur = cur->next)
  271. init_input_filter(fg, cur);
  272. for (cur = outputs; cur;) {
  273. GROW_ARRAY(fg->outputs, fg->nb_outputs);
  274. fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]));
  275. if (!fg->outputs[fg->nb_outputs - 1])
  276. exit_program(1);
  277. fg->outputs[fg->nb_outputs - 1]->graph = fg;
  278. fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
  279. fg->outputs[fg->nb_outputs - 1]->type = avfilter_pad_get_type(cur->filter_ctx->output_pads,
  280. cur->pad_idx);
  281. cur = cur->next;
  282. fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
  283. }
  284. fail:
  285. avfilter_inout_free(&inputs);
  286. avfilter_graph_free(&graph);
  287. return ret;
  288. }
  289. static int insert_trim(int64_t start_time, int64_t duration,
  290. AVFilterContext **last_filter, int *pad_idx,
  291. const char *filter_name)
  292. {
  293. AVFilterGraph *graph = (*last_filter)->graph;
  294. AVFilterContext *ctx;
  295. const AVFilter *trim;
  296. enum AVMediaType type = avfilter_pad_get_type((*last_filter)->output_pads, *pad_idx);
  297. const char *name = (type == AVMEDIA_TYPE_VIDEO) ? "trim" : "atrim";
  298. int ret = 0;
  299. if (duration == INT64_MAX && start_time == AV_NOPTS_VALUE)
  300. return 0;
  301. trim = avfilter_get_by_name(name);
  302. if (!trim) {
  303. av_log(NULL, AV_LOG_ERROR, "%s filter not present, cannot limit "
  304. "recording time.\n", name);
  305. return AVERROR_FILTER_NOT_FOUND;
  306. }
  307. ctx = avfilter_graph_alloc_filter(graph, trim, filter_name);
  308. if (!ctx)
  309. return AVERROR(ENOMEM);
  310. if (duration != INT64_MAX) {
  311. ret = av_opt_set_int(ctx, "durationi", duration,
  312. AV_OPT_SEARCH_CHILDREN);
  313. }
  314. if (ret >= 0 && start_time != AV_NOPTS_VALUE) {
  315. ret = av_opt_set_int(ctx, "starti", start_time,
  316. AV_OPT_SEARCH_CHILDREN);
  317. }
  318. if (ret < 0) {
  319. av_log(ctx, AV_LOG_ERROR, "Error configuring the %s filter", name);
  320. return ret;
  321. }
  322. ret = avfilter_init_str(ctx, NULL);
  323. if (ret < 0)
  324. return ret;
  325. ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
  326. if (ret < 0)
  327. return ret;
  328. *last_filter = ctx;
  329. *pad_idx = 0;
  330. return 0;
  331. }
  332. static int insert_filter(AVFilterContext **last_filter, int *pad_idx,
  333. const char *filter_name, const char *args)
  334. {
  335. AVFilterGraph *graph = (*last_filter)->graph;
  336. AVFilterContext *ctx;
  337. int ret;
  338. ret = avfilter_graph_create_filter(&ctx,
  339. avfilter_get_by_name(filter_name),
  340. filter_name, args, NULL, graph);
  341. if (ret < 0)
  342. return ret;
  343. ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
  344. if (ret < 0)
  345. return ret;
  346. *last_filter = ctx;
  347. *pad_idx = 0;
  348. return 0;
  349. }
  350. static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
  351. {
  352. char *pix_fmts;
  353. OutputStream *ost = ofilter->ost;
  354. OutputFile *of = output_files[ost->file_index];
  355. AVCodecContext *codec = ost->enc_ctx;
  356. AVFilterContext *last_filter = out->filter_ctx;
  357. int pad_idx = out->pad_idx;
  358. int ret;
  359. char name[255];
  360. snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
  361. ret = avfilter_graph_create_filter(&ofilter->filter,
  362. avfilter_get_by_name("buffersink"),
  363. name, NULL, NULL, fg->graph);
  364. if (ret < 0)
  365. return ret;
  366. if (codec->width || codec->height) {
  367. char args[255];
  368. AVFilterContext *filter;
  369. AVDictionaryEntry *e = NULL;
  370. snprintf(args, sizeof(args), "%d:%d",
  371. codec->width,
  372. codec->height);
  373. while ((e = av_dict_get(ost->sws_dict, "", e,
  374. AV_DICT_IGNORE_SUFFIX))) {
  375. av_strlcatf(args, sizeof(args), ":%s=%s", e->key, e->value);
  376. }
  377. snprintf(name, sizeof(name), "scaler for output stream %d:%d",
  378. ost->file_index, ost->index);
  379. if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
  380. name, args, NULL, fg->graph)) < 0)
  381. return ret;
  382. if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
  383. return ret;
  384. last_filter = filter;
  385. pad_idx = 0;
  386. }
  387. if ((pix_fmts = choose_pix_fmts(ost))) {
  388. AVFilterContext *filter;
  389. snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
  390. ost->file_index, ost->index);
  391. ret = avfilter_graph_create_filter(&filter,
  392. avfilter_get_by_name("format"),
  393. "format", pix_fmts, NULL, fg->graph);
  394. av_freep(&pix_fmts);
  395. if (ret < 0)
  396. return ret;
  397. if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
  398. return ret;
  399. last_filter = filter;
  400. pad_idx = 0;
  401. }
  402. if (ost->frame_rate.num && 0) {
  403. AVFilterContext *fps;
  404. char args[255];
  405. snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
  406. ost->frame_rate.den);
  407. snprintf(name, sizeof(name), "fps for output stream %d:%d",
  408. ost->file_index, ost->index);
  409. ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
  410. name, args, NULL, fg->graph);
  411. if (ret < 0)
  412. return ret;
  413. ret = avfilter_link(last_filter, pad_idx, fps, 0);
  414. if (ret < 0)
  415. return ret;
  416. last_filter = fps;
  417. pad_idx = 0;
  418. }
  419. snprintf(name, sizeof(name), "trim for output stream %d:%d",
  420. ost->file_index, ost->index);
  421. ret = insert_trim(of->start_time, of->recording_time,
  422. &last_filter, &pad_idx, name);
  423. if (ret < 0)
  424. return ret;
  425. if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
  426. return ret;
  427. return 0;
  428. }
  429. static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
  430. {
  431. OutputStream *ost = ofilter->ost;
  432. OutputFile *of = output_files[ost->file_index];
  433. AVCodecContext *codec = ost->enc_ctx;
  434. AVFilterContext *last_filter = out->filter_ctx;
  435. int pad_idx = out->pad_idx;
  436. char *sample_fmts, *sample_rates, *channel_layouts;
  437. char name[255];
  438. int ret;
  439. snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
  440. ret = avfilter_graph_create_filter(&ofilter->filter,
  441. avfilter_get_by_name("abuffersink"),
  442. name, NULL, NULL, fg->graph);
  443. if (ret < 0)
  444. return ret;
  445. if ((ret = av_opt_set_int(ofilter->filter, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
  446. return ret;
  447. #define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do { \
  448. AVFilterContext *filt_ctx; \
  449. \
  450. av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi " \
  451. "similarly to -af " filter_name "=%s.\n", arg); \
  452. \
  453. ret = avfilter_graph_create_filter(&filt_ctx, \
  454. avfilter_get_by_name(filter_name), \
  455. filter_name, arg, NULL, fg->graph); \
  456. if (ret < 0) \
  457. return ret; \
  458. \
  459. ret = avfilter_link(last_filter, pad_idx, filt_ctx, 0); \
  460. if (ret < 0) \
  461. return ret; \
  462. \
  463. last_filter = filt_ctx; \
  464. pad_idx = 0; \
  465. } while (0)
  466. if (ost->audio_channels_mapped) {
  467. int i;
  468. AVBPrint pan_buf;
  469. av_bprint_init(&pan_buf, 256, 8192);
  470. av_bprintf(&pan_buf, "0x%"PRIx64,
  471. av_get_default_channel_layout(ost->audio_channels_mapped));
  472. for (i = 0; i < ost->audio_channels_mapped; i++)
  473. if (ost->audio_channels_map[i] != -1)
  474. av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
  475. AUTO_INSERT_FILTER("-map_channel", "pan", pan_buf.str);
  476. av_bprint_finalize(&pan_buf, NULL);
  477. }
  478. if (codec->channels && !codec->channel_layout)
  479. codec->channel_layout = av_get_default_channel_layout(codec->channels);
  480. sample_fmts = choose_sample_fmts(ost);
  481. sample_rates = choose_sample_rates(ost);
  482. channel_layouts = choose_channel_layouts(ost);
  483. if (sample_fmts || sample_rates || channel_layouts) {
  484. AVFilterContext *format;
  485. char args[256];
  486. args[0] = 0;
  487. if (sample_fmts)
  488. av_strlcatf(args, sizeof(args), "sample_fmts=%s:",
  489. sample_fmts);
  490. if (sample_rates)
  491. av_strlcatf(args, sizeof(args), "sample_rates=%s:",
  492. sample_rates);
  493. if (channel_layouts)
  494. av_strlcatf(args, sizeof(args), "channel_layouts=%s:",
  495. channel_layouts);
  496. av_freep(&sample_fmts);
  497. av_freep(&sample_rates);
  498. av_freep(&channel_layouts);
  499. snprintf(name, sizeof(name), "audio format for output stream %d:%d",
  500. ost->file_index, ost->index);
  501. ret = avfilter_graph_create_filter(&format,
  502. avfilter_get_by_name("aformat"),
  503. name, args, NULL, fg->graph);
  504. if (ret < 0)
  505. return ret;
  506. ret = avfilter_link(last_filter, pad_idx, format, 0);
  507. if (ret < 0)
  508. return ret;
  509. last_filter = format;
  510. pad_idx = 0;
  511. }
  512. if (audio_volume != 256 && 0) {
  513. char args[256];
  514. snprintf(args, sizeof(args), "%f", audio_volume / 256.);
  515. AUTO_INSERT_FILTER("-vol", "volume", args);
  516. }
  517. if (ost->apad && of->shortest) {
  518. char args[256];
  519. int i;
  520. for (i=0; i<of->ctx->nb_streams; i++)
  521. if (of->ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  522. break;
  523. if (i<of->ctx->nb_streams) {
  524. snprintf(args, sizeof(args), "%s", ost->apad);
  525. AUTO_INSERT_FILTER("-apad", "apad", args);
  526. }
  527. }
  528. snprintf(name, sizeof(name), "trim for output stream %d:%d",
  529. ost->file_index, ost->index);
  530. ret = insert_trim(of->start_time, of->recording_time,
  531. &last_filter, &pad_idx, name);
  532. if (ret < 0)
  533. return ret;
  534. if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
  535. return ret;
  536. return 0;
  537. }
  538. #define DESCRIBE_FILTER_LINK(f, inout, in) \
  539. { \
  540. AVFilterContext *ctx = inout->filter_ctx; \
  541. AVFilterPad *pads = in ? ctx->input_pads : ctx->output_pads; \
  542. int nb_pads = in ? ctx->nb_inputs : ctx->nb_outputs; \
  543. AVIOContext *pb; \
  544. \
  545. if (avio_open_dyn_buf(&pb) < 0) \
  546. exit_program(1); \
  547. \
  548. avio_printf(pb, "%s", ctx->filter->name); \
  549. if (nb_pads > 1) \
  550. avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
  551. avio_w8(pb, 0); \
  552. avio_close_dyn_buf(pb, &f->name); \
  553. }
  554. int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
  555. {
  556. av_freep(&ofilter->name);
  557. DESCRIBE_FILTER_LINK(ofilter, out, 0);
  558. if (!ofilter->ost) {
  559. av_log(NULL, AV_LOG_FATAL, "Filter %s has a unconnected output\n", ofilter->name);
  560. exit_program(1);
  561. }
  562. switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
  563. case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
  564. case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
  565. default: av_assert0(0);
  566. }
  567. }
  568. static int sub2video_prepare(InputStream *ist)
  569. {
  570. AVFormatContext *avf = input_files[ist->file_index]->ctx;
  571. int i, w, h;
  572. /* Compute the size of the canvas for the subtitles stream.
  573. If the subtitles codec has set a size, use it. Otherwise use the
  574. maximum dimensions of the video streams in the same file. */
  575. w = ist->dec_ctx->width;
  576. h = ist->dec_ctx->height;
  577. if (!(w && h)) {
  578. for (i = 0; i < avf->nb_streams; i++) {
  579. if (avf->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  580. w = FFMAX(w, avf->streams[i]->codec->width);
  581. h = FFMAX(h, avf->streams[i]->codec->height);
  582. }
  583. }
  584. if (!(w && h)) {
  585. w = FFMAX(w, 720);
  586. h = FFMAX(h, 576);
  587. }
  588. av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h);
  589. }
  590. ist->sub2video.w = ist->resample_width = w;
  591. ist->sub2video.h = ist->resample_height = h;
  592. /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the
  593. palettes for all rectangles are identical or compatible */
  594. ist->resample_pix_fmt = ist->dec_ctx->pix_fmt = AV_PIX_FMT_RGB32;
  595. ist->sub2video.frame = av_frame_alloc();
  596. if (!ist->sub2video.frame)
  597. return AVERROR(ENOMEM);
  598. ist->sub2video.last_pts = INT64_MIN;
  599. return 0;
  600. }
  601. static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
  602. AVFilterInOut *in)
  603. {
  604. AVFilterContext *last_filter;
  605. const AVFilter *buffer_filt = avfilter_get_by_name("buffer");
  606. InputStream *ist = ifilter->ist;
  607. InputFile *f = input_files[ist->file_index];
  608. AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
  609. ist->st->time_base;
  610. AVRational fr = ist->framerate;
  611. AVRational sar;
  612. AVBPrint args;
  613. char name[255];
  614. int ret, pad_idx = 0;
  615. int64_t tsoffset = 0;
  616. if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  617. av_log(NULL, AV_LOG_ERROR, "Cannot connect video filter to audio input\n");
  618. return AVERROR(EINVAL);
  619. }
  620. if (!fr.num)
  621. fr = av_guess_frame_rate(input_files[ist->file_index]->ctx, ist->st, NULL);
  622. if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  623. ret = sub2video_prepare(ist);
  624. if (ret < 0)
  625. return ret;
  626. }
  627. sar = ist->st->sample_aspect_ratio.num ?
  628. ist->st->sample_aspect_ratio :
  629. ist->dec_ctx->sample_aspect_ratio;
  630. if(!sar.den)
  631. sar = (AVRational){0,1};
  632. av_bprint_init(&args, 0, 1);
  633. av_bprintf(&args,
  634. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:"
  635. "pixel_aspect=%d/%d:sws_param=flags=%d", ist->resample_width,
  636. ist->resample_height,
  637. ist->hwaccel_retrieve_data ? ist->hwaccel_retrieved_pix_fmt : ist->resample_pix_fmt,
  638. tb.num, tb.den, sar.num, sar.den,
  639. SWS_BILINEAR + ((ist->dec_ctx->flags&AV_CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
  640. if (fr.num && fr.den)
  641. av_bprintf(&args, ":frame_rate=%d/%d", fr.num, fr.den);
  642. snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
  643. ist->file_index, ist->st->index);
  644. if ((ret = avfilter_graph_create_filter(&ifilter->filter, buffer_filt, name,
  645. args.str, NULL, fg->graph)) < 0)
  646. return ret;
  647. last_filter = ifilter->filter;
  648. if (ist->autorotate) {
  649. double theta = get_rotation(ist->st);
  650. if (fabs(theta - 90) < 1.0) {
  651. ret = insert_filter(&last_filter, &pad_idx, "transpose", "clock");
  652. } else if (fabs(theta - 180) < 1.0) {
  653. ret = insert_filter(&last_filter, &pad_idx, "hflip", NULL);
  654. if (ret < 0)
  655. return ret;
  656. ret = insert_filter(&last_filter, &pad_idx, "vflip", NULL);
  657. } else if (fabs(theta - 270) < 1.0) {
  658. ret = insert_filter(&last_filter, &pad_idx, "transpose", "cclock");
  659. } else if (fabs(theta) > 1.0) {
  660. char rotate_buf[64];
  661. snprintf(rotate_buf, sizeof(rotate_buf), "%f*PI/180", theta);
  662. ret = insert_filter(&last_filter, &pad_idx, "rotate", rotate_buf);
  663. }
  664. if (ret < 0)
  665. return ret;
  666. }
  667. if (ist->framerate.num) {
  668. AVFilterContext *setpts;
  669. snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
  670. ist->file_index, ist->st->index);
  671. if ((ret = avfilter_graph_create_filter(&setpts,
  672. avfilter_get_by_name("setpts"),
  673. name, "N", NULL,
  674. fg->graph)) < 0)
  675. return ret;
  676. if ((ret = avfilter_link(last_filter, 0, setpts, 0)) < 0)
  677. return ret;
  678. last_filter = setpts;
  679. }
  680. if (do_deinterlace) {
  681. AVFilterContext *yadif;
  682. snprintf(name, sizeof(name), "deinterlace input from stream %d:%d",
  683. ist->file_index, ist->st->index);
  684. if ((ret = avfilter_graph_create_filter(&yadif,
  685. avfilter_get_by_name("yadif"),
  686. name, "", NULL,
  687. fg->graph)) < 0)
  688. return ret;
  689. if ((ret = avfilter_link(last_filter, 0, yadif, 0)) < 0)
  690. return ret;
  691. last_filter = yadif;
  692. }
  693. snprintf(name, sizeof(name), "trim for input stream %d:%d",
  694. ist->file_index, ist->st->index);
  695. if (copy_ts) {
  696. tsoffset = f->start_time == AV_NOPTS_VALUE ? 0 : f->start_time;
  697. if (!start_at_zero && f->ctx->start_time != AV_NOPTS_VALUE)
  698. tsoffset += f->ctx->start_time;
  699. }
  700. ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
  701. AV_NOPTS_VALUE : tsoffset, f->recording_time,
  702. &last_filter, &pad_idx, name);
  703. if (ret < 0)
  704. return ret;
  705. if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
  706. return ret;
  707. return 0;
  708. }
  709. static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
  710. AVFilterInOut *in)
  711. {
  712. AVFilterContext *last_filter;
  713. const AVFilter *abuffer_filt = avfilter_get_by_name("abuffer");
  714. InputStream *ist = ifilter->ist;
  715. InputFile *f = input_files[ist->file_index];
  716. AVBPrint args;
  717. char name[255];
  718. int ret, pad_idx = 0;
  719. int64_t tsoffset = 0;
  720. if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_AUDIO) {
  721. av_log(NULL, AV_LOG_ERROR, "Cannot connect audio filter to non audio input\n");
  722. return AVERROR(EINVAL);
  723. }
  724. av_bprint_init(&args, 0, AV_BPRINT_SIZE_AUTOMATIC);
  725. av_bprintf(&args, "time_base=%d/%d:sample_rate=%d:sample_fmt=%s",
  726. 1, ist->dec_ctx->sample_rate,
  727. ist->dec_ctx->sample_rate,
  728. av_get_sample_fmt_name(ist->dec_ctx->sample_fmt));
  729. if (ist->dec_ctx->channel_layout)
  730. av_bprintf(&args, ":channel_layout=0x%"PRIx64,
  731. ist->dec_ctx->channel_layout);
  732. else
  733. av_bprintf(&args, ":channels=%d", ist->dec_ctx->channels);
  734. snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
  735. ist->file_index, ist->st->index);
  736. if ((ret = avfilter_graph_create_filter(&ifilter->filter, abuffer_filt,
  737. name, args.str, NULL,
  738. fg->graph)) < 0)
  739. return ret;
  740. last_filter = ifilter->filter;
  741. #define AUTO_INSERT_FILTER_INPUT(opt_name, filter_name, arg) do { \
  742. AVFilterContext *filt_ctx; \
  743. \
  744. av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi " \
  745. "similarly to -af " filter_name "=%s.\n", arg); \
  746. \
  747. snprintf(name, sizeof(name), "graph %d %s for input stream %d:%d", \
  748. fg->index, filter_name, ist->file_index, ist->st->index); \
  749. ret = avfilter_graph_create_filter(&filt_ctx, \
  750. avfilter_get_by_name(filter_name), \
  751. name, arg, NULL, fg->graph); \
  752. if (ret < 0) \
  753. return ret; \
  754. \
  755. ret = avfilter_link(last_filter, 0, filt_ctx, 0); \
  756. if (ret < 0) \
  757. return ret; \
  758. \
  759. last_filter = filt_ctx; \
  760. } while (0)
  761. if (audio_sync_method > 0) {
  762. char args[256] = {0};
  763. av_strlcatf(args, sizeof(args), "async=%d", audio_sync_method);
  764. if (audio_drift_threshold != 0.1)
  765. av_strlcatf(args, sizeof(args), ":min_hard_comp=%f", audio_drift_threshold);
  766. if (!fg->reconfiguration)
  767. av_strlcatf(args, sizeof(args), ":first_pts=0");
  768. AUTO_INSERT_FILTER_INPUT("-async", "aresample", args);
  769. }
  770. // if (ost->audio_channels_mapped) {
  771. // int i;
  772. // AVBPrint pan_buf;
  773. // av_bprint_init(&pan_buf, 256, 8192);
  774. // av_bprintf(&pan_buf, "0x%"PRIx64,
  775. // av_get_default_channel_layout(ost->audio_channels_mapped));
  776. // for (i = 0; i < ost->audio_channels_mapped; i++)
  777. // if (ost->audio_channels_map[i] != -1)
  778. // av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
  779. // AUTO_INSERT_FILTER_INPUT("-map_channel", "pan", pan_buf.str);
  780. // av_bprint_finalize(&pan_buf, NULL);
  781. // }
  782. if (audio_volume != 256) {
  783. char args[256];
  784. av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
  785. "audio filter instead.\n");
  786. snprintf(args, sizeof(args), "%f", audio_volume / 256.);
  787. AUTO_INSERT_FILTER_INPUT("-vol", "volume", args);
  788. }
  789. snprintf(name, sizeof(name), "trim for input stream %d:%d",
  790. ist->file_index, ist->st->index);
  791. if (copy_ts) {
  792. tsoffset = f->start_time == AV_NOPTS_VALUE ? 0 : f->start_time;
  793. if (!start_at_zero && f->ctx->start_time != AV_NOPTS_VALUE)
  794. tsoffset += f->ctx->start_time;
  795. }
  796. ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
  797. AV_NOPTS_VALUE : tsoffset, f->recording_time,
  798. &last_filter, &pad_idx, name);
  799. if (ret < 0)
  800. return ret;
  801. if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
  802. return ret;
  803. return 0;
  804. }
  805. static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
  806. AVFilterInOut *in)
  807. {
  808. av_freep(&ifilter->name);
  809. DESCRIBE_FILTER_LINK(ifilter, in, 1);
  810. if (!ifilter->ist->dec) {
  811. av_log(NULL, AV_LOG_ERROR,
  812. "No decoder for stream #%d:%d, filtering impossible\n",
  813. ifilter->ist->file_index, ifilter->ist->st->index);
  814. return AVERROR_DECODER_NOT_FOUND;
  815. }
  816. switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
  817. case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
  818. case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
  819. default: av_assert0(0);
  820. }
  821. }
  822. int configure_filtergraph(FilterGraph *fg)
  823. {
  824. AVFilterInOut *inputs, *outputs, *cur;
  825. int ret, i, simple = !fg->graph_desc;
  826. const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
  827. fg->graph_desc;
  828. avfilter_graph_free(&fg->graph);
  829. if (!(fg->graph = avfilter_graph_alloc()))
  830. return AVERROR(ENOMEM);
  831. if (simple) {
  832. OutputStream *ost = fg->outputs[0]->ost;
  833. char args[512];
  834. AVDictionaryEntry *e = NULL;
  835. args[0] = 0;
  836. while ((e = av_dict_get(ost->sws_dict, "", e,
  837. AV_DICT_IGNORE_SUFFIX))) {
  838. av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
  839. }
  840. if (strlen(args))
  841. args[strlen(args)-1] = 0;
  842. fg->graph->scale_sws_opts = av_strdup(args);
  843. args[0] = 0;
  844. while ((e = av_dict_get(ost->swr_opts, "", e,
  845. AV_DICT_IGNORE_SUFFIX))) {
  846. av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
  847. }
  848. if (strlen(args))
  849. args[strlen(args)-1] = 0;
  850. av_opt_set(fg->graph, "aresample_swr_opts", args, 0);
  851. args[0] = '\0';
  852. while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
  853. AV_DICT_IGNORE_SUFFIX))) {
  854. av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
  855. }
  856. if (strlen(args))
  857. args[strlen(args) - 1] = '\0';
  858. fg->graph->resample_lavr_opts = av_strdup(args);
  859. e = av_dict_get(ost->encoder_opts, "threads", NULL, 0);
  860. if (e)
  861. av_opt_set(fg->graph, "threads", e->value, 0);
  862. }
  863. if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
  864. return ret;
  865. if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
  866. const char *num_inputs;
  867. const char *num_outputs;
  868. if (!outputs) {
  869. num_outputs = "0";
  870. } else if (outputs->next) {
  871. num_outputs = ">1";
  872. } else {
  873. num_outputs = "1";
  874. }
  875. if (!inputs) {
  876. num_inputs = "0";
  877. } else if (inputs->next) {
  878. num_inputs = ">1";
  879. } else {
  880. num_inputs = "1";
  881. }
  882. av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' was expected "
  883. "to have exactly 1 input and 1 output."
  884. " However, it had %s input(s) and %s output(s)."
  885. " Please adjust, or use a complex filtergraph (-filter_complex) instead.\n",
  886. graph_desc, num_inputs, num_outputs);
  887. return AVERROR(EINVAL);
  888. }
  889. for (cur = inputs, i = 0; cur; cur = cur->next, i++)
  890. if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0) {
  891. avfilter_inout_free(&inputs);
  892. avfilter_inout_free(&outputs);
  893. return ret;
  894. }
  895. avfilter_inout_free(&inputs);
  896. for (cur = outputs, i = 0; cur; cur = cur->next, i++)
  897. configure_output_filter(fg, fg->outputs[i], cur);
  898. avfilter_inout_free(&outputs);
  899. if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
  900. return ret;
  901. fg->reconfiguration = 1;
  902. for (i = 0; i < fg->nb_outputs; i++) {
  903. OutputStream *ost = fg->outputs[i]->ost;
  904. if (ost &&
  905. ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  906. !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
  907. av_buffersink_set_frame_size(ost->filter->filter,
  908. ost->enc_ctx->frame_size);
  909. }
  910. return 0;
  911. }
  912. int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
  913. {
  914. int i;
  915. for (i = 0; i < fg->nb_inputs; i++)
  916. if (fg->inputs[i]->ist == ist)
  917. return 1;
  918. return 0;
  919. }