ffmpeg_mux_init.c 95 KB

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