ffmpeg_mux_init.c 115 KB

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