ffmpeg_mux_init.c 114 KB

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