ffmpeg_mux_init.c 113 KB

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