ffmpeg_mux_init.c 112 KB

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