ffmpeg_mux_init.c 103 KB

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