ffmpeg_mux_init.c 111 KB

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