ffmpeg_mux_init.c 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403
  1. /*
  2. * Muxer/output file setup.
  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 <string.h>
  21. #include "cmdutils.h"
  22. #include "ffmpeg.h"
  23. #include "ffmpeg_mux.h"
  24. #include "fopen_utf8.h"
  25. #include "libavformat/avformat.h"
  26. #include "libavformat/avio.h"
  27. #include "libavcodec/avcodec.h"
  28. #include "libavfilter/avfilter.h"
  29. #include "libavutil/avassert.h"
  30. #include "libavutil/avstring.h"
  31. #include "libavutil/avutil.h"
  32. #include "libavutil/bprint.h"
  33. #include "libavutil/dict.h"
  34. #include "libavutil/getenv_utf8.h"
  35. #include "libavutil/intreadwrite.h"
  36. #include "libavutil/log.h"
  37. #include "libavutil/mem.h"
  38. #include "libavutil/opt.h"
  39. #include "libavutil/parseutils.h"
  40. #include "libavutil/pixdesc.h"
  41. #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
  42. static const char *const opt_name_apad[] = {"apad", NULL};
  43. static const char *const opt_name_autoscale[] = {"autoscale", NULL};
  44. static const char *const opt_name_bits_per_raw_sample[] = {"bits_per_raw_sample", NULL};
  45. static const char *const opt_name_bitstream_filters[] = {"bsf", "absf", "vbsf", NULL};
  46. static const char *const opt_name_copy_initial_nonkeyframes[] = {"copyinkf", NULL};
  47. static const char *const opt_name_copy_prior_start[] = {"copypriorss", NULL};
  48. static const char *const opt_name_disposition[] = {"disposition", NULL};
  49. static const char *const opt_name_enc_time_bases[] = {"enc_time_base", NULL};
  50. static const char *const opt_name_enc_stats_pre[] = {"enc_stats_pre", NULL};
  51. static const char *const opt_name_enc_stats_post[] = {"enc_stats_post", NULL};
  52. static const char *const opt_name_mux_stats[] = {"mux_stats", NULL};
  53. static const char *const opt_name_enc_stats_pre_fmt[] = {"enc_stats_pre_fmt", NULL};
  54. static const char *const opt_name_enc_stats_post_fmt[] = {"enc_stats_post_fmt", NULL};
  55. static const char *const opt_name_mux_stats_fmt[] = {"mux_stats_fmt", NULL};
  56. static const char *const opt_name_filters[] = {"filter", "af", "vf", NULL};
  57. static const char *const opt_name_filter_scripts[] = {"filter_script", NULL};
  58. static const char *const opt_name_fix_sub_duration_heartbeat[] = {"fix_sub_duration_heartbeat", NULL};
  59. static const char *const opt_name_fps_mode[] = {"fps_mode", NULL};
  60. static const char *const opt_name_force_fps[] = {"force_fps", NULL};
  61. static const char *const opt_name_forced_key_frames[] = {"forced_key_frames", NULL};
  62. static const char *const opt_name_frame_aspect_ratios[] = {"aspect", NULL};
  63. static const char *const opt_name_intra_matrices[] = {"intra_matrix", NULL};
  64. static const char *const opt_name_inter_matrices[] = {"inter_matrix", NULL};
  65. static const char *const opt_name_chroma_intra_matrices[] = {"chroma_intra_matrix", NULL};
  66. static const char *const opt_name_max_frame_rates[] = {"fpsmax", NULL};
  67. static const char *const opt_name_max_frames[] = {"frames", "aframes", "vframes", "dframes", NULL};
  68. static const char *const opt_name_max_muxing_queue_size[] = {"max_muxing_queue_size", NULL};
  69. static const char *const opt_name_muxing_queue_data_threshold[] = {"muxing_queue_data_threshold", NULL};
  70. static const char *const opt_name_pass[] = {"pass", NULL};
  71. static const char *const opt_name_passlogfiles[] = {"passlogfile", NULL};
  72. static const char *const opt_name_presets[] = {"pre", "apre", "vpre", "spre", NULL};
  73. static const char *const opt_name_qscale[] = {"q", "qscale", NULL};
  74. static const char *const opt_name_rc_overrides[] = {"rc_override", NULL};
  75. static const char *const opt_name_time_bases[] = {"time_base", NULL};
  76. static const char *const opt_name_audio_channels[] = {"ac", NULL};
  77. static const char *const opt_name_audio_ch_layouts[] = {"channel_layout", "ch_layout", NULL};
  78. static const char *const opt_name_audio_sample_rate[] = {"ar", NULL};
  79. static const char *const opt_name_frame_sizes[] = {"s", NULL};
  80. static const char *const opt_name_frame_pix_fmts[] = {"pix_fmt", NULL};
  81. static const char *const opt_name_sample_fmts[] = {"sample_fmt", NULL};
  82. static int check_opt_bitexact(void *ctx, const AVDictionary *opts,
  83. const char *opt_name, int flag)
  84. {
  85. const AVDictionaryEntry *e = av_dict_get(opts, opt_name, NULL, 0);
  86. if (e) {
  87. const AVOption *o = av_opt_find(ctx, opt_name, NULL, 0, 0);
  88. int val = 0;
  89. if (!o)
  90. return 0;
  91. av_opt_eval_flags(ctx, o, e->value, &val);
  92. return !!(val & flag);
  93. }
  94. return 0;
  95. }
  96. static int choose_encoder(const OptionsContext *o, AVFormatContext *s,
  97. OutputStream *ost, const AVCodec **enc)
  98. {
  99. enum AVMediaType type = ost->st->codecpar->codec_type;
  100. char *codec_name = NULL;
  101. *enc = NULL;
  102. if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO || type == AVMEDIA_TYPE_SUBTITLE) {
  103. MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
  104. if (!codec_name) {
  105. ost->st->codecpar->codec_id = av_guess_codec(s->oformat, NULL, s->url,
  106. NULL, ost->st->codecpar->codec_type);
  107. *enc = avcodec_find_encoder(ost->st->codecpar->codec_id);
  108. if (!*enc) {
  109. av_log(ost, AV_LOG_FATAL, "Automatic encoder selection failed "
  110. "Default encoder for format %s (codec %s) is "
  111. "probably disabled. Please choose an encoder manually.\n",
  112. s->oformat->name, avcodec_get_name(ost->st->codecpar->codec_id));
  113. return AVERROR_ENCODER_NOT_FOUND;
  114. }
  115. } else if (strcmp(codec_name, "copy")) {
  116. *enc = find_codec_or_die(ost, codec_name, ost->st->codecpar->codec_type, 1);
  117. ost->st->codecpar->codec_id = (*enc)->id;
  118. }
  119. }
  120. return 0;
  121. }
  122. static char *get_line(AVIOContext *s, AVBPrint *bprint)
  123. {
  124. char c;
  125. while ((c = avio_r8(s)) && c != '\n')
  126. av_bprint_chars(bprint, c, 1);
  127. if (!av_bprint_is_complete(bprint))
  128. report_and_exit(AVERROR(ENOMEM));
  129. return bprint->str;
  130. }
  131. static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
  132. {
  133. int i, ret = -1;
  134. char filename[1000];
  135. char *env_avconv_datadir = getenv_utf8("AVCONV_DATADIR");
  136. char *env_home = getenv_utf8("HOME");
  137. const char *base[3] = { env_avconv_datadir,
  138. env_home,
  139. AVCONV_DATADIR,
  140. };
  141. for (i = 0; i < FF_ARRAY_ELEMS(base) && ret < 0; i++) {
  142. if (!base[i])
  143. continue;
  144. if (codec_name) {
  145. snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
  146. i != 1 ? "" : "/.avconv", codec_name, preset_name);
  147. ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
  148. }
  149. if (ret < 0) {
  150. snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
  151. i != 1 ? "" : "/.avconv", preset_name);
  152. ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
  153. }
  154. }
  155. freeenv_utf8(env_home);
  156. freeenv_utf8(env_avconv_datadir);
  157. return ret;
  158. }
  159. typedef struct EncStatsFile {
  160. char *path;
  161. AVIOContext *io;
  162. } EncStatsFile;
  163. static EncStatsFile *enc_stats_files;
  164. static int nb_enc_stats_files;
  165. static int enc_stats_get_file(AVIOContext **io, const char *path)
  166. {
  167. EncStatsFile *esf;
  168. int ret;
  169. for (int i = 0; i < nb_enc_stats_files; i++)
  170. if (!strcmp(path, enc_stats_files[i].path)) {
  171. *io = enc_stats_files[i].io;
  172. return 0;
  173. }
  174. GROW_ARRAY(enc_stats_files, nb_enc_stats_files);
  175. esf = &enc_stats_files[nb_enc_stats_files - 1];
  176. ret = avio_open2(&esf->io, path, AVIO_FLAG_WRITE, &int_cb, NULL);
  177. if (ret < 0) {
  178. av_log(NULL, AV_LOG_ERROR, "Error opening stats file '%s': %s\n",
  179. path, av_err2str(ret));
  180. return ret;
  181. }
  182. esf->path = av_strdup(path);
  183. if (!esf->path)
  184. return AVERROR(ENOMEM);
  185. *io = esf->io;
  186. return 0;
  187. }
  188. void of_enc_stats_close(void)
  189. {
  190. for (int i = 0; i < nb_enc_stats_files; i++) {
  191. av_freep(&enc_stats_files[i].path);
  192. avio_closep(&enc_stats_files[i].io);
  193. }
  194. av_freep(&enc_stats_files);
  195. nb_enc_stats_files = 0;
  196. }
  197. static int unescape(char **pdst, size_t *dst_len,
  198. const char **pstr, char delim)
  199. {
  200. const char *str = *pstr;
  201. char *dst;
  202. size_t len, idx;
  203. *pdst = NULL;
  204. len = strlen(str);
  205. if (!len)
  206. return 0;
  207. dst = av_malloc(len + 1);
  208. if (!dst)
  209. return AVERROR(ENOMEM);
  210. for (idx = 0; *str; idx++, str++) {
  211. if (str[0] == '\\' && str[1])
  212. str++;
  213. else if (*str == delim)
  214. break;
  215. dst[idx] = *str;
  216. }
  217. if (!idx) {
  218. av_freep(&dst);
  219. return 0;
  220. }
  221. dst[idx] = 0;
  222. *pdst = dst;
  223. *dst_len = idx;
  224. *pstr = str;
  225. return 0;
  226. }
  227. static int enc_stats_init(OutputStream *ost, EncStats *es, int pre,
  228. const char *path, const char *fmt_spec)
  229. {
  230. static const struct {
  231. enum EncStatsType type;
  232. const char *str;
  233. int pre_only:1;
  234. int post_only:1;
  235. int need_input_data:1;
  236. } fmt_specs[] = {
  237. { ENC_STATS_FILE_IDX, "fidx" },
  238. { ENC_STATS_STREAM_IDX, "sidx" },
  239. { ENC_STATS_FRAME_NUM, "n" },
  240. { ENC_STATS_FRAME_NUM_IN, "ni", 0, 0, 1 },
  241. { ENC_STATS_TIMEBASE, "tb" },
  242. { ENC_STATS_TIMEBASE_IN, "tbi", 0, 0, 1 },
  243. { ENC_STATS_PTS, "pts" },
  244. { ENC_STATS_PTS_TIME, "t" },
  245. { ENC_STATS_PTS_IN, "ptsi", 0, 0, 1 },
  246. { ENC_STATS_PTS_TIME_IN, "ti", 0, 0, 1 },
  247. { ENC_STATS_DTS, "dts", 0, 1 },
  248. { ENC_STATS_DTS_TIME, "dt", 0, 1 },
  249. { ENC_STATS_SAMPLE_NUM, "sn", 1 },
  250. { ENC_STATS_NB_SAMPLES, "samp", 1 },
  251. { ENC_STATS_PKT_SIZE, "size", 0, 1 },
  252. { ENC_STATS_BITRATE, "br", 0, 1 },
  253. { ENC_STATS_AVG_BITRATE, "abr", 0, 1 },
  254. };
  255. const char *next = fmt_spec;
  256. int ret;
  257. while (*next) {
  258. EncStatsComponent *c;
  259. char *val;
  260. size_t val_len;
  261. // get the sequence up until next opening brace
  262. ret = unescape(&val, &val_len, &next, '{');
  263. if (ret < 0)
  264. return ret;
  265. if (val) {
  266. GROW_ARRAY(es->components, es->nb_components);
  267. c = &es->components[es->nb_components - 1];
  268. c->type = ENC_STATS_LITERAL;
  269. c->str = val;
  270. c->str_len = val_len;
  271. }
  272. if (!*next)
  273. break;
  274. next++;
  275. // get the part inside braces
  276. ret = unescape(&val, &val_len, &next, '}');
  277. if (ret < 0)
  278. return ret;
  279. if (!val) {
  280. av_log(NULL, AV_LOG_ERROR,
  281. "Empty formatting directive in: %s\n", fmt_spec);
  282. return AVERROR(EINVAL);
  283. }
  284. if (!*next) {
  285. av_log(NULL, AV_LOG_ERROR,
  286. "Missing closing brace in: %s\n", fmt_spec);
  287. ret = AVERROR(EINVAL);
  288. goto fail;
  289. }
  290. next++;
  291. GROW_ARRAY(es->components, es->nb_components);
  292. c = &es->components[es->nb_components - 1];
  293. for (size_t i = 0; i < FF_ARRAY_ELEMS(fmt_specs); i++) {
  294. if (!strcmp(val, fmt_specs[i].str)) {
  295. if ((pre && fmt_specs[i].post_only) || (!pre && fmt_specs[i].pre_only)) {
  296. av_log(NULL, AV_LOG_ERROR,
  297. "Format directive '%s' may only be used %s-encoding\n",
  298. val, pre ? "post" : "pre");
  299. ret = AVERROR(EINVAL);
  300. goto fail;
  301. }
  302. c->type = fmt_specs[i].type;
  303. if (fmt_specs[i].need_input_data) {
  304. if (ost->ist)
  305. ost->ist->want_frame_data = 1;
  306. else {
  307. av_log(ost, AV_LOG_WARNING,
  308. "Format directive '%s' is unavailable, because "
  309. "this output stream has no associated input stream\n",
  310. val);
  311. }
  312. }
  313. break;
  314. }
  315. }
  316. if (!c->type) {
  317. av_log(NULL, AV_LOG_ERROR, "Invalid format directive: %s\n", val);
  318. ret = AVERROR(EINVAL);
  319. goto fail;
  320. }
  321. fail:
  322. av_freep(&val);
  323. if (ret < 0)
  324. return ret;
  325. }
  326. ret = enc_stats_get_file(&es->io, path);
  327. if (ret < 0)
  328. return ret;
  329. return 0;
  330. }
  331. static const char *output_stream_item_name(void *obj)
  332. {
  333. const MuxStream *ms = obj;
  334. return ms->log_name;
  335. }
  336. static const AVClass output_stream_class = {
  337. .class_name = "OutputStream",
  338. .version = LIBAVUTIL_VERSION_INT,
  339. .item_name = output_stream_item_name,
  340. .category = AV_CLASS_CATEGORY_MUXER,
  341. };
  342. static MuxStream *mux_stream_alloc(Muxer *mux, enum AVMediaType type)
  343. {
  344. const char *type_str = av_get_media_type_string(type);
  345. MuxStream *ms = allocate_array_elem(&mux->of.streams, sizeof(*ms),
  346. &mux->of.nb_streams);
  347. ms->ost.file_index = mux->of.index;
  348. ms->ost.index = mux->of.nb_streams - 1;
  349. ms->ost.class = &output_stream_class;
  350. snprintf(ms->log_name, sizeof(ms->log_name), "%cost#%d:%d",
  351. type_str ? *type_str : '?', mux->of.index, ms->ost.index);
  352. return ms;
  353. }
  354. static OutputStream *new_output_stream(Muxer *mux, const OptionsContext *o,
  355. enum AVMediaType type, InputStream *ist)
  356. {
  357. AVFormatContext *oc = mux->fc;
  358. MuxStream *ms;
  359. OutputStream *ost;
  360. const AVCodec *enc;
  361. AVStream *st = avformat_new_stream(oc, NULL);
  362. int ret = 0;
  363. const char *bsfs = NULL, *time_base = NULL;
  364. char *next, *codec_tag = NULL;
  365. double qscale = -1;
  366. int i;
  367. if (!st)
  368. report_and_exit(AVERROR(ENOMEM));
  369. if (oc->nb_streams - 1 < o->nb_streamid_map)
  370. st->id = o->streamid_map[oc->nb_streams - 1];
  371. ms = mux_stream_alloc(mux, type);
  372. ost = &ms->ost;
  373. ms->muxing_queue = av_fifo_alloc2(8, sizeof(AVPacket*), 0);
  374. if (!ms->muxing_queue)
  375. report_and_exit(AVERROR(ENOMEM));
  376. ms->last_mux_dts = AV_NOPTS_VALUE;
  377. ost->st = st;
  378. ost->ist = ist;
  379. ost->kf.ref_pts = AV_NOPTS_VALUE;
  380. st->codecpar->codec_type = type;
  381. ret = choose_encoder(o, oc, ost, &enc);
  382. if (ret < 0) {
  383. av_log(ost, AV_LOG_FATAL, "Error selecting an encoder\n");
  384. exit_program(1);
  385. }
  386. if (enc) {
  387. ost->enc_ctx = avcodec_alloc_context3(enc);
  388. if (!ost->enc_ctx)
  389. report_and_exit(AVERROR(ENOMEM));
  390. av_strlcat(ms->log_name, "/", sizeof(ms->log_name));
  391. av_strlcat(ms->log_name, enc->name, sizeof(ms->log_name));
  392. } else {
  393. av_strlcat(ms->log_name, "/copy", sizeof(ms->log_name));
  394. }
  395. ost->filtered_frame = av_frame_alloc();
  396. if (!ost->filtered_frame)
  397. report_and_exit(AVERROR(ENOMEM));
  398. ost->pkt = av_packet_alloc();
  399. if (!ost->pkt)
  400. report_and_exit(AVERROR(ENOMEM));
  401. if (ost->enc_ctx) {
  402. AVCodecContext *enc = ost->enc_ctx;
  403. AVIOContext *s = NULL;
  404. char *buf = NULL, *arg = NULL, *preset = NULL;
  405. const char *enc_stats_pre = NULL, *enc_stats_post = NULL, *mux_stats = NULL;
  406. ost->encoder_opts = filter_codec_opts(o->g->codec_opts, enc->codec_id,
  407. oc, st, enc->codec);
  408. MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
  409. ost->autoscale = 1;
  410. MATCH_PER_STREAM_OPT(autoscale, i, ost->autoscale, oc, st);
  411. if (preset && (!(ret = get_preset_file_2(preset, enc->codec->name, &s)))) {
  412. AVBPrint bprint;
  413. av_bprint_init(&bprint, 0, AV_BPRINT_SIZE_UNLIMITED);
  414. do {
  415. av_bprint_clear(&bprint);
  416. buf = get_line(s, &bprint);
  417. if (!buf[0] || buf[0] == '#')
  418. continue;
  419. if (!(arg = strchr(buf, '='))) {
  420. av_log(ost, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
  421. exit_program(1);
  422. }
  423. *arg++ = 0;
  424. av_dict_set(&ost->encoder_opts, buf, arg, AV_DICT_DONT_OVERWRITE);
  425. } while (!s->eof_reached);
  426. av_bprint_finalize(&bprint, NULL);
  427. avio_closep(&s);
  428. }
  429. if (ret) {
  430. av_log(ost, AV_LOG_FATAL,
  431. "Preset %s specified, but could not be opened.\n", preset);
  432. exit_program(1);
  433. }
  434. MATCH_PER_STREAM_OPT(enc_stats_pre, str, enc_stats_pre, oc, st);
  435. if (enc_stats_pre &&
  436. (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)) {
  437. const char *format = "{fidx} {sidx} {n} {t}";
  438. MATCH_PER_STREAM_OPT(enc_stats_pre_fmt, str, format, oc, st);
  439. ret = enc_stats_init(ost, &ost->enc_stats_pre, 1, enc_stats_pre, format);
  440. if (ret < 0)
  441. exit_program(1);
  442. }
  443. MATCH_PER_STREAM_OPT(enc_stats_post, str, enc_stats_post, oc, st);
  444. if (enc_stats_post &&
  445. (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)) {
  446. const char *format = "{fidx} {sidx} {n} {t}";
  447. MATCH_PER_STREAM_OPT(enc_stats_post_fmt, str, format, oc, st);
  448. ret = enc_stats_init(ost, &ost->enc_stats_post, 0, enc_stats_post, format);
  449. if (ret < 0)
  450. exit_program(1);
  451. }
  452. MATCH_PER_STREAM_OPT(mux_stats, str, mux_stats, oc, st);
  453. if (mux_stats &&
  454. (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)) {
  455. const char *format = "{fidx} {sidx} {n} {t}";
  456. MATCH_PER_STREAM_OPT(mux_stats_fmt, str, format, oc, st);
  457. ret = enc_stats_init(ost, &ms->stats, 0, mux_stats, format);
  458. if (ret < 0)
  459. exit_program(1);
  460. }
  461. } else {
  462. ost->encoder_opts = filter_codec_opts(o->g->codec_opts, AV_CODEC_ID_NONE, oc, st, NULL);
  463. }
  464. if (o->bitexact) {
  465. ost->bitexact = 1;
  466. } else if (ost->enc_ctx) {
  467. ost->bitexact = check_opt_bitexact(ost->enc_ctx, ost->encoder_opts, "flags",
  468. AV_CODEC_FLAG_BITEXACT);
  469. }
  470. MATCH_PER_STREAM_OPT(time_bases, str, time_base, oc, st);
  471. if (time_base) {
  472. AVRational q;
  473. if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
  474. q.num <= 0 || q.den <= 0) {
  475. av_log(ost, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
  476. exit_program(1);
  477. }
  478. st->time_base = q;
  479. }
  480. MATCH_PER_STREAM_OPT(enc_time_bases, str, time_base, oc, st);
  481. if (time_base) {
  482. AVRational q;
  483. if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
  484. q.den <= 0) {
  485. av_log(ost, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
  486. exit_program(1);
  487. }
  488. ost->enc_timebase = q;
  489. }
  490. ms->max_frames = INT64_MAX;
  491. MATCH_PER_STREAM_OPT(max_frames, i64, ms->max_frames, oc, st);
  492. for (i = 0; i<o->nb_max_frames; i++) {
  493. char *p = o->max_frames[i].specifier;
  494. if (!*p && type != AVMEDIA_TYPE_VIDEO) {
  495. av_log(ost, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");
  496. break;
  497. }
  498. }
  499. ost->copy_prior_start = -1;
  500. MATCH_PER_STREAM_OPT(copy_prior_start, i, ost->copy_prior_start, oc ,st);
  501. MATCH_PER_STREAM_OPT(bitstream_filters, str, bsfs, oc, st);
  502. if (bsfs && *bsfs) {
  503. ret = av_bsf_list_parse_str(bsfs, &ms->bsf_ctx);
  504. if (ret < 0) {
  505. av_log(ost, AV_LOG_ERROR, "Error parsing bitstream filter sequence '%s': %s\n", bsfs, av_err2str(ret));
  506. exit_program(1);
  507. }
  508. }
  509. MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
  510. if (codec_tag) {
  511. uint32_t tag = strtol(codec_tag, &next, 0);
  512. if (*next) {
  513. uint8_t buf[4] = { 0 };
  514. memcpy(buf, codec_tag, FFMIN(sizeof(buf), strlen(codec_tag)));
  515. tag = AV_RL32(buf);
  516. }
  517. ost->st->codecpar->codec_tag = tag;
  518. if (ost->enc_ctx)
  519. ost->enc_ctx->codec_tag = tag;
  520. }
  521. MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
  522. if (ost->enc_ctx && qscale >= 0) {
  523. ost->enc_ctx->flags |= AV_CODEC_FLAG_QSCALE;
  524. ost->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;
  525. }
  526. ms->max_muxing_queue_size = 128;
  527. MATCH_PER_STREAM_OPT(max_muxing_queue_size, i, ms->max_muxing_queue_size, oc, st);
  528. ms->muxing_queue_data_threshold = 50*1024*1024;
  529. MATCH_PER_STREAM_OPT(muxing_queue_data_threshold, i, ms->muxing_queue_data_threshold, oc, st);
  530. MATCH_PER_STREAM_OPT(bits_per_raw_sample, i, ost->bits_per_raw_sample,
  531. oc, st);
  532. MATCH_PER_STREAM_OPT(fix_sub_duration_heartbeat, i, ost->fix_sub_duration_heartbeat,
  533. oc, st);
  534. if (oc->oformat->flags & AVFMT_GLOBALHEADER && ost->enc_ctx)
  535. ost->enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  536. av_dict_copy(&ost->sws_dict, o->g->sws_dict, 0);
  537. av_dict_copy(&ost->swr_opts, o->g->swr_opts, 0);
  538. if (ost->enc_ctx && av_get_exact_bits_per_sample(ost->enc_ctx->codec_id) == 24)
  539. av_dict_set(&ost->swr_opts, "output_sample_bits", "24", 0);
  540. if (ost->ist) {
  541. ost->ist->discard = 0;
  542. ost->ist->st->discard = ost->ist->user_set_discard;
  543. }
  544. ost->last_mux_dts = AV_NOPTS_VALUE;
  545. ost->last_filter_pts = AV_NOPTS_VALUE;
  546. MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i,
  547. ost->copy_initial_nonkeyframes, oc, st);
  548. return ost;
  549. }
  550. static char *get_ost_filters(const OptionsContext *o, AVFormatContext *oc,
  551. OutputStream *ost)
  552. {
  553. AVStream *st = ost->st;
  554. if (ost->filters_script && ost->filters) {
  555. av_log(ost, AV_LOG_ERROR, "Both -filter and -filter_script set\n");
  556. exit_program(1);
  557. }
  558. if (ost->filters_script)
  559. return file_read(ost->filters_script);
  560. else if (ost->filters)
  561. return av_strdup(ost->filters);
  562. return av_strdup(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ?
  563. "null" : "anull");
  564. }
  565. static void check_streamcopy_filters(const OptionsContext *o, AVFormatContext *oc,
  566. OutputStream *ost, enum AVMediaType type)
  567. {
  568. if (ost->filters_script || ost->filters) {
  569. av_log(ost, AV_LOG_ERROR,
  570. "%s '%s' was defined, but codec copy was selected.\n"
  571. "Filtering and streamcopy cannot be used together.\n",
  572. ost->filters ? "Filtergraph" : "Filtergraph script",
  573. ost->filters ? ost->filters : ost->filters_script);
  574. exit_program(1);
  575. }
  576. }
  577. static void parse_matrix_coeffs(void *logctx, uint16_t *dest, const char *str)
  578. {
  579. int i;
  580. const char *p = str;
  581. for (i = 0;; i++) {
  582. dest[i] = atoi(p);
  583. if (i == 63)
  584. break;
  585. p = strchr(p, ',');
  586. if (!p) {
  587. av_log(logctx, AV_LOG_FATAL,
  588. "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
  589. exit_program(1);
  590. }
  591. p++;
  592. }
  593. }
  594. static OutputStream *new_video_stream(Muxer *mux, const OptionsContext *o, InputStream *ist)
  595. {
  596. AVFormatContext *oc = mux->fc;
  597. AVStream *st;
  598. OutputStream *ost;
  599. char *frame_rate = NULL, *max_frame_rate = NULL, *frame_aspect_ratio = NULL;
  600. ost = new_output_stream(mux, o, AVMEDIA_TYPE_VIDEO, ist);
  601. st = ost->st;
  602. MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
  603. if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
  604. av_log(ost, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
  605. exit_program(1);
  606. }
  607. MATCH_PER_STREAM_OPT(max_frame_rates, str, max_frame_rate, oc, st);
  608. if (max_frame_rate && av_parse_video_rate(&ost->max_frame_rate, max_frame_rate) < 0) {
  609. av_log(ost, AV_LOG_FATAL, "Invalid maximum framerate value: %s\n", max_frame_rate);
  610. exit_program(1);
  611. }
  612. if (frame_rate && max_frame_rate) {
  613. av_log(ost, AV_LOG_ERROR, "Only one of -fpsmax and -r can be set for a stream.\n");
  614. exit_program(1);
  615. }
  616. MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
  617. if (frame_aspect_ratio) {
  618. AVRational q;
  619. if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
  620. q.num <= 0 || q.den <= 0) {
  621. av_log(ost, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
  622. exit_program(1);
  623. }
  624. ost->frame_aspect_ratio = q;
  625. }
  626. MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
  627. MATCH_PER_STREAM_OPT(filters, str, ost->filters, oc, st);
  628. if (ost->enc_ctx) {
  629. AVCodecContext *video_enc = ost->enc_ctx;
  630. const char *p = NULL, *fps_mode = NULL;
  631. char *frame_size = NULL;
  632. char *frame_pix_fmt = NULL;
  633. char *intra_matrix = NULL, *inter_matrix = NULL;
  634. char *chroma_intra_matrix = NULL;
  635. int do_pass = 0;
  636. int i;
  637. MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
  638. if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
  639. av_log(ost, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
  640. exit_program(1);
  641. }
  642. MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
  643. if (frame_pix_fmt && *frame_pix_fmt == '+') {
  644. ost->keep_pix_fmt = 1;
  645. if (!*++frame_pix_fmt)
  646. frame_pix_fmt = NULL;
  647. }
  648. if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == AV_PIX_FMT_NONE) {
  649. av_log(ost, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
  650. exit_program(1);
  651. }
  652. st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
  653. MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
  654. if (intra_matrix) {
  655. if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64)))
  656. report_and_exit(AVERROR(ENOMEM));
  657. parse_matrix_coeffs(ost, video_enc->intra_matrix, intra_matrix);
  658. }
  659. MATCH_PER_STREAM_OPT(chroma_intra_matrices, str, chroma_intra_matrix, oc, st);
  660. if (chroma_intra_matrix) {
  661. uint16_t *p = av_mallocz(sizeof(*video_enc->chroma_intra_matrix) * 64);
  662. if (!p)
  663. report_and_exit(AVERROR(ENOMEM));
  664. video_enc->chroma_intra_matrix = p;
  665. parse_matrix_coeffs(ost, p, chroma_intra_matrix);
  666. }
  667. MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
  668. if (inter_matrix) {
  669. if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64)))
  670. report_and_exit(AVERROR(ENOMEM));
  671. parse_matrix_coeffs(ost, video_enc->inter_matrix, inter_matrix);
  672. }
  673. MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
  674. for (i = 0; p; i++) {
  675. int start, end, q;
  676. int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
  677. if (e != 3) {
  678. av_log(ost, AV_LOG_FATAL, "error parsing rc_override\n");
  679. exit_program(1);
  680. }
  681. video_enc->rc_override =
  682. av_realloc_array(video_enc->rc_override,
  683. i + 1, sizeof(RcOverride));
  684. if (!video_enc->rc_override) {
  685. av_log(ost, AV_LOG_FATAL, "Could not (re)allocate memory for rc_override.\n");
  686. exit_program(1);
  687. }
  688. video_enc->rc_override[i].start_frame = start;
  689. video_enc->rc_override[i].end_frame = end;
  690. if (q > 0) {
  691. video_enc->rc_override[i].qscale = q;
  692. video_enc->rc_override[i].quality_factor = 1.0;
  693. }
  694. else {
  695. video_enc->rc_override[i].qscale = 0;
  696. video_enc->rc_override[i].quality_factor = -q/100.0;
  697. }
  698. p = strchr(p, '/');
  699. if (p) p++;
  700. }
  701. video_enc->rc_override_count = i;
  702. #if FFMPEG_OPT_PSNR
  703. if (do_psnr) {
  704. av_log(ost, AV_LOG_WARNING, "The -psnr option is deprecated, use -flags +psnr\n");
  705. video_enc->flags|= AV_CODEC_FLAG_PSNR;
  706. }
  707. #endif
  708. /* two pass mode */
  709. MATCH_PER_STREAM_OPT(pass, i, do_pass, oc, st);
  710. if (do_pass) {
  711. if (do_pass & 1) {
  712. video_enc->flags |= AV_CODEC_FLAG_PASS1;
  713. av_dict_set(&ost->encoder_opts, "flags", "+pass1", AV_DICT_APPEND);
  714. }
  715. if (do_pass & 2) {
  716. video_enc->flags |= AV_CODEC_FLAG_PASS2;
  717. av_dict_set(&ost->encoder_opts, "flags", "+pass2", AV_DICT_APPEND);
  718. }
  719. }
  720. MATCH_PER_STREAM_OPT(passlogfiles, str, ost->logfile_prefix, oc, st);
  721. if (ost->logfile_prefix &&
  722. !(ost->logfile_prefix = av_strdup(ost->logfile_prefix)))
  723. report_and_exit(AVERROR(ENOMEM));
  724. if (do_pass) {
  725. int ost_idx = -1;
  726. char logfilename[1024];
  727. FILE *f;
  728. /* compute this stream's global index */
  729. for (int i = 0; i <= ost->file_index; i++)
  730. ost_idx += output_files[i]->nb_streams;
  731. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  732. ost->logfile_prefix ? ost->logfile_prefix :
  733. DEFAULT_PASS_LOGFILENAME_PREFIX,
  734. ost_idx);
  735. if (!strcmp(ost->enc_ctx->codec->name, "libx264")) {
  736. av_dict_set(&ost->encoder_opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  737. } else {
  738. if (video_enc->flags & AV_CODEC_FLAG_PASS2) {
  739. char *logbuffer = file_read(logfilename);
  740. if (!logbuffer) {
  741. av_log(ost, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  742. logfilename);
  743. exit_program(1);
  744. }
  745. video_enc->stats_in = logbuffer;
  746. }
  747. if (video_enc->flags & AV_CODEC_FLAG_PASS1) {
  748. f = fopen_utf8(logfilename, "wb");
  749. if (!f) {
  750. av_log(ost, AV_LOG_FATAL,
  751. "Cannot write log file '%s' for pass-1 encoding: %s\n",
  752. logfilename, strerror(errno));
  753. exit_program(1);
  754. }
  755. ost->logfile = f;
  756. }
  757. }
  758. }
  759. MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
  760. ost->top_field_first = -1;
  761. MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
  762. ost->vsync_method = video_sync_method;
  763. MATCH_PER_STREAM_OPT(fps_mode, str, fps_mode, oc, st);
  764. if (fps_mode)
  765. parse_and_set_vsync(fps_mode, &ost->vsync_method, ost->file_index, ost->index, 0);
  766. if ((ost->frame_rate.num || ost->max_frame_rate.num) &&
  767. !(ost->vsync_method == VSYNC_AUTO ||
  768. ost->vsync_method == VSYNC_CFR || ost->vsync_method == VSYNC_VSCFR)) {
  769. av_log(ost, AV_LOG_FATAL, "One of -r/-fpsmax was specified "
  770. "together a non-CFR -vsync/-fps_mode. This is contradictory.\n");
  771. exit_program(1);
  772. }
  773. if (ost->vsync_method == VSYNC_AUTO) {
  774. if (ost->frame_rate.num || ost->max_frame_rate.num) {
  775. ost->vsync_method = VSYNC_CFR;
  776. } else if (!strcmp(oc->oformat->name, "avi")) {
  777. ost->vsync_method = VSYNC_VFR;
  778. } else {
  779. ost->vsync_method = (oc->oformat->flags & AVFMT_VARIABLE_FPS) ?
  780. ((oc->oformat->flags & AVFMT_NOTIMESTAMPS) ?
  781. VSYNC_PASSTHROUGH : VSYNC_VFR) :
  782. VSYNC_CFR;
  783. }
  784. if (ost->ist && ost->vsync_method == VSYNC_CFR) {
  785. const InputFile *ifile = input_files[ost->ist->file_index];
  786. if (ifile->nb_streams == 1 && ifile->input_ts_offset == 0)
  787. ost->vsync_method = VSYNC_VSCFR;
  788. }
  789. if (ost->vsync_method == VSYNC_CFR && copy_ts) {
  790. ost->vsync_method = VSYNC_VSCFR;
  791. }
  792. }
  793. ost->is_cfr = (ost->vsync_method == VSYNC_CFR || ost->vsync_method == VSYNC_VSCFR);
  794. ost->avfilter = get_ost_filters(o, oc, ost);
  795. if (!ost->avfilter)
  796. exit_program(1);
  797. ost->last_frame = av_frame_alloc();
  798. if (!ost->last_frame)
  799. report_and_exit(AVERROR(ENOMEM));
  800. } else
  801. check_streamcopy_filters(o, oc, ost, AVMEDIA_TYPE_VIDEO);
  802. return ost;
  803. }
  804. static OutputStream *new_audio_stream(Muxer *mux, const OptionsContext *o, InputStream *ist)
  805. {
  806. AVFormatContext *oc = mux->fc;
  807. AVStream *st;
  808. OutputStream *ost;
  809. ost = new_output_stream(mux, o, AVMEDIA_TYPE_AUDIO, ist);
  810. st = ost->st;
  811. MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
  812. MATCH_PER_STREAM_OPT(filters, str, ost->filters, oc, st);
  813. if (ost->enc_ctx) {
  814. AVCodecContext *audio_enc = ost->enc_ctx;
  815. int channels = 0;
  816. char *layout = NULL;
  817. char *sample_fmt = NULL;
  818. MATCH_PER_STREAM_OPT(audio_channels, i, channels, oc, st);
  819. if (channels) {
  820. audio_enc->ch_layout.order = AV_CHANNEL_ORDER_UNSPEC;
  821. audio_enc->ch_layout.nb_channels = channels;
  822. }
  823. MATCH_PER_STREAM_OPT(audio_ch_layouts, str, layout, oc, st);
  824. if (layout) {
  825. if (av_channel_layout_from_string(&audio_enc->ch_layout, layout) < 0) {
  826. #if FF_API_OLD_CHANNEL_LAYOUT
  827. uint64_t mask;
  828. AV_NOWARN_DEPRECATED({
  829. mask = av_get_channel_layout(layout);
  830. })
  831. if (!mask) {
  832. #endif
  833. av_log(ost, AV_LOG_FATAL, "Unknown channel layout: %s\n", layout);
  834. exit_program(1);
  835. #if FF_API_OLD_CHANNEL_LAYOUT
  836. }
  837. av_log(ost, AV_LOG_WARNING, "Channel layout '%s' uses a deprecated syntax.\n",
  838. layout);
  839. av_channel_layout_from_mask(&audio_enc->ch_layout, mask);
  840. #endif
  841. }
  842. }
  843. MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
  844. if (sample_fmt &&
  845. (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
  846. av_log(ost, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
  847. exit_program(1);
  848. }
  849. MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
  850. MATCH_PER_STREAM_OPT(apad, str, ost->apad, oc, st);
  851. ost->apad = av_strdup(ost->apad);
  852. ost->avfilter = get_ost_filters(o, oc, ost);
  853. if (!ost->avfilter)
  854. exit_program(1);
  855. #if FFMPEG_OPT_MAP_CHANNEL
  856. /* check for channel mapping for this audio stream */
  857. for (int n = 0; n < o->nb_audio_channel_maps; n++) {
  858. AudioChannelMap *map = &o->audio_channel_maps[n];
  859. if ((map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
  860. (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
  861. InputStream *ist;
  862. if (map->channel_idx == -1) {
  863. ist = NULL;
  864. } else if (!ost->ist) {
  865. av_log(ost, AV_LOG_FATAL, "Cannot determine input stream for channel mapping %d.%d\n",
  866. ost->file_index, ost->st->index);
  867. continue;
  868. } else {
  869. ist = ost->ist;
  870. }
  871. if (!ist || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) {
  872. if (av_reallocp_array(&ost->audio_channels_map,
  873. ost->audio_channels_mapped + 1,
  874. sizeof(*ost->audio_channels_map)
  875. ) < 0 )
  876. report_and_exit(AVERROR(ENOMEM));
  877. ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
  878. }
  879. }
  880. }
  881. #endif
  882. } else
  883. check_streamcopy_filters(o, oc, ost, AVMEDIA_TYPE_AUDIO);
  884. return ost;
  885. }
  886. static OutputStream *new_data_stream(Muxer *mux, const OptionsContext *o, InputStream *ist)
  887. {
  888. OutputStream *ost;
  889. ost = new_output_stream(mux, o, AVMEDIA_TYPE_DATA, ist);
  890. if (ost->enc_ctx) {
  891. av_log(ost, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
  892. exit_program(1);
  893. }
  894. return ost;
  895. }
  896. static OutputStream *new_unknown_stream(Muxer *mux, const OptionsContext *o, InputStream *ist)
  897. {
  898. OutputStream *ost;
  899. ost = new_output_stream(mux, o, AVMEDIA_TYPE_UNKNOWN, ist);
  900. if (ost->enc_ctx) {
  901. av_log(ost, AV_LOG_FATAL, "Unknown stream encoding not supported yet (only streamcopy)\n");
  902. exit_program(1);
  903. }
  904. return ost;
  905. }
  906. static OutputStream *new_attachment_stream(Muxer *mux, const OptionsContext *o, InputStream *ist)
  907. {
  908. OutputStream *ost = new_output_stream(mux, o, AVMEDIA_TYPE_ATTACHMENT, ist);
  909. ost->finished = 1;
  910. return ost;
  911. }
  912. static OutputStream *new_subtitle_stream(Muxer *mux, const OptionsContext *o, InputStream *ist)
  913. {
  914. AVStream *st;
  915. OutputStream *ost;
  916. ost = new_output_stream(mux, o, AVMEDIA_TYPE_SUBTITLE, ist);
  917. st = ost->st;
  918. if (ost->enc_ctx) {
  919. AVCodecContext *subtitle_enc = ost->enc_ctx;
  920. char *frame_size = NULL;
  921. MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, mux->fc, st);
  922. if (frame_size && av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size) < 0) {
  923. av_log(ost, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
  924. exit_program(1);
  925. }
  926. }
  927. return ost;
  928. }
  929. static void init_output_filter(OutputFilter *ofilter, const OptionsContext *o,
  930. Muxer *mux)
  931. {
  932. OutputStream *ost;
  933. switch (ofilter->type) {
  934. case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(mux, o, NULL); break;
  935. case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(mux, o, NULL); break;
  936. default:
  937. av_log(mux, AV_LOG_FATAL, "Only video and audio filters are supported "
  938. "currently.\n");
  939. exit_program(1);
  940. }
  941. ost->filter = ofilter;
  942. ofilter->ost = ost;
  943. ofilter->format = -1;
  944. if (!ost->enc_ctx) {
  945. av_log(ost, AV_LOG_ERROR, "Streamcopy requested for output stream fed "
  946. "from a complex filtergraph. Filtering and streamcopy "
  947. "cannot be used together.\n");
  948. exit_program(1);
  949. }
  950. if (ost->avfilter && (ost->filters || ost->filters_script)) {
  951. const char *opt = ost->filters ? "-vf/-af/-filter" : "-filter_script";
  952. av_log(ost, AV_LOG_ERROR,
  953. "%s '%s' was specified through the %s option "
  954. "for output stream %d:%d, which is fed from a complex filtergraph.\n"
  955. "%s and -filter_complex cannot be used together for the same stream.\n",
  956. ost->filters ? "Filtergraph" : "Filtergraph script",
  957. ost->filters ? ost->filters : ost->filters_script,
  958. opt, ost->file_index, ost->index, opt);
  959. exit_program(1);
  960. }
  961. avfilter_inout_free(&ofilter->out_tmp);
  962. }
  963. static void map_auto_video(Muxer *mux, const OptionsContext *o)
  964. {
  965. AVFormatContext *oc = mux->fc;
  966. InputStream *best_ist = NULL;
  967. int best_score = 0;
  968. int qcr;
  969. /* video: highest resolution */
  970. if (av_guess_codec(oc->oformat, NULL, oc->url, NULL, AVMEDIA_TYPE_VIDEO) == AV_CODEC_ID_NONE)
  971. return;
  972. qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);
  973. for (int j = 0; j < nb_input_files; j++) {
  974. InputFile *ifile = input_files[j];
  975. InputStream *file_best_ist = NULL;
  976. int file_best_score = 0;
  977. for (int i = 0; i < ifile->nb_streams; i++) {
  978. InputStream *ist = ifile->streams[i];
  979. int score;
  980. if (ist->user_set_discard == AVDISCARD_ALL ||
  981. ist->st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
  982. continue;
  983. score = ist->st->codecpar->width * ist->st->codecpar->height
  984. + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
  985. + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
  986. if((qcr!=MKTAG('A', 'P', 'I', 'C')) && (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
  987. score = 1;
  988. if (score > file_best_score) {
  989. if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
  990. continue;
  991. file_best_score = score;
  992. file_best_ist = ist;
  993. }
  994. }
  995. if (file_best_ist) {
  996. if((qcr == MKTAG('A', 'P', 'I', 'C')) ||
  997. !(file_best_ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
  998. file_best_score -= 5000000*!!(file_best_ist->st->disposition & AV_DISPOSITION_DEFAULT);
  999. if (file_best_score > best_score) {
  1000. best_score = file_best_score;
  1001. best_ist = file_best_ist;
  1002. }
  1003. }
  1004. }
  1005. if (best_ist)
  1006. new_video_stream(mux, o, best_ist);
  1007. }
  1008. static void map_auto_audio(Muxer *mux, const OptionsContext *o)
  1009. {
  1010. AVFormatContext *oc = mux->fc;
  1011. InputStream *best_ist = NULL;
  1012. int best_score = 0;
  1013. /* audio: most channels */
  1014. if (av_guess_codec(oc->oformat, NULL, oc->url, NULL, AVMEDIA_TYPE_AUDIO) == AV_CODEC_ID_NONE)
  1015. return;
  1016. for (int j = 0; j < nb_input_files; j++) {
  1017. InputFile *ifile = input_files[j];
  1018. InputStream *file_best_ist = NULL;
  1019. int file_best_score = 0;
  1020. for (int i = 0; i < ifile->nb_streams; i++) {
  1021. InputStream *ist = ifile->streams[i];
  1022. int score;
  1023. if (ist->user_set_discard == AVDISCARD_ALL ||
  1024. ist->st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
  1025. continue;
  1026. score = ist->st->codecpar->ch_layout.nb_channels
  1027. + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
  1028. + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
  1029. if (score > file_best_score) {
  1030. file_best_score = score;
  1031. file_best_ist = ist;
  1032. }
  1033. }
  1034. if (file_best_ist) {
  1035. file_best_score -= 5000000*!!(file_best_ist->st->disposition & AV_DISPOSITION_DEFAULT);
  1036. if (file_best_score > best_score) {
  1037. best_score = file_best_score;
  1038. best_ist = file_best_ist;
  1039. }
  1040. }
  1041. }
  1042. if (best_ist)
  1043. new_audio_stream(mux, o, best_ist);
  1044. }
  1045. static void map_auto_subtitle(Muxer *mux, const OptionsContext *o)
  1046. {
  1047. AVFormatContext *oc = mux->fc;
  1048. char *subtitle_codec_name = NULL;
  1049. /* subtitles: pick first */
  1050. MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, oc, "s");
  1051. if (!avcodec_find_encoder(oc->oformat->subtitle_codec) && !subtitle_codec_name)
  1052. return;
  1053. for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist))
  1054. if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1055. AVCodecDescriptor const *input_descriptor =
  1056. avcodec_descriptor_get(ist->st->codecpar->codec_id);
  1057. AVCodecDescriptor const *output_descriptor = NULL;
  1058. AVCodec const *output_codec =
  1059. avcodec_find_encoder(oc->oformat->subtitle_codec);
  1060. int input_props = 0, output_props = 0;
  1061. if (ist->user_set_discard == AVDISCARD_ALL)
  1062. continue;
  1063. if (output_codec)
  1064. output_descriptor = avcodec_descriptor_get(output_codec->id);
  1065. if (input_descriptor)
  1066. input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
  1067. if (output_descriptor)
  1068. output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
  1069. if (subtitle_codec_name ||
  1070. input_props & output_props ||
  1071. // Map dvb teletext which has neither property to any output subtitle encoder
  1072. input_descriptor && output_descriptor &&
  1073. (!input_descriptor->props ||
  1074. !output_descriptor->props)) {
  1075. new_subtitle_stream(mux, o, ist);
  1076. break;
  1077. }
  1078. }
  1079. }
  1080. static void map_auto_data(Muxer *mux, const OptionsContext *o)
  1081. {
  1082. AVFormatContext *oc = mux->fc;
  1083. /* Data only if codec id match */
  1084. enum AVCodecID codec_id = av_guess_codec(oc->oformat, NULL, oc->url, NULL, AVMEDIA_TYPE_DATA);
  1085. if (codec_id == AV_CODEC_ID_NONE)
  1086. return;
  1087. for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
  1088. if (ist->user_set_discard == AVDISCARD_ALL)
  1089. continue;
  1090. if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA &&
  1091. ist->st->codecpar->codec_id == codec_id )
  1092. new_data_stream(mux, o, ist);
  1093. }
  1094. }
  1095. static void map_manual(Muxer *mux, const OptionsContext *o, const StreamMap *map)
  1096. {
  1097. InputStream *ist;
  1098. if (map->disabled)
  1099. return;
  1100. if (map->linklabel) {
  1101. FilterGraph *fg;
  1102. OutputFilter *ofilter = NULL;
  1103. int j, k;
  1104. for (j = 0; j < nb_filtergraphs; j++) {
  1105. fg = filtergraphs[j];
  1106. for (k = 0; k < fg->nb_outputs; k++) {
  1107. AVFilterInOut *out = fg->outputs[k]->out_tmp;
  1108. if (out && !strcmp(out->name, map->linklabel)) {
  1109. ofilter = fg->outputs[k];
  1110. goto loop_end;
  1111. }
  1112. }
  1113. }
  1114. loop_end:
  1115. if (!ofilter) {
  1116. av_log(mux, AV_LOG_FATAL, "Output with label '%s' does not exist "
  1117. "in any defined filter graph, or was already used elsewhere.\n", map->linklabel);
  1118. exit_program(1);
  1119. }
  1120. init_output_filter(ofilter, o, mux);
  1121. } else {
  1122. ist = input_files[map->file_index]->streams[map->stream_index];
  1123. if (ist->user_set_discard == AVDISCARD_ALL) {
  1124. av_log(mux, AV_LOG_FATAL, "Stream #%d:%d is disabled and cannot be mapped.\n",
  1125. map->file_index, map->stream_index);
  1126. exit_program(1);
  1127. }
  1128. if(o->subtitle_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1129. return;
  1130. if(o-> audio_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  1131. return;
  1132. if(o-> video_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  1133. return;
  1134. if(o-> data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
  1135. return;
  1136. switch (ist->st->codecpar->codec_type) {
  1137. case AVMEDIA_TYPE_VIDEO: new_video_stream (mux, o, ist); break;
  1138. case AVMEDIA_TYPE_AUDIO: new_audio_stream (mux, o, ist); break;
  1139. case AVMEDIA_TYPE_SUBTITLE: new_subtitle_stream (mux, o, ist); break;
  1140. case AVMEDIA_TYPE_DATA: new_data_stream (mux, o, ist); break;
  1141. case AVMEDIA_TYPE_ATTACHMENT: new_attachment_stream(mux, o, ist); break;
  1142. case AVMEDIA_TYPE_UNKNOWN:
  1143. if (copy_unknown_streams) {
  1144. new_unknown_stream (mux, o, ist);
  1145. break;
  1146. }
  1147. default:
  1148. av_log(mux, ignore_unknown_streams ? AV_LOG_WARNING : AV_LOG_FATAL,
  1149. "Cannot map stream #%d:%d - unsupported type.\n",
  1150. map->file_index, map->stream_index);
  1151. if (!ignore_unknown_streams) {
  1152. av_log(mux, AV_LOG_FATAL,
  1153. "If you want unsupported types ignored instead "
  1154. "of failing, please use the -ignore_unknown option\n"
  1155. "If you want them copied, please use -copy_unknown\n");
  1156. exit_program(1);
  1157. }
  1158. }
  1159. }
  1160. }
  1161. static void of_add_attachments(Muxer *mux, const OptionsContext *o)
  1162. {
  1163. OutputStream *ost;
  1164. int err;
  1165. for (int i = 0; i < o->nb_attachments; i++) {
  1166. AVIOContext *pb;
  1167. uint8_t *attachment;
  1168. const char *p;
  1169. int64_t len;
  1170. if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
  1171. av_log(mux, AV_LOG_FATAL, "Could not open attachment file %s.\n",
  1172. o->attachments[i]);
  1173. exit_program(1);
  1174. }
  1175. if ((len = avio_size(pb)) <= 0) {
  1176. av_log(mux, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
  1177. o->attachments[i]);
  1178. exit_program(1);
  1179. }
  1180. if (len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE ||
  1181. !(attachment = av_malloc(len + AV_INPUT_BUFFER_PADDING_SIZE))) {
  1182. av_log(mux, AV_LOG_FATAL, "Attachment %s too large.\n",
  1183. o->attachments[i]);
  1184. exit_program(1);
  1185. }
  1186. avio_read(pb, attachment, len);
  1187. memset(attachment + len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  1188. ost = new_attachment_stream(mux, o, NULL);
  1189. ost->attachment_filename = o->attachments[i];
  1190. ost->st->codecpar->extradata = attachment;
  1191. ost->st->codecpar->extradata_size = len;
  1192. p = strrchr(o->attachments[i], '/');
  1193. av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
  1194. avio_closep(&pb);
  1195. }
  1196. }
  1197. static void create_streams(Muxer *mux, const OptionsContext *o)
  1198. {
  1199. AVFormatContext *oc = mux->fc;
  1200. int auto_disable_v = o->video_disable;
  1201. int auto_disable_a = o->audio_disable;
  1202. int auto_disable_s = o->subtitle_disable;
  1203. int auto_disable_d = o->data_disable;
  1204. /* create streams for all unlabeled output pads */
  1205. for (int i = 0; i < nb_filtergraphs; i++) {
  1206. FilterGraph *fg = filtergraphs[i];
  1207. for (int j = 0; j < fg->nb_outputs; j++) {
  1208. OutputFilter *ofilter = fg->outputs[j];
  1209. if (!ofilter->out_tmp || ofilter->out_tmp->name)
  1210. continue;
  1211. switch (ofilter->type) {
  1212. case AVMEDIA_TYPE_VIDEO: auto_disable_v = 1; break;
  1213. case AVMEDIA_TYPE_AUDIO: auto_disable_a = 1; break;
  1214. case AVMEDIA_TYPE_SUBTITLE: auto_disable_s = 1; break;
  1215. }
  1216. init_output_filter(ofilter, o, mux);
  1217. }
  1218. }
  1219. if (!o->nb_stream_maps) {
  1220. /* pick the "best" stream of each type */
  1221. if (!auto_disable_v)
  1222. map_auto_video(mux, o);
  1223. if (!auto_disable_a)
  1224. map_auto_audio(mux, o);
  1225. if (!auto_disable_s)
  1226. map_auto_subtitle(mux, o);
  1227. if (!auto_disable_d)
  1228. map_auto_data(mux, o);
  1229. } else {
  1230. for (int i = 0; i < o->nb_stream_maps; i++)
  1231. map_manual(mux, o, &o->stream_maps[i]);
  1232. }
  1233. of_add_attachments(mux, o);
  1234. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1235. av_dump_format(oc, nb_output_files - 1, oc->url, 1);
  1236. av_log(mux, AV_LOG_ERROR, "Output file does not contain any stream\n");
  1237. exit_program(1);
  1238. }
  1239. }
  1240. static int setup_sync_queues(Muxer *mux, AVFormatContext *oc, int64_t buf_size_us)
  1241. {
  1242. OutputFile *of = &mux->of;
  1243. int nb_av_enc = 0, nb_interleaved = 0;
  1244. int limit_frames = 0, limit_frames_av_enc = 0;
  1245. #define IS_AV_ENC(ost, type) \
  1246. (ost->enc_ctx && (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO))
  1247. #define IS_INTERLEAVED(type) (type != AVMEDIA_TYPE_ATTACHMENT)
  1248. for (int i = 0; i < oc->nb_streams; i++) {
  1249. OutputStream *ost = of->streams[i];
  1250. MuxStream *ms = ms_from_ost(ost);
  1251. enum AVMediaType type = ost->st->codecpar->codec_type;
  1252. ost->sq_idx_encode = -1;
  1253. ost->sq_idx_mux = -1;
  1254. nb_interleaved += IS_INTERLEAVED(type);
  1255. nb_av_enc += IS_AV_ENC(ost, type);
  1256. limit_frames |= ms->max_frames < INT64_MAX;
  1257. limit_frames_av_enc |= (ms->max_frames < INT64_MAX) && IS_AV_ENC(ost, type);
  1258. }
  1259. if (!((nb_interleaved > 1 && of->shortest) ||
  1260. (nb_interleaved > 0 && limit_frames)))
  1261. return 0;
  1262. /* if we have more than one encoded audio/video streams, or at least
  1263. * one encoded audio/video stream is frame-limited, then we
  1264. * synchronize them before encoding */
  1265. if ((of->shortest && nb_av_enc > 1) || limit_frames_av_enc) {
  1266. of->sq_encode = sq_alloc(SYNC_QUEUE_FRAMES, buf_size_us);
  1267. if (!of->sq_encode)
  1268. return AVERROR(ENOMEM);
  1269. for (int i = 0; i < oc->nb_streams; i++) {
  1270. OutputStream *ost = of->streams[i];
  1271. MuxStream *ms = ms_from_ost(ost);
  1272. enum AVMediaType type = ost->st->codecpar->codec_type;
  1273. if (!IS_AV_ENC(ost, type))
  1274. continue;
  1275. ost->sq_idx_encode = sq_add_stream(of->sq_encode,
  1276. of->shortest || ms->max_frames < INT64_MAX);
  1277. if (ost->sq_idx_encode < 0)
  1278. return ost->sq_idx_encode;
  1279. ost->sq_frame = av_frame_alloc();
  1280. if (!ost->sq_frame)
  1281. return AVERROR(ENOMEM);
  1282. if (ms->max_frames != INT64_MAX)
  1283. sq_limit_frames(of->sq_encode, ost->sq_idx_encode, ms->max_frames);
  1284. }
  1285. }
  1286. /* if there are any additional interleaved streams, then ALL the streams
  1287. * are also synchronized before sending them to the muxer */
  1288. if (nb_interleaved > nb_av_enc) {
  1289. mux->sq_mux = sq_alloc(SYNC_QUEUE_PACKETS, buf_size_us);
  1290. if (!mux->sq_mux)
  1291. return AVERROR(ENOMEM);
  1292. mux->sq_pkt = av_packet_alloc();
  1293. if (!mux->sq_pkt)
  1294. return AVERROR(ENOMEM);
  1295. for (int i = 0; i < oc->nb_streams; i++) {
  1296. OutputStream *ost = of->streams[i];
  1297. MuxStream *ms = ms_from_ost(ost);
  1298. enum AVMediaType type = ost->st->codecpar->codec_type;
  1299. if (!IS_INTERLEAVED(type))
  1300. continue;
  1301. ost->sq_idx_mux = sq_add_stream(mux->sq_mux,
  1302. of->shortest || ms->max_frames < INT64_MAX);
  1303. if (ost->sq_idx_mux < 0)
  1304. return ost->sq_idx_mux;
  1305. if (ms->max_frames != INT64_MAX)
  1306. sq_limit_frames(mux->sq_mux, ost->sq_idx_mux, ms->max_frames);
  1307. }
  1308. }
  1309. #undef IS_AV_ENC
  1310. #undef IS_INTERLEAVED
  1311. return 0;
  1312. }
  1313. static void of_add_programs(Muxer *mux, const OptionsContext *o)
  1314. {
  1315. AVFormatContext *oc = mux->fc;
  1316. /* process manually set programs */
  1317. for (int i = 0; i < o->nb_program; i++) {
  1318. const char *p = o->program[i].u.str;
  1319. int progid = i+1;
  1320. AVProgram *program;
  1321. while(*p) {
  1322. const char *p2 = av_get_token(&p, ":");
  1323. const char *to_dealloc = p2;
  1324. char *key;
  1325. if (!p2)
  1326. break;
  1327. if(*p) p++;
  1328. key = av_get_token(&p2, "=");
  1329. if (!key || !*p2) {
  1330. av_freep(&to_dealloc);
  1331. av_freep(&key);
  1332. break;
  1333. }
  1334. p2++;
  1335. if (!strcmp(key, "program_num"))
  1336. progid = strtol(p2, NULL, 0);
  1337. av_freep(&to_dealloc);
  1338. av_freep(&key);
  1339. }
  1340. program = av_new_program(oc, progid);
  1341. if (!program)
  1342. report_and_exit(AVERROR(ENOMEM));
  1343. p = o->program[i].u.str;
  1344. while(*p) {
  1345. const char *p2 = av_get_token(&p, ":");
  1346. const char *to_dealloc = p2;
  1347. char *key;
  1348. if (!p2)
  1349. break;
  1350. if(*p) p++;
  1351. key = av_get_token(&p2, "=");
  1352. if (!key) {
  1353. av_log(mux, AV_LOG_FATAL,
  1354. "No '=' character in program string %s.\n",
  1355. p2);
  1356. exit_program(1);
  1357. }
  1358. if (!*p2)
  1359. exit_program(1);
  1360. p2++;
  1361. if (!strcmp(key, "title")) {
  1362. av_dict_set(&program->metadata, "title", p2, 0);
  1363. } else if (!strcmp(key, "program_num")) {
  1364. } else if (!strcmp(key, "st")) {
  1365. int st_num = strtol(p2, NULL, 0);
  1366. av_program_add_stream_index(oc, progid, st_num);
  1367. } else {
  1368. av_log(mux, AV_LOG_FATAL, "Unknown program key %s.\n", key);
  1369. exit_program(1);
  1370. }
  1371. av_freep(&to_dealloc);
  1372. av_freep(&key);
  1373. }
  1374. }
  1375. }
  1376. /**
  1377. * Parse a metadata specifier passed as 'arg' parameter.
  1378. * @param arg metadata string to parse
  1379. * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
  1380. * @param index for type c/p, chapter/program index is written here
  1381. * @param stream_spec for type s, the stream specifier is written here
  1382. */
  1383. static void parse_meta_type(void *logctx, const char *arg,
  1384. char *type, int *index, const char **stream_spec)
  1385. {
  1386. if (*arg) {
  1387. *type = *arg;
  1388. switch (*arg) {
  1389. case 'g':
  1390. break;
  1391. case 's':
  1392. if (*(++arg) && *arg != ':') {
  1393. av_log(logctx, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
  1394. exit_program(1);
  1395. }
  1396. *stream_spec = *arg == ':' ? arg + 1 : "";
  1397. break;
  1398. case 'c':
  1399. case 'p':
  1400. if (*(++arg) == ':')
  1401. *index = strtol(++arg, NULL, 0);
  1402. break;
  1403. default:
  1404. av_log(logctx, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
  1405. exit_program(1);
  1406. }
  1407. } else
  1408. *type = 'g';
  1409. }
  1410. static void of_add_metadata(OutputFile *of, AVFormatContext *oc,
  1411. const OptionsContext *o)
  1412. {
  1413. for (int i = 0; i < o->nb_metadata; i++) {
  1414. AVDictionary **m;
  1415. char type, *val;
  1416. const char *stream_spec;
  1417. int index = 0, ret = 0;
  1418. val = strchr(o->metadata[i].u.str, '=');
  1419. if (!val) {
  1420. av_log(of, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
  1421. o->metadata[i].u.str);
  1422. exit_program(1);
  1423. }
  1424. *val++ = 0;
  1425. parse_meta_type(of, o->metadata[i].specifier, &type, &index, &stream_spec);
  1426. if (type == 's') {
  1427. for (int j = 0; j < oc->nb_streams; j++) {
  1428. OutputStream *ost = of->streams[j];
  1429. if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
  1430. #if FFMPEG_ROTATION_METADATA
  1431. if (!strcmp(o->metadata[i].u.str, "rotate")) {
  1432. char *tail;
  1433. double theta = av_strtod(val, &tail);
  1434. if (!*tail) {
  1435. ost->rotate_overridden = 1;
  1436. ost->rotate_override_value = theta;
  1437. }
  1438. av_log(ost, AV_LOG_WARNING,
  1439. "Conversion of a 'rotate' metadata key to a "
  1440. "proper display matrix rotation is deprecated. "
  1441. "See -display_rotation for setting rotation "
  1442. "instead.");
  1443. } else {
  1444. #endif
  1445. av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
  1446. #if FFMPEG_ROTATION_METADATA
  1447. }
  1448. #endif
  1449. } else if (ret < 0)
  1450. exit_program(1);
  1451. }
  1452. } else {
  1453. switch (type) {
  1454. case 'g':
  1455. m = &oc->metadata;
  1456. break;
  1457. case 'c':
  1458. if (index < 0 || index >= oc->nb_chapters) {
  1459. av_log(of, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
  1460. exit_program(1);
  1461. }
  1462. m = &oc->chapters[index]->metadata;
  1463. break;
  1464. case 'p':
  1465. if (index < 0 || index >= oc->nb_programs) {
  1466. av_log(of, AV_LOG_FATAL, "Invalid program index %d in metadata specifier.\n", index);
  1467. exit_program(1);
  1468. }
  1469. m = &oc->programs[index]->metadata;
  1470. break;
  1471. default:
  1472. av_log(of, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
  1473. exit_program(1);
  1474. }
  1475. av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
  1476. }
  1477. }
  1478. }
  1479. static void set_channel_layout(OutputFilter *f, OutputStream *ost)
  1480. {
  1481. const AVCodec *c = ost->enc_ctx->codec;
  1482. int i, err;
  1483. if (ost->enc_ctx->ch_layout.order != AV_CHANNEL_ORDER_UNSPEC) {
  1484. /* Pass the layout through for all orders but UNSPEC */
  1485. err = av_channel_layout_copy(&f->ch_layout, &ost->enc_ctx->ch_layout);
  1486. if (err < 0)
  1487. report_and_exit(AVERROR(ENOMEM));
  1488. return;
  1489. }
  1490. /* Requested layout is of order UNSPEC */
  1491. if (!c->ch_layouts) {
  1492. /* Use the default native layout for the requested amount of channels when the
  1493. encoder doesn't have a list of supported layouts */
  1494. av_channel_layout_default(&f->ch_layout, ost->enc_ctx->ch_layout.nb_channels);
  1495. return;
  1496. }
  1497. /* Encoder has a list of supported layouts. Pick the first layout in it with the
  1498. same amount of channels as the requested layout */
  1499. for (i = 0; c->ch_layouts[i].nb_channels; i++) {
  1500. if (c->ch_layouts[i].nb_channels == ost->enc_ctx->ch_layout.nb_channels)
  1501. break;
  1502. }
  1503. if (c->ch_layouts[i].nb_channels) {
  1504. /* Use it if one is found */
  1505. err = av_channel_layout_copy(&f->ch_layout, &c->ch_layouts[i]);
  1506. if (err < 0)
  1507. report_and_exit(AVERROR(ENOMEM));
  1508. return;
  1509. }
  1510. /* If no layout for the amount of channels requested was found, use the default
  1511. native layout for it. */
  1512. av_channel_layout_default(&f->ch_layout, ost->enc_ctx->ch_layout.nb_channels);
  1513. }
  1514. static int copy_chapters(InputFile *ifile, OutputFile *ofile, AVFormatContext *os,
  1515. int copy_metadata)
  1516. {
  1517. AVFormatContext *is = ifile->ctx;
  1518. AVChapter **tmp;
  1519. int i;
  1520. tmp = av_realloc_f(os->chapters, is->nb_chapters + os->nb_chapters, sizeof(*os->chapters));
  1521. if (!tmp)
  1522. return AVERROR(ENOMEM);
  1523. os->chapters = tmp;
  1524. for (i = 0; i < is->nb_chapters; i++) {
  1525. AVChapter *in_ch = is->chapters[i], *out_ch;
  1526. int64_t start_time = (ofile->start_time == AV_NOPTS_VALUE) ? 0 : ofile->start_time;
  1527. int64_t ts_off = av_rescale_q(start_time - ifile->ts_offset,
  1528. AV_TIME_BASE_Q, in_ch->time_base);
  1529. int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
  1530. av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
  1531. if (in_ch->end < ts_off)
  1532. continue;
  1533. if (rt != INT64_MAX && in_ch->start > rt + ts_off)
  1534. break;
  1535. out_ch = av_mallocz(sizeof(AVChapter));
  1536. if (!out_ch)
  1537. return AVERROR(ENOMEM);
  1538. out_ch->id = in_ch->id;
  1539. out_ch->time_base = in_ch->time_base;
  1540. out_ch->start = FFMAX(0, in_ch->start - ts_off);
  1541. out_ch->end = FFMIN(rt, in_ch->end - ts_off);
  1542. if (copy_metadata)
  1543. av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
  1544. os->chapters[os->nb_chapters++] = out_ch;
  1545. }
  1546. return 0;
  1547. }
  1548. static int copy_metadata(Muxer *mux, AVFormatContext *ic,
  1549. const char *outspec, const char *inspec,
  1550. int *metadata_global_manual, int *metadata_streams_manual,
  1551. int *metadata_chapters_manual, const OptionsContext *o)
  1552. {
  1553. AVFormatContext *oc = mux->fc;
  1554. AVDictionary **meta_in = NULL;
  1555. AVDictionary **meta_out = NULL;
  1556. int i, ret = 0;
  1557. char type_in, type_out;
  1558. const char *istream_spec = NULL, *ostream_spec = NULL;
  1559. int idx_in = 0, idx_out = 0;
  1560. parse_meta_type(mux, inspec, &type_in, &idx_in, &istream_spec);
  1561. parse_meta_type(mux, outspec, &type_out, &idx_out, &ostream_spec);
  1562. if (type_in == 'g' || type_out == 'g' || (!*outspec && !ic))
  1563. *metadata_global_manual = 1;
  1564. if (type_in == 's' || type_out == 's' || (!*outspec && !ic))
  1565. *metadata_streams_manual = 1;
  1566. if (type_in == 'c' || type_out == 'c' || (!*outspec && !ic))
  1567. *metadata_chapters_manual = 1;
  1568. /* ic is NULL when just disabling automatic mappings */
  1569. if (!ic)
  1570. return 0;
  1571. #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
  1572. if ((index) < 0 || (index) >= (nb_elems)) {\
  1573. av_log(mux, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
  1574. (desc), (index));\
  1575. exit_program(1);\
  1576. }
  1577. #define SET_DICT(type, meta, context, index)\
  1578. switch (type) {\
  1579. case 'g':\
  1580. meta = &context->metadata;\
  1581. break;\
  1582. case 'c':\
  1583. METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
  1584. meta = &context->chapters[index]->metadata;\
  1585. break;\
  1586. case 'p':\
  1587. METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
  1588. meta = &context->programs[index]->metadata;\
  1589. break;\
  1590. case 's':\
  1591. break; /* handled separately below */ \
  1592. default: av_assert0(0);\
  1593. }\
  1594. SET_DICT(type_in, meta_in, ic, idx_in);
  1595. SET_DICT(type_out, meta_out, oc, idx_out);
  1596. /* for input streams choose first matching stream */
  1597. if (type_in == 's') {
  1598. for (i = 0; i < ic->nb_streams; i++) {
  1599. if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
  1600. meta_in = &ic->streams[i]->metadata;
  1601. break;
  1602. } else if (ret < 0)
  1603. exit_program(1);
  1604. }
  1605. if (!meta_in) {
  1606. av_log(mux, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
  1607. exit_program(1);
  1608. }
  1609. }
  1610. if (type_out == 's') {
  1611. for (i = 0; i < oc->nb_streams; i++) {
  1612. if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
  1613. meta_out = &oc->streams[i]->metadata;
  1614. av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
  1615. } else if (ret < 0)
  1616. exit_program(1);
  1617. }
  1618. } else
  1619. av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
  1620. return 0;
  1621. }
  1622. static void copy_meta(Muxer *mux, const OptionsContext *o)
  1623. {
  1624. OutputFile *of = &mux->of;
  1625. AVFormatContext *oc = mux->fc;
  1626. int chapters_input_file = o->chapters_input_file;
  1627. int metadata_global_manual = 0;
  1628. int metadata_streams_manual = 0;
  1629. int metadata_chapters_manual = 0;
  1630. /* copy metadata */
  1631. for (int i = 0; i < o->nb_metadata_map; i++) {
  1632. char *p;
  1633. int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
  1634. if (in_file_index >= nb_input_files) {
  1635. av_log(mux, AV_LOG_FATAL, "Invalid input file index %d while "
  1636. "processing metadata maps\n", in_file_index);
  1637. exit_program(1);
  1638. }
  1639. copy_metadata(mux,
  1640. in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL,
  1641. o->metadata_map[i].specifier, *p ? p + 1 : p,
  1642. &metadata_global_manual, &metadata_streams_manual,
  1643. &metadata_chapters_manual, o);
  1644. }
  1645. /* copy chapters */
  1646. if (chapters_input_file >= nb_input_files) {
  1647. if (chapters_input_file == INT_MAX) {
  1648. /* copy chapters from the first input file that has them*/
  1649. chapters_input_file = -1;
  1650. for (int i = 0; i < nb_input_files; i++)
  1651. if (input_files[i]->ctx->nb_chapters) {
  1652. chapters_input_file = i;
  1653. break;
  1654. }
  1655. } else {
  1656. av_log(mux, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
  1657. chapters_input_file);
  1658. exit_program(1);
  1659. }
  1660. }
  1661. if (chapters_input_file >= 0)
  1662. copy_chapters(input_files[chapters_input_file], of, oc,
  1663. !metadata_chapters_manual);
  1664. /* copy global metadata by default */
  1665. if (!metadata_global_manual && nb_input_files){
  1666. av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
  1667. AV_DICT_DONT_OVERWRITE);
  1668. if (of->recording_time != INT64_MAX)
  1669. av_dict_set(&oc->metadata, "duration", NULL, 0);
  1670. av_dict_set(&oc->metadata, "creation_time", NULL, 0);
  1671. av_dict_set(&oc->metadata, "company_name", NULL, 0);
  1672. av_dict_set(&oc->metadata, "product_name", NULL, 0);
  1673. av_dict_set(&oc->metadata, "product_version", NULL, 0);
  1674. }
  1675. if (!metadata_streams_manual)
  1676. for (int i = 0; i < of->nb_streams; i++) {
  1677. OutputStream *ost = of->streams[i];
  1678. if (!ost->ist) /* this is true e.g. for attached files */
  1679. continue;
  1680. av_dict_copy(&ost->st->metadata, ost->ist->st->metadata, AV_DICT_DONT_OVERWRITE);
  1681. if (ost->enc_ctx) {
  1682. av_dict_set(&ost->st->metadata, "encoder", NULL, 0);
  1683. }
  1684. }
  1685. }
  1686. static int set_dispositions(Muxer *mux, const OptionsContext *o)
  1687. {
  1688. OutputFile *of = &mux->of;
  1689. AVFormatContext *ctx = mux->fc;
  1690. int nb_streams[AVMEDIA_TYPE_NB] = { 0 };
  1691. int have_default[AVMEDIA_TYPE_NB] = { 0 };
  1692. int have_manual = 0;
  1693. int ret = 0;
  1694. const char **dispositions;
  1695. dispositions = av_calloc(ctx->nb_streams, sizeof(*dispositions));
  1696. if (!dispositions)
  1697. return AVERROR(ENOMEM);
  1698. // first, copy the input dispositions
  1699. for (int i = 0; i < ctx->nb_streams; i++) {
  1700. OutputStream *ost = of->streams[i];
  1701. nb_streams[ost->st->codecpar->codec_type]++;
  1702. MATCH_PER_STREAM_OPT(disposition, str, dispositions[i], ctx, ost->st);
  1703. have_manual |= !!dispositions[i];
  1704. if (ost->ist) {
  1705. ost->st->disposition = ost->ist->st->disposition;
  1706. if (ost->st->disposition & AV_DISPOSITION_DEFAULT)
  1707. have_default[ost->st->codecpar->codec_type] = 1;
  1708. }
  1709. }
  1710. if (have_manual) {
  1711. // process manually set dispositions - they override the above copy
  1712. for (int i = 0; i < ctx->nb_streams; i++) {
  1713. OutputStream *ost = of->streams[i];
  1714. const char *disp = dispositions[i];
  1715. if (!disp)
  1716. continue;
  1717. ret = av_opt_set(ost->st, "disposition", disp, 0);
  1718. if (ret < 0)
  1719. goto finish;
  1720. }
  1721. } else {
  1722. // For each media type with more than one stream, find a suitable stream to
  1723. // mark as default, unless one is already marked default.
  1724. // "Suitable" means the first of that type, skipping attached pictures.
  1725. for (int i = 0; i < ctx->nb_streams; i++) {
  1726. OutputStream *ost = of->streams[i];
  1727. enum AVMediaType type = ost->st->codecpar->codec_type;
  1728. if (nb_streams[type] < 2 || have_default[type] ||
  1729. ost->st->disposition & AV_DISPOSITION_ATTACHED_PIC)
  1730. continue;
  1731. ost->st->disposition |= AV_DISPOSITION_DEFAULT;
  1732. have_default[type] = 1;
  1733. }
  1734. }
  1735. finish:
  1736. av_freep(&dispositions);
  1737. return ret;
  1738. }
  1739. const char *const forced_keyframes_const_names[] = {
  1740. "n",
  1741. "n_forced",
  1742. "prev_forced_n",
  1743. "prev_forced_t",
  1744. "t",
  1745. NULL
  1746. };
  1747. static int compare_int64(const void *a, const void *b)
  1748. {
  1749. return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
  1750. }
  1751. static void parse_forced_key_frames(KeyframeForceCtx *kf, const Muxer *mux,
  1752. const char *spec)
  1753. {
  1754. const char *p;
  1755. int n = 1, i, size, index = 0;
  1756. int64_t t, *pts;
  1757. for (p = spec; *p; p++)
  1758. if (*p == ',')
  1759. n++;
  1760. size = n;
  1761. pts = av_malloc_array(size, sizeof(*pts));
  1762. if (!pts)
  1763. report_and_exit(AVERROR(ENOMEM));
  1764. p = spec;
  1765. for (i = 0; i < n; i++) {
  1766. char *next = strchr(p, ',');
  1767. if (next)
  1768. *next++ = 0;
  1769. if (strstr(p, "chapters") == p) {
  1770. AVChapter * const *ch = mux->fc->chapters;
  1771. unsigned int nb_ch = mux->fc->nb_chapters;
  1772. int j;
  1773. if (nb_ch > INT_MAX - size ||
  1774. !(pts = av_realloc_f(pts, size += nb_ch - 1,
  1775. sizeof(*pts))))
  1776. report_and_exit(AVERROR(ENOMEM));
  1777. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
  1778. for (j = 0; j < nb_ch; j++) {
  1779. const AVChapter *c = ch[j];
  1780. av_assert1(index < size);
  1781. pts[index++] = av_rescale_q(c->start, c->time_base,
  1782. AV_TIME_BASE_Q) + t;
  1783. }
  1784. } else {
  1785. av_assert1(index < size);
  1786. pts[index++] = parse_time_or_die("force_key_frames", p, 1);
  1787. }
  1788. p = next;
  1789. }
  1790. av_assert0(index == size);
  1791. qsort(pts, size, sizeof(*pts), compare_int64);
  1792. kf->nb_pts = size;
  1793. kf->pts = pts;
  1794. }
  1795. static int process_forced_keyframes(Muxer *mux, const OptionsContext *o)
  1796. {
  1797. for (int i = 0; i < mux->of.nb_streams; i++) {
  1798. OutputStream *ost = mux->of.streams[i];
  1799. const char *forced_keyframes = NULL;
  1800. MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_keyframes, mux->fc, ost->st);
  1801. if (!(ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  1802. ost->enc_ctx && forced_keyframes))
  1803. continue;
  1804. if (!strncmp(forced_keyframes, "expr:", 5)) {
  1805. int ret = av_expr_parse(&ost->kf.pexpr, forced_keyframes + 5,
  1806. forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
  1807. if (ret < 0) {
  1808. av_log(ost, AV_LOG_ERROR,
  1809. "Invalid force_key_frames expression '%s'\n", forced_keyframes + 5);
  1810. return ret;
  1811. }
  1812. ost->kf.expr_const_values[FKF_N] = 0;
  1813. ost->kf.expr_const_values[FKF_N_FORCED] = 0;
  1814. ost->kf.expr_const_values[FKF_PREV_FORCED_N] = NAN;
  1815. ost->kf.expr_const_values[FKF_PREV_FORCED_T] = NAN;
  1816. // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
  1817. // parse it only for static kf timings
  1818. } else if (!strcmp(forced_keyframes, "source")) {
  1819. ost->kf.type = KF_FORCE_SOURCE;
  1820. } else if (!strcmp(forced_keyframes, "source_no_drop")) {
  1821. ost->kf.type = KF_FORCE_SOURCE_NO_DROP;
  1822. } else {
  1823. parse_forced_key_frames(&ost->kf, mux, forced_keyframes);
  1824. }
  1825. }
  1826. return 0;
  1827. }
  1828. static void validate_enc_avopt(Muxer *mux, const AVDictionary *codec_avopt)
  1829. {
  1830. const AVClass *class = avcodec_get_class();
  1831. const AVClass *fclass = avformat_get_class();
  1832. const OutputFile *of = &mux->of;
  1833. AVDictionary *unused_opts;
  1834. const AVDictionaryEntry *e;
  1835. unused_opts = strip_specifiers(codec_avopt);
  1836. for (int i = 0; i < of->nb_streams; i++) {
  1837. e = NULL;
  1838. while ((e = av_dict_iterate(of->streams[i]->encoder_opts, e)))
  1839. av_dict_set(&unused_opts, e->key, NULL, 0);
  1840. }
  1841. e = NULL;
  1842. while ((e = av_dict_iterate(unused_opts, e))) {
  1843. const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
  1844. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
  1845. const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
  1846. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
  1847. if (!option || foption)
  1848. continue;
  1849. if (!(option->flags & AV_OPT_FLAG_ENCODING_PARAM)) {
  1850. av_log(mux, AV_LOG_ERROR, "Codec AVOption %s (%s) is not an "
  1851. "encoding option.\n", e->key, option->help ? option->help : "");
  1852. exit_program(1);
  1853. }
  1854. // gop_timecode is injected by generic code but not always used
  1855. if (!strcmp(e->key, "gop_timecode"))
  1856. continue;
  1857. av_log(mux, AV_LOG_WARNING, "Codec AVOption %s (%s) has not been used "
  1858. "for any stream. The most likely reason is either wrong type "
  1859. "(e.g. a video option with no video streams) or that it is a "
  1860. "private option of some encoder which was not actually used for "
  1861. "any stream.\n", e->key, option->help ? option->help : "");
  1862. }
  1863. av_dict_free(&unused_opts);
  1864. }
  1865. static const char *output_file_item_name(void *obj)
  1866. {
  1867. const Muxer *mux = obj;
  1868. return mux->log_name;
  1869. }
  1870. static const AVClass output_file_class = {
  1871. .class_name = "OutputFile",
  1872. .version = LIBAVUTIL_VERSION_INT,
  1873. .item_name = output_file_item_name,
  1874. .category = AV_CLASS_CATEGORY_MUXER,
  1875. };
  1876. static Muxer *mux_alloc(void)
  1877. {
  1878. Muxer *mux = allocate_array_elem(&output_files, sizeof(*mux), &nb_output_files);
  1879. mux->of.class = &output_file_class;
  1880. mux->of.index = nb_output_files - 1;
  1881. snprintf(mux->log_name, sizeof(mux->log_name), "out#%d", mux->of.index);
  1882. return mux;
  1883. }
  1884. int of_open(const OptionsContext *o, const char *filename)
  1885. {
  1886. Muxer *mux;
  1887. AVFormatContext *oc;
  1888. int err;
  1889. OutputFile *of;
  1890. int64_t recording_time = o->recording_time;
  1891. int64_t stop_time = o->stop_time;
  1892. mux = mux_alloc();
  1893. of = &mux->of;
  1894. if (stop_time != INT64_MAX && recording_time != INT64_MAX) {
  1895. stop_time = INT64_MAX;
  1896. av_log(mux, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
  1897. }
  1898. if (stop_time != INT64_MAX && recording_time == INT64_MAX) {
  1899. int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
  1900. if (stop_time <= start_time) {
  1901. av_log(mux, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
  1902. exit_program(1);
  1903. } else {
  1904. recording_time = stop_time - start_time;
  1905. }
  1906. }
  1907. of->recording_time = recording_time;
  1908. of->start_time = o->start_time;
  1909. of->shortest = o->shortest;
  1910. mux->thread_queue_size = o->thread_queue_size > 0 ? o->thread_queue_size : 8;
  1911. mux->limit_filesize = o->limit_filesize;
  1912. av_dict_copy(&mux->opts, o->g->format_opts, 0);
  1913. if (!strcmp(filename, "-"))
  1914. filename = "pipe:";
  1915. err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
  1916. if (!oc) {
  1917. print_error(filename, err);
  1918. exit_program(1);
  1919. }
  1920. mux->fc = oc;
  1921. av_strlcat(mux->log_name, "/", sizeof(mux->log_name));
  1922. av_strlcat(mux->log_name, oc->oformat->name, sizeof(mux->log_name));
  1923. if (strcmp(oc->oformat->name, "rtp"))
  1924. want_sdp = 0;
  1925. of->format = oc->oformat;
  1926. if (recording_time != INT64_MAX)
  1927. oc->duration = recording_time;
  1928. oc->interrupt_callback = int_cb;
  1929. if (o->bitexact) {
  1930. oc->flags |= AVFMT_FLAG_BITEXACT;
  1931. of->bitexact = 1;
  1932. } else {
  1933. of->bitexact = check_opt_bitexact(oc, mux->opts, "fflags",
  1934. AVFMT_FLAG_BITEXACT);
  1935. }
  1936. /* create all output streams for this file */
  1937. create_streams(mux, o);
  1938. /* check if all codec options have been used */
  1939. validate_enc_avopt(mux, o->g->codec_opts);
  1940. /* set the decoding_needed flags and create simple filtergraphs */
  1941. for (int i = 0; i < of->nb_streams; i++) {
  1942. OutputStream *ost = of->streams[i];
  1943. if (ost->enc_ctx && ost->ist) {
  1944. InputStream *ist = ost->ist;
  1945. ist->decoding_needed |= DECODING_FOR_OST;
  1946. ist->processing_needed = 1;
  1947. if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
  1948. ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  1949. err = init_simple_filtergraph(ist, ost);
  1950. if (err < 0) {
  1951. av_log(ost, AV_LOG_ERROR,
  1952. "Error initializing a simple filtergraph\n");
  1953. exit_program(1);
  1954. }
  1955. }
  1956. } else if (ost->ist) {
  1957. ost->ist->processing_needed = 1;
  1958. }
  1959. /* set the filter output constraints */
  1960. if (ost->filter) {
  1961. const AVCodec *c = ost->enc_ctx->codec;
  1962. OutputFilter *f = ost->filter;
  1963. switch (ost->enc_ctx->codec_type) {
  1964. case AVMEDIA_TYPE_VIDEO:
  1965. f->frame_rate = ost->frame_rate;
  1966. f->width = ost->enc_ctx->width;
  1967. f->height = ost->enc_ctx->height;
  1968. if (ost->enc_ctx->pix_fmt != AV_PIX_FMT_NONE) {
  1969. f->format = ost->enc_ctx->pix_fmt;
  1970. } else {
  1971. f->formats = c->pix_fmts;
  1972. }
  1973. break;
  1974. case AVMEDIA_TYPE_AUDIO:
  1975. if (ost->enc_ctx->sample_fmt != AV_SAMPLE_FMT_NONE) {
  1976. f->format = ost->enc_ctx->sample_fmt;
  1977. } else {
  1978. f->formats = c->sample_fmts;
  1979. }
  1980. if (ost->enc_ctx->sample_rate) {
  1981. f->sample_rate = ost->enc_ctx->sample_rate;
  1982. } else {
  1983. f->sample_rates = c->supported_samplerates;
  1984. }
  1985. if (ost->enc_ctx->ch_layout.nb_channels) {
  1986. set_channel_layout(f, ost);
  1987. } else if (c->ch_layouts) {
  1988. f->ch_layouts = c->ch_layouts;
  1989. }
  1990. break;
  1991. }
  1992. }
  1993. }
  1994. /* check filename in case of an image number is expected */
  1995. if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
  1996. if (!av_filename_number_test(oc->url)) {
  1997. print_error(oc->url, AVERROR(EINVAL));
  1998. exit_program(1);
  1999. }
  2000. }
  2001. if (!(oc->oformat->flags & AVFMT_NOFILE)) {
  2002. /* test if it already exists to avoid losing precious files */
  2003. assert_file_overwrite(filename);
  2004. /* open the file */
  2005. if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
  2006. &oc->interrupt_callback,
  2007. &mux->opts)) < 0) {
  2008. print_error(filename, err);
  2009. exit_program(1);
  2010. }
  2011. } else if (strcmp(oc->oformat->name, "image2")==0 && !av_filename_number_test(filename))
  2012. assert_file_overwrite(filename);
  2013. if (o->mux_preload) {
  2014. av_dict_set_int(&mux->opts, "preload", o->mux_preload*AV_TIME_BASE, 0);
  2015. }
  2016. oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
  2017. /* copy metadata and chapters from input files */
  2018. copy_meta(mux, o);
  2019. of_add_programs(mux, o);
  2020. of_add_metadata(of, oc, o);
  2021. err = set_dispositions(mux, o);
  2022. if (err < 0) {
  2023. av_log(mux, AV_LOG_FATAL, "Error setting output stream dispositions\n");
  2024. exit_program(1);
  2025. }
  2026. // parse forced keyframe specifications;
  2027. // must be done after chapters are created
  2028. err = process_forced_keyframes(mux, o);
  2029. if (err < 0) {
  2030. av_log(mux, AV_LOG_FATAL, "Error processing forced keyframes\n");
  2031. exit_program(1);
  2032. }
  2033. err = setup_sync_queues(mux, oc, o->shortest_buf_duration * AV_TIME_BASE);
  2034. if (err < 0) {
  2035. av_log(mux, AV_LOG_FATAL, "Error setting up output sync queues\n");
  2036. exit_program(1);
  2037. }
  2038. of->url = filename;
  2039. /* write the header for files with no streams */
  2040. if (of->format->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
  2041. int ret = mux_check_init(mux);
  2042. if (ret < 0)
  2043. return ret;
  2044. }
  2045. return 0;
  2046. }