utils.c 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095
  1. /*
  2. * various utility functions for use within FFmpeg
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /* #define DEBUG */
  22. #include "avformat.h"
  23. #include "avio_internal.h"
  24. #include "internal.h"
  25. #include "libavcodec/internal.h"
  26. #include "libavcodec/raw.h"
  27. #include "libavutil/opt.h"
  28. #include "libavutil/dict.h"
  29. #include "libavutil/pixdesc.h"
  30. #include "metadata.h"
  31. #include "id3v2.h"
  32. #include "libavutil/avstring.h"
  33. #include "libavutil/mathematics.h"
  34. #include "riff.h"
  35. #include "audiointerleave.h"
  36. #include "url.h"
  37. #include <sys/time.h>
  38. #include <time.h>
  39. #include <strings.h>
  40. #include <stdarg.h>
  41. #if CONFIG_NETWORK
  42. #include "network.h"
  43. #endif
  44. #undef NDEBUG
  45. #include <assert.h>
  46. /**
  47. * @file
  48. * various utility functions for use within FFmpeg
  49. */
  50. unsigned avformat_version(void)
  51. {
  52. return LIBAVFORMAT_VERSION_INT;
  53. }
  54. const char *avformat_configuration(void)
  55. {
  56. return FFMPEG_CONFIGURATION;
  57. }
  58. const char *avformat_license(void)
  59. {
  60. #define LICENSE_PREFIX "libavformat license: "
  61. return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
  62. }
  63. /* fraction handling */
  64. /**
  65. * f = val + (num / den) + 0.5.
  66. *
  67. * 'num' is normalized so that it is such as 0 <= num < den.
  68. *
  69. * @param f fractional number
  70. * @param val integer value
  71. * @param num must be >= 0
  72. * @param den must be >= 1
  73. */
  74. static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
  75. {
  76. num += (den >> 1);
  77. if (num >= den) {
  78. val += num / den;
  79. num = num % den;
  80. }
  81. f->val = val;
  82. f->num = num;
  83. f->den = den;
  84. }
  85. /**
  86. * Fractional addition to f: f = f + (incr / f->den).
  87. *
  88. * @param f fractional number
  89. * @param incr increment, can be positive or negative
  90. */
  91. static void frac_add(AVFrac *f, int64_t incr)
  92. {
  93. int64_t num, den;
  94. num = f->num + incr;
  95. den = f->den;
  96. if (num < 0) {
  97. f->val += num / den;
  98. num = num % den;
  99. if (num < 0) {
  100. num += den;
  101. f->val--;
  102. }
  103. } else if (num >= den) {
  104. f->val += num / den;
  105. num = num % den;
  106. }
  107. f->num = num;
  108. }
  109. /** head of registered input format linked list */
  110. static AVInputFormat *first_iformat = NULL;
  111. /** head of registered output format linked list */
  112. static AVOutputFormat *first_oformat = NULL;
  113. AVInputFormat *av_iformat_next(AVInputFormat *f)
  114. {
  115. if(f) return f->next;
  116. else return first_iformat;
  117. }
  118. AVOutputFormat *av_oformat_next(AVOutputFormat *f)
  119. {
  120. if(f) return f->next;
  121. else return first_oformat;
  122. }
  123. void av_register_input_format(AVInputFormat *format)
  124. {
  125. AVInputFormat **p;
  126. p = &first_iformat;
  127. while (*p != NULL) p = &(*p)->next;
  128. *p = format;
  129. format->next = NULL;
  130. }
  131. void av_register_output_format(AVOutputFormat *format)
  132. {
  133. AVOutputFormat **p;
  134. p = &first_oformat;
  135. while (*p != NULL) p = &(*p)->next;
  136. *p = format;
  137. format->next = NULL;
  138. }
  139. int av_match_ext(const char *filename, const char *extensions)
  140. {
  141. const char *ext, *p;
  142. char ext1[32], *q;
  143. if(!filename)
  144. return 0;
  145. ext = strrchr(filename, '.');
  146. if (ext) {
  147. ext++;
  148. p = extensions;
  149. for(;;) {
  150. q = ext1;
  151. while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
  152. *q++ = *p++;
  153. *q = '\0';
  154. if (!strcasecmp(ext1, ext))
  155. return 1;
  156. if (*p == '\0')
  157. break;
  158. p++;
  159. }
  160. }
  161. return 0;
  162. }
  163. static int match_format(const char *name, const char *names)
  164. {
  165. const char *p;
  166. int len, namelen;
  167. if (!name || !names)
  168. return 0;
  169. namelen = strlen(name);
  170. while ((p = strchr(names, ','))) {
  171. len = FFMAX(p - names, namelen);
  172. if (!strncasecmp(name, names, len))
  173. return 1;
  174. names = p+1;
  175. }
  176. return !strcasecmp(name, names);
  177. }
  178. AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
  179. const char *mime_type)
  180. {
  181. AVOutputFormat *fmt = NULL, *fmt_found;
  182. int score_max, score;
  183. /* specific test for image sequences */
  184. #if CONFIG_IMAGE2_MUXER
  185. if (!short_name && filename &&
  186. av_filename_number_test(filename) &&
  187. ff_guess_image2_codec(filename) != CODEC_ID_NONE) {
  188. return av_guess_format("image2", NULL, NULL);
  189. }
  190. #endif
  191. /* Find the proper file type. */
  192. fmt_found = NULL;
  193. score_max = 0;
  194. while ((fmt = av_oformat_next(fmt))) {
  195. score = 0;
  196. if (fmt->name && short_name && !strcmp(fmt->name, short_name))
  197. score += 100;
  198. if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
  199. score += 10;
  200. if (filename && fmt->extensions &&
  201. av_match_ext(filename, fmt->extensions)) {
  202. score += 5;
  203. }
  204. if (score > score_max) {
  205. score_max = score;
  206. fmt_found = fmt;
  207. }
  208. }
  209. return fmt_found;
  210. }
  211. enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
  212. const char *filename, const char *mime_type, enum AVMediaType type){
  213. if(type == AVMEDIA_TYPE_VIDEO){
  214. enum CodecID codec_id= CODEC_ID_NONE;
  215. #if CONFIG_IMAGE2_MUXER
  216. if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
  217. codec_id= ff_guess_image2_codec(filename);
  218. }
  219. #endif
  220. if(codec_id == CODEC_ID_NONE)
  221. codec_id= fmt->video_codec;
  222. return codec_id;
  223. }else if(type == AVMEDIA_TYPE_AUDIO)
  224. return fmt->audio_codec;
  225. else if (type == AVMEDIA_TYPE_SUBTITLE)
  226. return fmt->subtitle_codec;
  227. else
  228. return CODEC_ID_NONE;
  229. }
  230. AVInputFormat *av_find_input_format(const char *short_name)
  231. {
  232. AVInputFormat *fmt = NULL;
  233. while ((fmt = av_iformat_next(fmt))) {
  234. if (match_format(short_name, fmt->name))
  235. return fmt;
  236. }
  237. return NULL;
  238. }
  239. int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
  240. {
  241. int ret= av_new_packet(pkt, size);
  242. if(ret<0)
  243. return ret;
  244. pkt->pos= avio_tell(s);
  245. ret= avio_read(s, pkt->data, size);
  246. if(ret<=0)
  247. av_free_packet(pkt);
  248. else
  249. av_shrink_packet(pkt, ret);
  250. return ret;
  251. }
  252. int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
  253. {
  254. int ret;
  255. int old_size;
  256. if (!pkt->size)
  257. return av_get_packet(s, pkt, size);
  258. old_size = pkt->size;
  259. ret = av_grow_packet(pkt, size);
  260. if (ret < 0)
  261. return ret;
  262. ret = avio_read(s, pkt->data + old_size, size);
  263. av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
  264. return ret;
  265. }
  266. int av_filename_number_test(const char *filename)
  267. {
  268. char buf[1024];
  269. return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
  270. }
  271. AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened, int *score_ret)
  272. {
  273. AVProbeData lpd = *pd;
  274. AVInputFormat *fmt1 = NULL, *fmt;
  275. int score, score_max=0;
  276. if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
  277. int id3len = ff_id3v2_tag_len(lpd.buf);
  278. if (lpd.buf_size > id3len + 16) {
  279. lpd.buf += id3len;
  280. lpd.buf_size -= id3len;
  281. }
  282. }
  283. fmt = NULL;
  284. while ((fmt1 = av_iformat_next(fmt1))) {
  285. if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
  286. continue;
  287. score = 0;
  288. if (fmt1->read_probe) {
  289. score = fmt1->read_probe(&lpd);
  290. if(!score && fmt1->extensions && av_match_ext(lpd.filename, fmt1->extensions))
  291. score = 1;
  292. } else if (fmt1->extensions) {
  293. if (av_match_ext(lpd.filename, fmt1->extensions)) {
  294. score = 50;
  295. }
  296. }
  297. if (score > score_max) {
  298. score_max = score;
  299. fmt = fmt1;
  300. }else if (score == score_max)
  301. fmt = NULL;
  302. }
  303. *score_ret= score_max;
  304. return fmt;
  305. }
  306. AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
  307. {
  308. int score_ret;
  309. AVInputFormat *fmt= av_probe_input_format3(pd, is_opened, &score_ret);
  310. if(score_ret > *score_max){
  311. *score_max= score_ret;
  312. return fmt;
  313. }else
  314. return NULL;
  315. }
  316. AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
  317. int score=0;
  318. return av_probe_input_format2(pd, is_opened, &score);
  319. }
  320. static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd)
  321. {
  322. static const struct {
  323. const char *name; enum CodecID id; enum AVMediaType type;
  324. } fmt_id_type[] = {
  325. { "aac" , CODEC_ID_AAC , AVMEDIA_TYPE_AUDIO },
  326. { "ac3" , CODEC_ID_AC3 , AVMEDIA_TYPE_AUDIO },
  327. { "dts" , CODEC_ID_DTS , AVMEDIA_TYPE_AUDIO },
  328. { "eac3" , CODEC_ID_EAC3 , AVMEDIA_TYPE_AUDIO },
  329. { "h264" , CODEC_ID_H264 , AVMEDIA_TYPE_VIDEO },
  330. { "loas" , CODEC_ID_AAC_LATM , AVMEDIA_TYPE_AUDIO },
  331. { "m4v" , CODEC_ID_MPEG4 , AVMEDIA_TYPE_VIDEO },
  332. { "mp3" , CODEC_ID_MP3 , AVMEDIA_TYPE_AUDIO },
  333. { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
  334. { 0 }
  335. };
  336. int score;
  337. AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
  338. if (fmt) {
  339. int i;
  340. av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
  341. pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
  342. for (i = 0; fmt_id_type[i].name; i++) {
  343. if (!strcmp(fmt->name, fmt_id_type[i].name)) {
  344. st->codec->codec_id = fmt_id_type[i].id;
  345. st->codec->codec_type = fmt_id_type[i].type;
  346. break;
  347. }
  348. }
  349. }
  350. return score;
  351. }
  352. /************************************************************/
  353. /* input media file */
  354. #if FF_API_FORMAT_PARAMETERS
  355. static AVDictionary *convert_format_parameters(AVFormatParameters *ap)
  356. {
  357. char buf[1024];
  358. AVDictionary *opts = NULL;
  359. if (!ap)
  360. return NULL;
  361. if (ap->time_base.num) {
  362. snprintf(buf, sizeof(buf), "%d/%d", ap->time_base.den, ap->time_base.num);
  363. av_dict_set(&opts, "framerate", buf, 0);
  364. }
  365. if (ap->sample_rate) {
  366. snprintf(buf, sizeof(buf), "%d", ap->sample_rate);
  367. av_dict_set(&opts, "sample_rate", buf, 0);
  368. }
  369. if (ap->channels) {
  370. snprintf(buf, sizeof(buf), "%d", ap->channels);
  371. av_dict_set(&opts, "channels", buf, 0);
  372. }
  373. if (ap->width || ap->height) {
  374. snprintf(buf, sizeof(buf), "%dx%d", ap->width, ap->height);
  375. av_dict_set(&opts, "video_size", buf, 0);
  376. }
  377. if (ap->pix_fmt != PIX_FMT_NONE) {
  378. av_dict_set(&opts, "pixel_format", av_get_pix_fmt_name(ap->pix_fmt), 0);
  379. }
  380. if (ap->channel) {
  381. snprintf(buf, sizeof(buf), "%d", ap->channel);
  382. av_dict_set(&opts, "channel", buf, 0);
  383. }
  384. if (ap->standard) {
  385. av_dict_set(&opts, "standard", ap->standard, 0);
  386. }
  387. if (ap->mpeg2ts_compute_pcr) {
  388. av_dict_set(&opts, "mpeg2ts_compute_pcr", "1", 0);
  389. }
  390. if (ap->initial_pause) {
  391. av_dict_set(&opts, "initial_pause", "1", 0);
  392. }
  393. return opts;
  394. }
  395. /**
  396. * Open a media file from an IO stream. 'fmt' must be specified.
  397. */
  398. int av_open_input_stream(AVFormatContext **ic_ptr,
  399. AVIOContext *pb, const char *filename,
  400. AVInputFormat *fmt, AVFormatParameters *ap)
  401. {
  402. int err;
  403. AVDictionary *opts;
  404. AVFormatContext *ic;
  405. AVFormatParameters default_ap;
  406. if(!ap){
  407. ap=&default_ap;
  408. memset(ap, 0, sizeof(default_ap));
  409. }
  410. opts = convert_format_parameters(ap);
  411. if(!ap->prealloced_context)
  412. *ic_ptr = ic = avformat_alloc_context();
  413. else
  414. ic = *ic_ptr;
  415. if (!ic) {
  416. err = AVERROR(ENOMEM);
  417. goto fail;
  418. }
  419. if (pb && fmt && fmt->flags & AVFMT_NOFILE)
  420. av_log(ic, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
  421. "will be ignored with AVFMT_NOFILE format.\n");
  422. else
  423. ic->pb = pb;
  424. if ((err = avformat_open_input(&ic, filename, fmt, &opts)) < 0)
  425. goto fail;
  426. ic->pb = ic->pb ? ic->pb : pb; // don't leak custom pb if it wasn't set above
  427. *ic_ptr = ic;
  428. fail:
  429. av_dict_free(&opts);
  430. return err;
  431. }
  432. #endif
  433. int av_demuxer_open(AVFormatContext *ic, AVFormatParameters *ap){
  434. int err;
  435. if (ic->iformat->read_header) {
  436. err = ic->iformat->read_header(ic, ap);
  437. if (err < 0)
  438. return err;
  439. }
  440. if (ic->pb && !ic->data_offset)
  441. ic->data_offset = avio_tell(ic->pb);
  442. return 0;
  443. }
  444. /** size of probe buffer, for guessing file type from file contents */
  445. #define PROBE_BUF_MIN 2048
  446. #define PROBE_BUF_MAX (1<<20)
  447. int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
  448. const char *filename, void *logctx,
  449. unsigned int offset, unsigned int max_probe_size)
  450. {
  451. AVProbeData pd = { filename ? filename : "", NULL, -offset };
  452. unsigned char *buf = NULL;
  453. int ret = 0, probe_size;
  454. if (!max_probe_size) {
  455. max_probe_size = PROBE_BUF_MAX;
  456. } else if (max_probe_size > PROBE_BUF_MAX) {
  457. max_probe_size = PROBE_BUF_MAX;
  458. } else if (max_probe_size < PROBE_BUF_MIN) {
  459. return AVERROR(EINVAL);
  460. }
  461. if (offset >= max_probe_size) {
  462. return AVERROR(EINVAL);
  463. }
  464. for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;
  465. probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
  466. int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
  467. int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
  468. void *buftmp;
  469. if (probe_size < offset) {
  470. continue;
  471. }
  472. /* read probe data */
  473. buftmp = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
  474. if(!buftmp){
  475. av_free(buf);
  476. return AVERROR(ENOMEM);
  477. }
  478. buf=buftmp;
  479. if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
  480. /* fail if error was not end of file, otherwise, lower score */
  481. if (ret != AVERROR_EOF) {
  482. av_free(buf);
  483. return ret;
  484. }
  485. score = 0;
  486. ret = 0; /* error was end of file, nothing read */
  487. }
  488. pd.buf_size += ret;
  489. pd.buf = &buf[offset];
  490. memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
  491. /* guess file format */
  492. *fmt = av_probe_input_format2(&pd, 1, &score);
  493. if(*fmt){
  494. if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
  495. av_log(logctx, AV_LOG_WARNING, "Format %s detected only with low score of %d, misdetection possible!\n", (*fmt)->name, score);
  496. }else
  497. av_log(logctx, AV_LOG_DEBUG, "Format %s probed with size=%d and score=%d\n", (*fmt)->name, probe_size, score);
  498. }
  499. }
  500. if (!*fmt) {
  501. av_free(buf);
  502. return AVERROR_INVALIDDATA;
  503. }
  504. /* rewind. reuse probe buffer to avoid seeking */
  505. if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
  506. av_free(buf);
  507. return ret;
  508. }
  509. #if FF_API_FORMAT_PARAMETERS
  510. int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
  511. AVInputFormat *fmt,
  512. int buf_size,
  513. AVFormatParameters *ap)
  514. {
  515. int err;
  516. AVDictionary *opts = convert_format_parameters(ap);
  517. if (!ap || !ap->prealloced_context)
  518. *ic_ptr = NULL;
  519. err = avformat_open_input(ic_ptr, filename, fmt, &opts);
  520. av_dict_free(&opts);
  521. return err;
  522. }
  523. #endif
  524. /* open input file and probe the format if necessary */
  525. static int init_input(AVFormatContext *s, const char *filename)
  526. {
  527. int ret;
  528. AVProbeData pd = {filename, NULL, 0};
  529. if (s->pb) {
  530. s->flags |= AVFMT_FLAG_CUSTOM_IO;
  531. if (!s->iformat)
  532. return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);
  533. else if (s->iformat->flags & AVFMT_NOFILE)
  534. av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
  535. "will be ignored with AVFMT_NOFILE format.\n");
  536. return 0;
  537. }
  538. if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
  539. (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
  540. return 0;
  541. if ((ret = avio_open(&s->pb, filename, AVIO_FLAG_READ)) < 0)
  542. return ret;
  543. if (s->iformat)
  544. return 0;
  545. return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);
  546. }
  547. int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
  548. {
  549. AVFormatContext *s = *ps;
  550. int ret = 0;
  551. AVFormatParameters ap = { { 0 } };
  552. AVDictionary *tmp = NULL;
  553. if (!s && !(s = avformat_alloc_context()))
  554. return AVERROR(ENOMEM);
  555. if (fmt)
  556. s->iformat = fmt;
  557. if (options)
  558. av_dict_copy(&tmp, *options, 0);
  559. if ((ret = av_opt_set_dict(s, &tmp)) < 0)
  560. goto fail;
  561. if ((ret = init_input(s, filename)) < 0)
  562. goto fail;
  563. /* check filename in case an image number is expected */
  564. if (s->iformat->flags & AVFMT_NEEDNUMBER) {
  565. if (!av_filename_number_test(filename)) {
  566. ret = AVERROR(EINVAL);
  567. goto fail;
  568. }
  569. }
  570. s->duration = s->start_time = AV_NOPTS_VALUE;
  571. av_strlcpy(s->filename, filename, sizeof(s->filename));
  572. /* allocate private data */
  573. if (s->iformat->priv_data_size > 0) {
  574. if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
  575. ret = AVERROR(ENOMEM);
  576. goto fail;
  577. }
  578. if (s->iformat->priv_class) {
  579. *(const AVClass**)s->priv_data = s->iformat->priv_class;
  580. av_opt_set_defaults(s->priv_data);
  581. if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  582. goto fail;
  583. }
  584. }
  585. /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
  586. if (s->pb)
  587. ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC);
  588. if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
  589. if ((ret = s->iformat->read_header(s, &ap)) < 0)
  590. goto fail;
  591. if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->data_offset)
  592. s->data_offset = avio_tell(s->pb);
  593. s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
  594. if (options) {
  595. av_dict_free(options);
  596. *options = tmp;
  597. }
  598. *ps = s;
  599. return 0;
  600. fail:
  601. av_dict_free(&tmp);
  602. if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
  603. avio_close(s->pb);
  604. avformat_free_context(s);
  605. *ps = NULL;
  606. return ret;
  607. }
  608. /*******************************************************/
  609. static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
  610. AVPacketList **plast_pktl){
  611. AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
  612. if (!pktl)
  613. return NULL;
  614. if (*packet_buffer)
  615. (*plast_pktl)->next = pktl;
  616. else
  617. *packet_buffer = pktl;
  618. /* add the packet in the buffered packet list */
  619. *plast_pktl = pktl;
  620. pktl->pkt= *pkt;
  621. return &pktl->pkt;
  622. }
  623. int av_read_packet(AVFormatContext *s, AVPacket *pkt)
  624. {
  625. int ret, i;
  626. AVStream *st;
  627. for(;;){
  628. AVPacketList *pktl = s->raw_packet_buffer;
  629. if (pktl) {
  630. *pkt = pktl->pkt;
  631. if(s->streams[pkt->stream_index]->request_probe <= 0){
  632. s->raw_packet_buffer = pktl->next;
  633. s->raw_packet_buffer_remaining_size += pkt->size;
  634. av_free(pktl);
  635. return 0;
  636. }
  637. }
  638. av_init_packet(pkt);
  639. ret= s->iformat->read_packet(s, pkt);
  640. if (ret < 0) {
  641. if (!pktl || ret == AVERROR(EAGAIN))
  642. return ret;
  643. for (i = 0; i < s->nb_streams; i++)
  644. if(s->streams[i]->request_probe > 0)
  645. s->streams[i]->request_probe = -1;
  646. continue;
  647. }
  648. if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
  649. (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
  650. av_log(s, AV_LOG_WARNING,
  651. "Dropped corrupted packet (stream = %d)\n",
  652. pkt->stream_index);
  653. continue;
  654. }
  655. if(!(s->flags & AVFMT_FLAG_KEEP_SIDE_DATA))
  656. av_packet_merge_side_data(pkt);
  657. st= s->streams[pkt->stream_index];
  658. switch(st->codec->codec_type){
  659. case AVMEDIA_TYPE_VIDEO:
  660. if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
  661. break;
  662. case AVMEDIA_TYPE_AUDIO:
  663. if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
  664. break;
  665. case AVMEDIA_TYPE_SUBTITLE:
  666. if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
  667. break;
  668. }
  669. if(!pktl && st->request_probe <= 0)
  670. return ret;
  671. add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
  672. s->raw_packet_buffer_remaining_size -= pkt->size;
  673. if(st->request_probe>0){
  674. AVProbeData *pd = &st->probe_data;
  675. int end;
  676. av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
  677. --st->probe_packets;
  678. pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
  679. memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
  680. pd->buf_size += pkt->size;
  681. memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
  682. end= s->raw_packet_buffer_remaining_size <= 0
  683. || st->probe_packets<=0;
  684. if(end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
  685. int score= set_codec_from_probe_data(s, st, pd);
  686. if( (st->codec->codec_id != CODEC_ID_NONE && score > AVPROBE_SCORE_MAX/4)
  687. || end){
  688. pd->buf_size=0;
  689. av_freep(&pd->buf);
  690. st->request_probe= -1;
  691. if(st->codec->codec_id != CODEC_ID_NONE){
  692. av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
  693. }else
  694. av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
  695. }
  696. }
  697. }
  698. }
  699. }
  700. /**********************************************************/
  701. /**
  702. * Get the number of samples of an audio frame. Return -1 on error.
  703. */
  704. static int get_audio_frame_size(AVCodecContext *enc, int size)
  705. {
  706. int frame_size;
  707. if(enc->codec_id == CODEC_ID_VORBIS)
  708. return -1;
  709. if (enc->frame_size <= 1) {
  710. int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
  711. if (bits_per_sample) {
  712. if (enc->channels == 0)
  713. return -1;
  714. frame_size = (size << 3) / (bits_per_sample * enc->channels);
  715. } else {
  716. /* used for example by ADPCM codecs */
  717. if (enc->bit_rate == 0)
  718. return -1;
  719. frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
  720. }
  721. } else {
  722. frame_size = enc->frame_size;
  723. }
  724. return frame_size;
  725. }
  726. /**
  727. * Return the frame duration in seconds. Return 0 if not available.
  728. */
  729. static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
  730. AVCodecParserContext *pc, AVPacket *pkt)
  731. {
  732. int frame_size;
  733. *pnum = 0;
  734. *pden = 0;
  735. switch(st->codec->codec_type) {
  736. case AVMEDIA_TYPE_VIDEO:
  737. if(st->time_base.num*1000LL > st->time_base.den){
  738. *pnum = st->time_base.num;
  739. *pden = st->time_base.den;
  740. }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
  741. *pnum = st->codec->time_base.num;
  742. *pden = st->codec->time_base.den;
  743. if (pc && pc->repeat_pict) {
  744. *pnum = (*pnum) * (1 + pc->repeat_pict);
  745. }
  746. //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
  747. //Thus if we have no parser in such case leave duration undefined.
  748. if(st->codec->ticks_per_frame>1 && !pc){
  749. *pnum = *pden = 0;
  750. }
  751. }
  752. break;
  753. case AVMEDIA_TYPE_AUDIO:
  754. frame_size = get_audio_frame_size(st->codec, pkt->size);
  755. if (frame_size <= 0 || st->codec->sample_rate <= 0)
  756. break;
  757. *pnum = frame_size;
  758. *pden = st->codec->sample_rate;
  759. break;
  760. default:
  761. break;
  762. }
  763. }
  764. static int is_intra_only(AVCodecContext *enc){
  765. if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
  766. return 1;
  767. }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
  768. switch(enc->codec_id){
  769. case CODEC_ID_MJPEG:
  770. case CODEC_ID_MJPEGB:
  771. case CODEC_ID_LJPEG:
  772. case CODEC_ID_RAWVIDEO:
  773. case CODEC_ID_DVVIDEO:
  774. case CODEC_ID_HUFFYUV:
  775. case CODEC_ID_FFVHUFF:
  776. case CODEC_ID_ASV1:
  777. case CODEC_ID_ASV2:
  778. case CODEC_ID_VCR1:
  779. case CODEC_ID_DNXHD:
  780. case CODEC_ID_JPEG2000:
  781. return 1;
  782. default: break;
  783. }
  784. }
  785. return 0;
  786. }
  787. static void update_initial_timestamps(AVFormatContext *s, int stream_index,
  788. int64_t dts, int64_t pts)
  789. {
  790. AVStream *st= s->streams[stream_index];
  791. AVPacketList *pktl= s->packet_buffer;
  792. if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
  793. return;
  794. st->first_dts= dts - st->cur_dts;
  795. st->cur_dts= dts;
  796. for(; pktl; pktl= pktl->next){
  797. if(pktl->pkt.stream_index != stream_index)
  798. continue;
  799. //FIXME think more about this check
  800. if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
  801. pktl->pkt.pts += st->first_dts;
  802. if(pktl->pkt.dts != AV_NOPTS_VALUE)
  803. pktl->pkt.dts += st->first_dts;
  804. if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
  805. st->start_time= pktl->pkt.pts;
  806. }
  807. if (st->start_time == AV_NOPTS_VALUE)
  808. st->start_time = pts;
  809. }
  810. static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  811. {
  812. AVPacketList *pktl= s->packet_buffer;
  813. int64_t cur_dts= 0;
  814. if(st->first_dts != AV_NOPTS_VALUE){
  815. cur_dts= st->first_dts;
  816. for(; pktl; pktl= pktl->next){
  817. if(pktl->pkt.stream_index == pkt->stream_index){
  818. if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
  819. break;
  820. cur_dts -= pkt->duration;
  821. }
  822. }
  823. pktl= s->packet_buffer;
  824. st->first_dts = cur_dts;
  825. }else if(st->cur_dts)
  826. return;
  827. for(; pktl; pktl= pktl->next){
  828. if(pktl->pkt.stream_index != pkt->stream_index)
  829. continue;
  830. if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
  831. && !pktl->pkt.duration){
  832. pktl->pkt.dts= cur_dts;
  833. if(!st->codec->has_b_frames)
  834. pktl->pkt.pts= cur_dts;
  835. cur_dts += pkt->duration;
  836. pktl->pkt.duration= pkt->duration;
  837. }else
  838. break;
  839. }
  840. if(st->first_dts == AV_NOPTS_VALUE)
  841. st->cur_dts= cur_dts;
  842. }
  843. static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
  844. AVCodecParserContext *pc, AVPacket *pkt)
  845. {
  846. int num, den, presentation_delayed, delay, i;
  847. int64_t offset;
  848. if (s->flags & AVFMT_FLAG_NOFILLIN)
  849. return;
  850. if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
  851. pkt->dts= AV_NOPTS_VALUE;
  852. if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == AV_PICTURE_TYPE_B)
  853. //FIXME Set low_delay = 0 when has_b_frames = 1
  854. st->codec->has_b_frames = 1;
  855. /* do we have a video B-frame ? */
  856. delay= st->codec->has_b_frames;
  857. presentation_delayed = 0;
  858. // ignore delay caused by frame threading so that the mpeg2-without-dts
  859. // warning will not trigger
  860. if (delay && st->codec->active_thread_type&FF_THREAD_FRAME)
  861. delay -= st->codec->thread_count-1;
  862. /* XXX: need has_b_frame, but cannot get it if the codec is
  863. not initialized */
  864. if (delay &&
  865. pc && pc->pict_type != AV_PICTURE_TYPE_B)
  866. presentation_delayed = 1;
  867. if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
  868. /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
  869. pkt->dts -= 1LL<<st->pts_wrap_bits;
  870. }
  871. // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
  872. // we take the conservative approach and discard both
  873. // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
  874. if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
  875. av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
  876. pkt->dts= pkt->pts= AV_NOPTS_VALUE;
  877. }
  878. if (pkt->duration == 0) {
  879. compute_frame_duration(&num, &den, st, pc, pkt);
  880. if (den && num) {
  881. pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
  882. if(pkt->duration != 0 && s->packet_buffer)
  883. update_initial_durations(s, st, pkt);
  884. }
  885. }
  886. /* correct timestamps with byte offset if demuxers only have timestamps
  887. on packet boundaries */
  888. if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
  889. /* this will estimate bitrate based on this frame's duration and size */
  890. offset = av_rescale(pc->offset, pkt->duration, pkt->size);
  891. if(pkt->pts != AV_NOPTS_VALUE)
  892. pkt->pts += offset;
  893. if(pkt->dts != AV_NOPTS_VALUE)
  894. pkt->dts += offset;
  895. }
  896. if (pc && pc->dts_sync_point >= 0) {
  897. // we have synchronization info from the parser
  898. int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
  899. if (den > 0) {
  900. int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
  901. if (pkt->dts != AV_NOPTS_VALUE) {
  902. // got DTS from the stream, update reference timestamp
  903. st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
  904. pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
  905. } else if (st->reference_dts != AV_NOPTS_VALUE) {
  906. // compute DTS based on reference timestamp
  907. pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
  908. pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
  909. }
  910. if (pc->dts_sync_point > 0)
  911. st->reference_dts = pkt->dts; // new reference
  912. }
  913. }
  914. /* This may be redundant, but it should not hurt. */
  915. if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
  916. presentation_delayed = 1;
  917. // av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
  918. /* interpolate PTS and DTS if they are not present */
  919. //We skip H264 currently because delay and has_b_frames are not reliably set
  920. if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
  921. if (presentation_delayed) {
  922. /* DTS = decompression timestamp */
  923. /* PTS = presentation timestamp */
  924. if (pkt->dts == AV_NOPTS_VALUE)
  925. pkt->dts = st->last_IP_pts;
  926. update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
  927. if (pkt->dts == AV_NOPTS_VALUE)
  928. pkt->dts = st->cur_dts;
  929. /* this is tricky: the dts must be incremented by the duration
  930. of the frame we are displaying, i.e. the last I- or P-frame */
  931. if (st->last_IP_duration == 0)
  932. st->last_IP_duration = pkt->duration;
  933. if(pkt->dts != AV_NOPTS_VALUE)
  934. st->cur_dts = pkt->dts + st->last_IP_duration;
  935. st->last_IP_duration = pkt->duration;
  936. st->last_IP_pts= pkt->pts;
  937. /* cannot compute PTS if not present (we can compute it only
  938. by knowing the future */
  939. } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
  940. if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
  941. int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
  942. int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
  943. if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
  944. pkt->pts += pkt->duration;
  945. // av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
  946. }
  947. }
  948. /* presentation is not delayed : PTS and DTS are the same */
  949. if(pkt->pts == AV_NOPTS_VALUE)
  950. pkt->pts = pkt->dts;
  951. update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
  952. if(pkt->pts == AV_NOPTS_VALUE)
  953. pkt->pts = st->cur_dts;
  954. pkt->dts = pkt->pts;
  955. if(pkt->pts != AV_NOPTS_VALUE)
  956. st->cur_dts = pkt->pts + pkt->duration;
  957. }
  958. }
  959. if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
  960. st->pts_buffer[0]= pkt->pts;
  961. for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
  962. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
  963. if(pkt->dts == AV_NOPTS_VALUE)
  964. pkt->dts= st->pts_buffer[0];
  965. if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
  966. update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
  967. }
  968. if(pkt->dts > st->cur_dts)
  969. st->cur_dts = pkt->dts;
  970. }
  971. // av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
  972. /* update flags */
  973. if(is_intra_only(st->codec))
  974. pkt->flags |= AV_PKT_FLAG_KEY;
  975. else if (pc) {
  976. pkt->flags = 0;
  977. /* keyframe computation */
  978. if (pc->key_frame == 1)
  979. pkt->flags |= AV_PKT_FLAG_KEY;
  980. else if (pc->key_frame == -1 && pc->pict_type == AV_PICTURE_TYPE_I)
  981. pkt->flags |= AV_PKT_FLAG_KEY;
  982. }
  983. if (pc)
  984. pkt->convergence_duration = pc->convergence_duration;
  985. }
  986. static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
  987. {
  988. AVStream *st;
  989. int len, ret, i;
  990. av_init_packet(pkt);
  991. for(;;) {
  992. /* select current input stream component */
  993. st = s->cur_st;
  994. if (st) {
  995. if (!st->need_parsing || !st->parser) {
  996. /* no parsing needed: we just output the packet as is */
  997. /* raw data support */
  998. *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
  999. compute_pkt_fields(s, st, NULL, pkt);
  1000. s->cur_st = NULL;
  1001. if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
  1002. (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
  1003. ff_reduce_index(s, st->index);
  1004. av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
  1005. }
  1006. break;
  1007. } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
  1008. len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
  1009. st->cur_ptr, st->cur_len,
  1010. st->cur_pkt.pts, st->cur_pkt.dts,
  1011. st->cur_pkt.pos);
  1012. st->cur_pkt.pts = AV_NOPTS_VALUE;
  1013. st->cur_pkt.dts = AV_NOPTS_VALUE;
  1014. /* increment read pointer */
  1015. st->cur_ptr += len;
  1016. st->cur_len -= len;
  1017. /* return packet if any */
  1018. if (pkt->size) {
  1019. got_packet:
  1020. pkt->duration = 0;
  1021. pkt->stream_index = st->index;
  1022. pkt->pts = st->parser->pts;
  1023. pkt->dts = st->parser->dts;
  1024. pkt->pos = st->parser->pos;
  1025. if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
  1026. s->cur_st = NULL;
  1027. pkt->destruct= st->cur_pkt.destruct;
  1028. st->cur_pkt.destruct= NULL;
  1029. st->cur_pkt.data = NULL;
  1030. assert(st->cur_len == 0);
  1031. }else{
  1032. pkt->destruct = NULL;
  1033. }
  1034. compute_pkt_fields(s, st, st->parser, pkt);
  1035. if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
  1036. int64_t pos= (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->pos : st->parser->frame_offset;
  1037. ff_reduce_index(s, st->index);
  1038. av_add_index_entry(st, pos, pkt->dts,
  1039. 0, 0, AVINDEX_KEYFRAME);
  1040. }
  1041. break;
  1042. }
  1043. } else {
  1044. /* free packet */
  1045. av_free_packet(&st->cur_pkt);
  1046. s->cur_st = NULL;
  1047. }
  1048. } else {
  1049. AVPacket cur_pkt;
  1050. /* read next packet */
  1051. ret = av_read_packet(s, &cur_pkt);
  1052. if (ret < 0) {
  1053. if (ret == AVERROR(EAGAIN))
  1054. return ret;
  1055. /* return the last frames, if any */
  1056. for(i = 0; i < s->nb_streams; i++) {
  1057. st = s->streams[i];
  1058. if (st->parser && st->need_parsing) {
  1059. av_parser_parse2(st->parser, st->codec,
  1060. &pkt->data, &pkt->size,
  1061. NULL, 0,
  1062. AV_NOPTS_VALUE, AV_NOPTS_VALUE,
  1063. AV_NOPTS_VALUE);
  1064. if (pkt->size)
  1065. goto got_packet;
  1066. }
  1067. }
  1068. /* no more packets: really terminate parsing */
  1069. return ret;
  1070. }
  1071. st = s->streams[cur_pkt.stream_index];
  1072. st->cur_pkt= cur_pkt;
  1073. if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
  1074. st->cur_pkt.dts != AV_NOPTS_VALUE &&
  1075. st->cur_pkt.pts < st->cur_pkt.dts){
  1076. av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
  1077. st->cur_pkt.stream_index,
  1078. st->cur_pkt.pts,
  1079. st->cur_pkt.dts,
  1080. st->cur_pkt.size);
  1081. // av_free_packet(&st->cur_pkt);
  1082. // return -1;
  1083. }
  1084. if(s->debug & FF_FDEBUG_TS)
  1085. av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
  1086. st->cur_pkt.stream_index,
  1087. st->cur_pkt.pts,
  1088. st->cur_pkt.dts,
  1089. st->cur_pkt.size,
  1090. st->cur_pkt.duration,
  1091. st->cur_pkt.flags);
  1092. s->cur_st = st;
  1093. st->cur_ptr = st->cur_pkt.data;
  1094. st->cur_len = st->cur_pkt.size;
  1095. if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
  1096. st->parser = av_parser_init(st->codec->codec_id);
  1097. if (!st->parser) {
  1098. av_log(s, AV_LOG_WARNING, "parser not found for codec "
  1099. "%s, packets or times may be invalid.\n",
  1100. avcodec_get_name(st->codec->codec_id));
  1101. /* no parser available: just output the raw packets */
  1102. st->need_parsing = AVSTREAM_PARSE_NONE;
  1103. }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
  1104. st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
  1105. }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
  1106. st->parser->flags |= PARSER_FLAG_ONCE;
  1107. }
  1108. }
  1109. }
  1110. }
  1111. if(s->debug & FF_FDEBUG_TS)
  1112. av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
  1113. pkt->stream_index,
  1114. pkt->pts,
  1115. pkt->dts,
  1116. pkt->size,
  1117. pkt->duration,
  1118. pkt->flags);
  1119. return 0;
  1120. }
  1121. int av_read_frame(AVFormatContext *s, AVPacket *pkt)
  1122. {
  1123. AVPacketList *pktl;
  1124. int eof=0;
  1125. const int genpts= s->flags & AVFMT_FLAG_GENPTS;
  1126. for(;;){
  1127. pktl = s->packet_buffer;
  1128. if (pktl) {
  1129. AVPacket *next_pkt= &pktl->pkt;
  1130. if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
  1131. int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
  1132. while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
  1133. if( pktl->pkt.stream_index == next_pkt->stream_index
  1134. && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
  1135. && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
  1136. next_pkt->pts= pktl->pkt.dts;
  1137. }
  1138. pktl= pktl->next;
  1139. }
  1140. pktl = s->packet_buffer;
  1141. }
  1142. if( next_pkt->pts != AV_NOPTS_VALUE
  1143. || next_pkt->dts == AV_NOPTS_VALUE
  1144. || !genpts || eof){
  1145. /* read packet from packet buffer, if there is data */
  1146. *pkt = *next_pkt;
  1147. s->packet_buffer = pktl->next;
  1148. av_free(pktl);
  1149. return 0;
  1150. }
  1151. }
  1152. if(genpts){
  1153. int ret= read_frame_internal(s, pkt);
  1154. if(ret<0){
  1155. if(pktl && ret != AVERROR(EAGAIN)){
  1156. eof=1;
  1157. continue;
  1158. }else
  1159. return ret;
  1160. }
  1161. if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
  1162. &s->packet_buffer_end)) < 0)
  1163. return AVERROR(ENOMEM);
  1164. }else{
  1165. assert(!s->packet_buffer);
  1166. return read_frame_internal(s, pkt);
  1167. }
  1168. }
  1169. }
  1170. /* XXX: suppress the packet queue */
  1171. static void flush_packet_queue(AVFormatContext *s)
  1172. {
  1173. AVPacketList *pktl;
  1174. for(;;) {
  1175. pktl = s->packet_buffer;
  1176. if (!pktl)
  1177. break;
  1178. s->packet_buffer = pktl->next;
  1179. av_free_packet(&pktl->pkt);
  1180. av_free(pktl);
  1181. }
  1182. while(s->raw_packet_buffer){
  1183. pktl = s->raw_packet_buffer;
  1184. s->raw_packet_buffer = pktl->next;
  1185. av_free_packet(&pktl->pkt);
  1186. av_free(pktl);
  1187. }
  1188. s->packet_buffer_end=
  1189. s->raw_packet_buffer_end= NULL;
  1190. s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
  1191. }
  1192. /*******************************************************/
  1193. /* seek support */
  1194. int av_find_default_stream_index(AVFormatContext *s)
  1195. {
  1196. int first_audio_index = -1;
  1197. int i;
  1198. AVStream *st;
  1199. if (s->nb_streams <= 0)
  1200. return -1;
  1201. for(i = 0; i < s->nb_streams; i++) {
  1202. st = s->streams[i];
  1203. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1204. return i;
  1205. }
  1206. if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  1207. first_audio_index = i;
  1208. }
  1209. return first_audio_index >= 0 ? first_audio_index : 0;
  1210. }
  1211. /**
  1212. * Flush the frame reader.
  1213. */
  1214. void ff_read_frame_flush(AVFormatContext *s)
  1215. {
  1216. AVStream *st;
  1217. int i, j;
  1218. flush_packet_queue(s);
  1219. s->cur_st = NULL;
  1220. /* for each stream, reset read state */
  1221. for(i = 0; i < s->nb_streams; i++) {
  1222. st = s->streams[i];
  1223. if (st->parser) {
  1224. av_parser_close(st->parser);
  1225. st->parser = NULL;
  1226. av_free_packet(&st->cur_pkt);
  1227. }
  1228. st->last_IP_pts = AV_NOPTS_VALUE;
  1229. st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
  1230. st->reference_dts = AV_NOPTS_VALUE;
  1231. /* fail safe */
  1232. st->cur_ptr = NULL;
  1233. st->cur_len = 0;
  1234. st->probe_packets = MAX_PROBE_PACKETS;
  1235. for(j=0; j<MAX_REORDER_DELAY+1; j++)
  1236. st->pts_buffer[j]= AV_NOPTS_VALUE;
  1237. }
  1238. }
  1239. void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
  1240. int i;
  1241. for(i = 0; i < s->nb_streams; i++) {
  1242. AVStream *st = s->streams[i];
  1243. st->cur_dts = av_rescale(timestamp,
  1244. st->time_base.den * (int64_t)ref_st->time_base.num,
  1245. st->time_base.num * (int64_t)ref_st->time_base.den);
  1246. }
  1247. }
  1248. void ff_reduce_index(AVFormatContext *s, int stream_index)
  1249. {
  1250. AVStream *st= s->streams[stream_index];
  1251. unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
  1252. if((unsigned)st->nb_index_entries >= max_entries){
  1253. int i;
  1254. for(i=0; 2*i<st->nb_index_entries; i++)
  1255. st->index_entries[i]= st->index_entries[2*i];
  1256. st->nb_index_entries= i;
  1257. }
  1258. }
  1259. int ff_add_index_entry(AVIndexEntry **index_entries,
  1260. int *nb_index_entries,
  1261. unsigned int *index_entries_allocated_size,
  1262. int64_t pos, int64_t timestamp, int size, int distance, int flags)
  1263. {
  1264. AVIndexEntry *entries, *ie;
  1265. int index;
  1266. if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
  1267. return -1;
  1268. entries = av_fast_realloc(*index_entries,
  1269. index_entries_allocated_size,
  1270. (*nb_index_entries + 1) *
  1271. sizeof(AVIndexEntry));
  1272. if(!entries)
  1273. return -1;
  1274. *index_entries= entries;
  1275. index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
  1276. if(index<0){
  1277. index= (*nb_index_entries)++;
  1278. ie= &entries[index];
  1279. assert(index==0 || ie[-1].timestamp < timestamp);
  1280. }else{
  1281. ie= &entries[index];
  1282. if(ie->timestamp != timestamp){
  1283. if(ie->timestamp <= timestamp)
  1284. return -1;
  1285. memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
  1286. (*nb_index_entries)++;
  1287. }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
  1288. distance= ie->min_distance;
  1289. }
  1290. ie->pos = pos;
  1291. ie->timestamp = timestamp;
  1292. ie->min_distance= distance;
  1293. ie->size= size;
  1294. ie->flags = flags;
  1295. return index;
  1296. }
  1297. int av_add_index_entry(AVStream *st,
  1298. int64_t pos, int64_t timestamp, int size, int distance, int flags)
  1299. {
  1300. return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
  1301. &st->index_entries_allocated_size, pos,
  1302. timestamp, size, distance, flags);
  1303. }
  1304. int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
  1305. int64_t wanted_timestamp, int flags)
  1306. {
  1307. int a, b, m;
  1308. int64_t timestamp;
  1309. a = - 1;
  1310. b = nb_entries;
  1311. //optimize appending index entries at the end
  1312. if(b && entries[b-1].timestamp < wanted_timestamp)
  1313. a= b-1;
  1314. while (b - a > 1) {
  1315. m = (a + b) >> 1;
  1316. timestamp = entries[m].timestamp;
  1317. if(timestamp >= wanted_timestamp)
  1318. b = m;
  1319. if(timestamp <= wanted_timestamp)
  1320. a = m;
  1321. }
  1322. m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
  1323. if(!(flags & AVSEEK_FLAG_ANY)){
  1324. while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
  1325. m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
  1326. }
  1327. }
  1328. if(m == nb_entries)
  1329. return -1;
  1330. return m;
  1331. }
  1332. int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
  1333. int flags)
  1334. {
  1335. return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
  1336. wanted_timestamp, flags);
  1337. }
  1338. int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1339. AVInputFormat *avif= s->iformat;
  1340. int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
  1341. int64_t ts_min, ts_max, ts;
  1342. int index;
  1343. int64_t ret;
  1344. AVStream *st;
  1345. if (stream_index < 0)
  1346. return -1;
  1347. av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
  1348. ts_max=
  1349. ts_min= AV_NOPTS_VALUE;
  1350. pos_limit= -1; //gcc falsely says it may be uninitialized
  1351. st= s->streams[stream_index];
  1352. if(st->index_entries){
  1353. AVIndexEntry *e;
  1354. index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()
  1355. index= FFMAX(index, 0);
  1356. e= &st->index_entries[index];
  1357. if(e->timestamp <= target_ts || e->pos == e->min_distance){
  1358. pos_min= e->pos;
  1359. ts_min= e->timestamp;
  1360. av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
  1361. pos_min,ts_min);
  1362. }else{
  1363. assert(index==0);
  1364. }
  1365. index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
  1366. assert(index < st->nb_index_entries);
  1367. if(index >= 0){
  1368. e= &st->index_entries[index];
  1369. assert(e->timestamp >= target_ts);
  1370. pos_max= e->pos;
  1371. ts_max= e->timestamp;
  1372. pos_limit= pos_max - e->min_distance;
  1373. av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
  1374. pos_max,pos_limit, ts_max);
  1375. }
  1376. }
  1377. pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
  1378. if(pos<0)
  1379. return -1;
  1380. /* do the seek */
  1381. if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
  1382. return ret;
  1383. av_update_cur_dts(s, st, ts);
  1384. return 0;
  1385. }
  1386. int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
  1387. int64_t pos, ts;
  1388. int64_t start_pos, filesize;
  1389. int no_change;
  1390. av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
  1391. if(ts_min == AV_NOPTS_VALUE){
  1392. pos_min = s->data_offset;
  1393. ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  1394. if (ts_min == AV_NOPTS_VALUE)
  1395. return -1;
  1396. }
  1397. if(ts_max == AV_NOPTS_VALUE){
  1398. int step= 1024;
  1399. filesize = avio_size(s->pb);
  1400. pos_max = filesize - 1;
  1401. do{
  1402. pos_max -= step;
  1403. ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
  1404. step += step;
  1405. }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
  1406. if (ts_max == AV_NOPTS_VALUE)
  1407. return -1;
  1408. for(;;){
  1409. int64_t tmp_pos= pos_max + 1;
  1410. int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
  1411. if(tmp_ts == AV_NOPTS_VALUE)
  1412. break;
  1413. ts_max= tmp_ts;
  1414. pos_max= tmp_pos;
  1415. if(tmp_pos >= filesize)
  1416. break;
  1417. }
  1418. pos_limit= pos_max;
  1419. }
  1420. if(ts_min > ts_max){
  1421. return -1;
  1422. }else if(ts_min == ts_max){
  1423. pos_limit= pos_min;
  1424. }
  1425. no_change=0;
  1426. while (pos_min < pos_limit) {
  1427. av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
  1428. pos_min, pos_max, ts_min, ts_max);
  1429. assert(pos_limit <= pos_max);
  1430. if(no_change==0){
  1431. int64_t approximate_keyframe_distance= pos_max - pos_limit;
  1432. // interpolate position (better than dichotomy)
  1433. pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
  1434. + pos_min - approximate_keyframe_distance;
  1435. }else if(no_change==1){
  1436. // bisection, if interpolation failed to change min or max pos last time
  1437. pos = (pos_min + pos_limit)>>1;
  1438. }else{
  1439. /* linear search if bisection failed, can only happen if there
  1440. are very few or no keyframes between min/max */
  1441. pos=pos_min;
  1442. }
  1443. if(pos <= pos_min)
  1444. pos= pos_min + 1;
  1445. else if(pos > pos_limit)
  1446. pos= pos_limit;
  1447. start_pos= pos;
  1448. ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
  1449. if(pos == pos_max)
  1450. no_change++;
  1451. else
  1452. no_change=0;
  1453. av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
  1454. pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
  1455. pos_limit, start_pos, no_change);
  1456. if(ts == AV_NOPTS_VALUE){
  1457. av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
  1458. return -1;
  1459. }
  1460. assert(ts != AV_NOPTS_VALUE);
  1461. if (target_ts <= ts) {
  1462. pos_limit = start_pos - 1;
  1463. pos_max = pos;
  1464. ts_max = ts;
  1465. }
  1466. if (target_ts >= ts) {
  1467. pos_min = pos;
  1468. ts_min = ts;
  1469. }
  1470. }
  1471. pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
  1472. ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
  1473. pos_min = pos;
  1474. ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  1475. pos_min++;
  1476. ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  1477. av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
  1478. pos, ts_min, target_ts, ts_max);
  1479. *ts_ret= ts;
  1480. return pos;
  1481. }
  1482. static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
  1483. int64_t pos_min, pos_max;
  1484. #if 0
  1485. AVStream *st;
  1486. if (stream_index < 0)
  1487. return -1;
  1488. st= s->streams[stream_index];
  1489. #endif
  1490. pos_min = s->data_offset;
  1491. pos_max = avio_size(s->pb) - 1;
  1492. if (pos < pos_min) pos= pos_min;
  1493. else if(pos > pos_max) pos= pos_max;
  1494. avio_seek(s->pb, pos, SEEK_SET);
  1495. #if 0
  1496. av_update_cur_dts(s, st, ts);
  1497. #endif
  1498. return 0;
  1499. }
  1500. static int seek_frame_generic(AVFormatContext *s,
  1501. int stream_index, int64_t timestamp, int flags)
  1502. {
  1503. int index;
  1504. int64_t ret;
  1505. AVStream *st;
  1506. AVIndexEntry *ie;
  1507. st = s->streams[stream_index];
  1508. index = av_index_search_timestamp(st, timestamp, flags);
  1509. if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  1510. return -1;
  1511. if(index < 0 || index==st->nb_index_entries-1){
  1512. int i;
  1513. AVPacket pkt;
  1514. if(st->nb_index_entries){
  1515. assert(st->index_entries);
  1516. ie= &st->index_entries[st->nb_index_entries-1];
  1517. if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
  1518. return ret;
  1519. av_update_cur_dts(s, st, ie->timestamp);
  1520. }else{
  1521. if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
  1522. return ret;
  1523. }
  1524. for(i=0;; i++) {
  1525. int ret;
  1526. do{
  1527. ret = av_read_frame(s, &pkt);
  1528. }while(ret == AVERROR(EAGAIN));
  1529. if(ret<0)
  1530. break;
  1531. av_free_packet(&pkt);
  1532. if(stream_index == pkt.stream_index){
  1533. if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
  1534. break;
  1535. }
  1536. }
  1537. index = av_index_search_timestamp(st, timestamp, flags);
  1538. }
  1539. if (index < 0)
  1540. return -1;
  1541. ff_read_frame_flush(s);
  1542. if (s->iformat->read_seek){
  1543. if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
  1544. return 0;
  1545. }
  1546. ie = &st->index_entries[index];
  1547. if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
  1548. return ret;
  1549. av_update_cur_dts(s, st, ie->timestamp);
  1550. return 0;
  1551. }
  1552. int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1553. {
  1554. int ret;
  1555. AVStream *st;
  1556. ff_read_frame_flush(s);
  1557. if(flags & AVSEEK_FLAG_BYTE)
  1558. return seek_frame_byte(s, stream_index, timestamp, flags);
  1559. if(stream_index < 0){
  1560. stream_index= av_find_default_stream_index(s);
  1561. if(stream_index < 0)
  1562. return -1;
  1563. st= s->streams[stream_index];
  1564. /* timestamp for default must be expressed in AV_TIME_BASE units */
  1565. timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
  1566. }
  1567. /* first, we try the format specific seek */
  1568. if (s->iformat->read_seek)
  1569. ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
  1570. else
  1571. ret = -1;
  1572. if (ret >= 0) {
  1573. return 0;
  1574. }
  1575. if(s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH))
  1576. return av_seek_frame_binary(s, stream_index, timestamp, flags);
  1577. else if (!(s->iformat->flags & AVFMT_NOGENSEARCH))
  1578. return seek_frame_generic(s, stream_index, timestamp, flags);
  1579. else
  1580. return -1;
  1581. }
  1582. int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  1583. {
  1584. if(min_ts > ts || max_ts < ts)
  1585. return -1;
  1586. ff_read_frame_flush(s);
  1587. if (s->iformat->read_seek2)
  1588. return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
  1589. if(s->iformat->read_timestamp){
  1590. //try to seek via read_timestamp()
  1591. }
  1592. //Fallback to old API if new is not implemented but old is
  1593. //Note the old has somewat different sematics
  1594. if(s->iformat->read_seek || 1)
  1595. return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));
  1596. // try some generic seek like seek_frame_generic() but with new ts semantics
  1597. }
  1598. /*******************************************************/
  1599. /**
  1600. * Return TRUE if the stream has accurate duration in any stream.
  1601. *
  1602. * @return TRUE if the stream has accurate duration for at least one component.
  1603. */
  1604. static int has_duration(AVFormatContext *ic)
  1605. {
  1606. int i;
  1607. AVStream *st;
  1608. for(i = 0;i < ic->nb_streams; i++) {
  1609. st = ic->streams[i];
  1610. if (st->duration != AV_NOPTS_VALUE)
  1611. return 1;
  1612. }
  1613. return 0;
  1614. }
  1615. /**
  1616. * Estimate the stream timings from the one of each components.
  1617. *
  1618. * Also computes the global bitrate if possible.
  1619. */
  1620. static void update_stream_timings(AVFormatContext *ic)
  1621. {
  1622. int64_t start_time, start_time1, start_time_text, end_time, end_time1;
  1623. int64_t duration, duration1;
  1624. int i;
  1625. AVStream *st;
  1626. start_time = INT64_MAX;
  1627. start_time_text = INT64_MAX;
  1628. end_time = INT64_MIN;
  1629. duration = INT64_MIN;
  1630. for(i = 0;i < ic->nb_streams; i++) {
  1631. st = ic->streams[i];
  1632. if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
  1633. start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
  1634. if (st->codec->codec_id == CODEC_ID_DVB_TELETEXT) {
  1635. if (start_time1 < start_time_text)
  1636. start_time_text = start_time1;
  1637. } else
  1638. if (start_time1 < start_time)
  1639. start_time = start_time1;
  1640. if (st->duration != AV_NOPTS_VALUE) {
  1641. end_time1 = start_time1
  1642. + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
  1643. if (end_time1 > end_time)
  1644. end_time = end_time1;
  1645. }
  1646. }
  1647. if (st->duration != AV_NOPTS_VALUE) {
  1648. duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
  1649. if (duration1 > duration)
  1650. duration = duration1;
  1651. }
  1652. }
  1653. if (start_time == INT64_MAX || (start_time > start_time_text && start_time - start_time_text < AV_TIME_BASE))
  1654. start_time = start_time_text;
  1655. if (start_time != INT64_MAX) {
  1656. ic->start_time = start_time;
  1657. if (end_time != INT64_MIN) {
  1658. if (end_time - start_time > duration)
  1659. duration = end_time - start_time;
  1660. }
  1661. }
  1662. if (duration != INT64_MIN) {
  1663. ic->duration = duration;
  1664. if (ic->file_size > 0) {
  1665. /* compute the bitrate */
  1666. ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
  1667. (double)ic->duration;
  1668. }
  1669. }
  1670. }
  1671. static void fill_all_stream_timings(AVFormatContext *ic)
  1672. {
  1673. int i;
  1674. AVStream *st;
  1675. update_stream_timings(ic);
  1676. for(i = 0;i < ic->nb_streams; i++) {
  1677. st = ic->streams[i];
  1678. if (st->start_time == AV_NOPTS_VALUE) {
  1679. if(ic->start_time != AV_NOPTS_VALUE)
  1680. st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
  1681. if(ic->duration != AV_NOPTS_VALUE)
  1682. st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
  1683. }
  1684. }
  1685. }
  1686. static void estimate_timings_from_bit_rate(AVFormatContext *ic)
  1687. {
  1688. int64_t filesize, duration;
  1689. int bit_rate, i;
  1690. AVStream *st;
  1691. /* if bit_rate is already set, we believe it */
  1692. if (ic->bit_rate <= 0) {
  1693. bit_rate = 0;
  1694. for(i=0;i<ic->nb_streams;i++) {
  1695. st = ic->streams[i];
  1696. if (st->codec->bit_rate > 0)
  1697. bit_rate += st->codec->bit_rate;
  1698. }
  1699. ic->bit_rate = bit_rate;
  1700. }
  1701. /* if duration is already set, we believe it */
  1702. if (ic->duration == AV_NOPTS_VALUE &&
  1703. ic->bit_rate != 0 &&
  1704. ic->file_size != 0) {
  1705. filesize = ic->file_size;
  1706. if (filesize > 0) {
  1707. for(i = 0; i < ic->nb_streams; i++) {
  1708. st = ic->streams[i];
  1709. duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
  1710. if (st->duration == AV_NOPTS_VALUE)
  1711. st->duration = duration;
  1712. }
  1713. }
  1714. }
  1715. }
  1716. #define DURATION_MAX_READ_SIZE 250000
  1717. #define DURATION_MAX_RETRY 3
  1718. /* only usable for MPEG-PS streams */
  1719. static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
  1720. {
  1721. AVPacket pkt1, *pkt = &pkt1;
  1722. AVStream *st;
  1723. int read_size, i, ret;
  1724. int64_t end_time;
  1725. int64_t filesize, offset, duration;
  1726. int retry=0;
  1727. ic->cur_st = NULL;
  1728. /* flush packet queue */
  1729. flush_packet_queue(ic);
  1730. for (i=0; i<ic->nb_streams; i++) {
  1731. st = ic->streams[i];
  1732. if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
  1733. av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
  1734. if (st->parser) {
  1735. av_parser_close(st->parser);
  1736. st->parser= NULL;
  1737. av_free_packet(&st->cur_pkt);
  1738. }
  1739. }
  1740. /* estimate the end time (duration) */
  1741. /* XXX: may need to support wrapping */
  1742. filesize = ic->file_size;
  1743. end_time = AV_NOPTS_VALUE;
  1744. do{
  1745. offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
  1746. if (offset < 0)
  1747. offset = 0;
  1748. avio_seek(ic->pb, offset, SEEK_SET);
  1749. read_size = 0;
  1750. for(;;) {
  1751. if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
  1752. break;
  1753. do {
  1754. ret = av_read_packet(ic, pkt);
  1755. } while(ret == AVERROR(EAGAIN));
  1756. if (ret != 0)
  1757. break;
  1758. read_size += pkt->size;
  1759. st = ic->streams[pkt->stream_index];
  1760. if (pkt->pts != AV_NOPTS_VALUE &&
  1761. (st->start_time != AV_NOPTS_VALUE ||
  1762. st->first_dts != AV_NOPTS_VALUE)) {
  1763. duration = end_time = pkt->pts;
  1764. if (st->start_time != AV_NOPTS_VALUE)
  1765. duration -= st->start_time;
  1766. else
  1767. duration -= st->first_dts;
  1768. if (duration < 0)
  1769. duration += 1LL<<st->pts_wrap_bits;
  1770. if (duration > 0) {
  1771. if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
  1772. st->duration = duration;
  1773. }
  1774. }
  1775. av_free_packet(pkt);
  1776. }
  1777. }while( end_time==AV_NOPTS_VALUE
  1778. && filesize > (DURATION_MAX_READ_SIZE<<retry)
  1779. && ++retry <= DURATION_MAX_RETRY);
  1780. fill_all_stream_timings(ic);
  1781. avio_seek(ic->pb, old_offset, SEEK_SET);
  1782. for (i=0; i<ic->nb_streams; i++) {
  1783. st= ic->streams[i];
  1784. st->cur_dts= st->first_dts;
  1785. st->last_IP_pts = AV_NOPTS_VALUE;
  1786. st->reference_dts = AV_NOPTS_VALUE;
  1787. }
  1788. }
  1789. static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
  1790. {
  1791. int64_t file_size;
  1792. /* get the file size, if possible */
  1793. if (ic->iformat->flags & AVFMT_NOFILE) {
  1794. file_size = 0;
  1795. } else {
  1796. file_size = avio_size(ic->pb);
  1797. if (file_size < 0)
  1798. file_size = 0;
  1799. }
  1800. ic->file_size = file_size;
  1801. if ((!strcmp(ic->iformat->name, "mpeg") ||
  1802. !strcmp(ic->iformat->name, "mpegts")) &&
  1803. file_size && ic->pb->seekable) {
  1804. /* get accurate estimate from the PTSes */
  1805. estimate_timings_from_pts(ic, old_offset);
  1806. } else if (has_duration(ic)) {
  1807. /* at least one component has timings - we use them for all
  1808. the components */
  1809. fill_all_stream_timings(ic);
  1810. } else {
  1811. av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
  1812. /* less precise: use bitrate info */
  1813. estimate_timings_from_bit_rate(ic);
  1814. }
  1815. update_stream_timings(ic);
  1816. {
  1817. int i;
  1818. AVStream av_unused *st;
  1819. for(i = 0;i < ic->nb_streams; i++) {
  1820. st = ic->streams[i];
  1821. av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
  1822. (double) st->start_time / AV_TIME_BASE,
  1823. (double) st->duration / AV_TIME_BASE);
  1824. }
  1825. av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
  1826. (double) ic->start_time / AV_TIME_BASE,
  1827. (double) ic->duration / AV_TIME_BASE,
  1828. ic->bit_rate / 1000);
  1829. }
  1830. }
  1831. static int has_codec_parameters(AVCodecContext *avctx)
  1832. {
  1833. int val;
  1834. switch (avctx->codec_type) {
  1835. case AVMEDIA_TYPE_AUDIO:
  1836. val = avctx->sample_rate && avctx->channels && avctx->sample_fmt != AV_SAMPLE_FMT_NONE;
  1837. if(!avctx->frame_size &&
  1838. (avctx->codec_id == CODEC_ID_VORBIS ||
  1839. avctx->codec_id == CODEC_ID_AAC ||
  1840. avctx->codec_id == CODEC_ID_MP1 ||
  1841. avctx->codec_id == CODEC_ID_MP2 ||
  1842. avctx->codec_id == CODEC_ID_MP3 ||
  1843. avctx->codec_id == CODEC_ID_SPEEX ||
  1844. avctx->codec_id == CODEC_ID_CELT))
  1845. return 0;
  1846. break;
  1847. case AVMEDIA_TYPE_VIDEO:
  1848. val = avctx->width && avctx->pix_fmt != PIX_FMT_NONE;
  1849. break;
  1850. case AVMEDIA_TYPE_DATA:
  1851. if(avctx->codec_id == CODEC_ID_NONE) return 1;
  1852. default:
  1853. val = 1;
  1854. break;
  1855. }
  1856. return avctx->codec_id != CODEC_ID_NONE && val != 0;
  1857. }
  1858. static int has_decode_delay_been_guessed(AVStream *st)
  1859. {
  1860. return st->codec->codec_id != CODEC_ID_H264 ||
  1861. st->codec_info_nb_frames >= 6 + st->codec->has_b_frames;
  1862. }
  1863. static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
  1864. {
  1865. int16_t *samples;
  1866. AVCodec *codec;
  1867. int got_picture, data_size, ret=0;
  1868. AVFrame picture;
  1869. if(!st->codec->codec){
  1870. codec = avcodec_find_decoder(st->codec->codec_id);
  1871. if (!codec)
  1872. return -1;
  1873. ret = avcodec_open2(st->codec, codec, options);
  1874. if (ret < 0)
  1875. return ret;
  1876. }
  1877. if(!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st) ||
  1878. (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF)) {
  1879. switch(st->codec->codec_type) {
  1880. case AVMEDIA_TYPE_VIDEO:
  1881. avcodec_get_frame_defaults(&picture);
  1882. ret = avcodec_decode_video2(st->codec, &picture,
  1883. &got_picture, avpkt);
  1884. break;
  1885. case AVMEDIA_TYPE_AUDIO:
  1886. data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
  1887. samples = av_malloc(data_size);
  1888. if (!samples)
  1889. goto fail;
  1890. ret = avcodec_decode_audio3(st->codec, samples,
  1891. &data_size, avpkt);
  1892. av_free(samples);
  1893. break;
  1894. default:
  1895. break;
  1896. }
  1897. }
  1898. fail:
  1899. return ret;
  1900. }
  1901. unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
  1902. {
  1903. while (tags->id != CODEC_ID_NONE) {
  1904. if (tags->id == id)
  1905. return tags->tag;
  1906. tags++;
  1907. }
  1908. return 0;
  1909. }
  1910. enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
  1911. {
  1912. int i;
  1913. for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
  1914. if(tag == tags[i].tag)
  1915. return tags[i].id;
  1916. }
  1917. for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
  1918. if (ff_toupper4(tag) == ff_toupper4(tags[i].tag))
  1919. return tags[i].id;
  1920. }
  1921. return CODEC_ID_NONE;
  1922. }
  1923. unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
  1924. {
  1925. int i;
  1926. for(i=0; tags && tags[i]; i++){
  1927. int tag= ff_codec_get_tag(tags[i], id);
  1928. if(tag) return tag;
  1929. }
  1930. return 0;
  1931. }
  1932. enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
  1933. {
  1934. int i;
  1935. for(i=0; tags && tags[i]; i++){
  1936. enum CodecID id= ff_codec_get_id(tags[i], tag);
  1937. if(id!=CODEC_ID_NONE) return id;
  1938. }
  1939. return CODEC_ID_NONE;
  1940. }
  1941. static void compute_chapters_end(AVFormatContext *s)
  1942. {
  1943. unsigned int i, j;
  1944. int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
  1945. for (i = 0; i < s->nb_chapters; i++)
  1946. if (s->chapters[i]->end == AV_NOPTS_VALUE) {
  1947. AVChapter *ch = s->chapters[i];
  1948. int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
  1949. : INT64_MAX;
  1950. for (j = 0; j < s->nb_chapters; j++) {
  1951. AVChapter *ch1 = s->chapters[j];
  1952. int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
  1953. if (j != i && next_start > ch->start && next_start < end)
  1954. end = next_start;
  1955. }
  1956. ch->end = (end == INT64_MAX) ? ch->start : end;
  1957. }
  1958. }
  1959. static int get_std_framerate(int i){
  1960. if(i<60*12) return i*1001;
  1961. else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
  1962. }
  1963. /*
  1964. * Is the time base unreliable.
  1965. * This is a heuristic to balance between quick acceptance of the values in
  1966. * the headers vs. some extra checks.
  1967. * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
  1968. * MPEG-2 commonly misuses field repeat flags to store different framerates.
  1969. * And there are "variable" fps files this needs to detect as well.
  1970. */
  1971. static int tb_unreliable(AVCodecContext *c){
  1972. if( c->time_base.den >= 101L*c->time_base.num
  1973. || c->time_base.den < 5L*c->time_base.num
  1974. /* || c->codec_tag == AV_RL32("DIVX")
  1975. || c->codec_tag == AV_RL32("XVID")*/
  1976. || c->codec_id == CODEC_ID_MPEG2VIDEO
  1977. || c->codec_id == CODEC_ID_H264
  1978. )
  1979. return 1;
  1980. return 0;
  1981. }
  1982. #if FF_API_FORMAT_PARAMETERS
  1983. int av_find_stream_info(AVFormatContext *ic)
  1984. {
  1985. return avformat_find_stream_info(ic, NULL);
  1986. }
  1987. #endif
  1988. int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
  1989. {
  1990. int i, count, ret, read_size, j;
  1991. AVStream *st;
  1992. AVPacket pkt1, *pkt;
  1993. int64_t old_offset = avio_tell(ic->pb);
  1994. int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
  1995. for(i=0;i<ic->nb_streams;i++) {
  1996. AVCodec *codec;
  1997. st = ic->streams[i];
  1998. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size) {
  1999. // We need to discard these since they can be plain wrong for
  2000. // backwards compatible HE-AAC signaling.
  2001. // But when we have no extradata we need to keep them or we can't
  2002. // play anything at all.
  2003. st->codec->sample_rate = 0;
  2004. st->codec->frame_size = 0;
  2005. st->codec->channels = 0;
  2006. }
  2007. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  2008. st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2009. /* if(!st->time_base.num)
  2010. st->time_base= */
  2011. if(!st->codec->time_base.num)
  2012. st->codec->time_base= st->time_base;
  2013. }
  2014. //only for the split stuff
  2015. if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
  2016. st->parser = av_parser_init(st->codec->codec_id);
  2017. if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
  2018. st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
  2019. }
  2020. }
  2021. assert(!st->codec->codec);
  2022. codec = avcodec_find_decoder(st->codec->codec_id);
  2023. /* Ensure that subtitle_header is properly set. */
  2024. if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
  2025. && codec && !st->codec->codec)
  2026. avcodec_open2(st->codec, codec, options ? &options[i] : NULL);
  2027. //try to just open decoders, in case this is enough to get parameters
  2028. if(!has_codec_parameters(st->codec)){
  2029. if (codec && !st->codec->codec)
  2030. avcodec_open2(st->codec, codec, options ? &options[i] : NULL);
  2031. }
  2032. }
  2033. for (i=0; i<ic->nb_streams; i++) {
  2034. ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
  2035. }
  2036. count = 0;
  2037. read_size = 0;
  2038. for(;;) {
  2039. if(url_interrupt_cb()){
  2040. ret= AVERROR_EXIT;
  2041. av_log(ic, AV_LOG_DEBUG, "interrupted\n");
  2042. break;
  2043. }
  2044. /* check if one codec still needs to be handled */
  2045. for(i=0;i<ic->nb_streams;i++) {
  2046. int fps_analyze_framecount = 20;
  2047. st = ic->streams[i];
  2048. if (!has_codec_parameters(st->codec))
  2049. break;
  2050. /* if the timebase is coarse (like the usual millisecond precision
  2051. of mkv), we need to analyze more frames to reliably arrive at
  2052. the correct fps */
  2053. if (av_q2d(st->time_base) > 0.0005)
  2054. fps_analyze_framecount *= 2;
  2055. if (ic->fps_probe_size >= 0)
  2056. fps_analyze_framecount = ic->fps_probe_size;
  2057. /* variable fps and no guess at the real fps */
  2058. if( tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
  2059. && st->info->duration_count < fps_analyze_framecount
  2060. && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  2061. break;
  2062. if(st->parser && st->parser->parser->split && !st->codec->extradata)
  2063. break;
  2064. if(st->first_dts == AV_NOPTS_VALUE)
  2065. break;
  2066. }
  2067. if (i == ic->nb_streams) {
  2068. /* NOTE: if the format has no header, then we need to read
  2069. some packets to get most of the streams, so we cannot
  2070. stop here */
  2071. if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
  2072. /* if we found the info for all the codecs, we can stop */
  2073. ret = count;
  2074. av_log(ic, AV_LOG_DEBUG, "All info found\n");
  2075. break;
  2076. }
  2077. }
  2078. /* we did not get all the codec info, but we read too much data */
  2079. if (read_size >= ic->probesize) {
  2080. ret = count;
  2081. av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
  2082. break;
  2083. }
  2084. /* NOTE: a new stream can be added there if no header in file
  2085. (AVFMTCTX_NOHEADER) */
  2086. ret = read_frame_internal(ic, &pkt1);
  2087. if (ret == AVERROR(EAGAIN))
  2088. continue;
  2089. if (ret < 0) {
  2090. /* EOF or error */
  2091. ret = -1; /* we could not have all the codec parameters before EOF */
  2092. for(i=0;i<ic->nb_streams;i++) {
  2093. st = ic->streams[i];
  2094. if (!has_codec_parameters(st->codec)){
  2095. char buf[256];
  2096. avcodec_string(buf, sizeof(buf), st->codec, 0);
  2097. av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
  2098. } else {
  2099. ret = 0;
  2100. }
  2101. }
  2102. break;
  2103. }
  2104. pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
  2105. if ((ret = av_dup_packet(pkt)) < 0)
  2106. goto find_stream_info_err;
  2107. read_size += pkt->size;
  2108. st = ic->streams[pkt->stream_index];
  2109. if (st->codec_info_nb_frames>1) {
  2110. int64_t t;
  2111. if (st->time_base.den > 0 && (t=av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q)) >= ic->max_analyze_duration) {
  2112. av_log(ic, AV_LOG_WARNING, "max_analyze_duration %d reached at %"PRId64"\n", ic->max_analyze_duration, t);
  2113. break;
  2114. }
  2115. st->info->codec_info_duration += pkt->duration;
  2116. }
  2117. {
  2118. int64_t last = st->info->last_dts;
  2119. int64_t duration= pkt->dts - last;
  2120. if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
  2121. double dur= duration * av_q2d(st->time_base);
  2122. // if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  2123. // av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
  2124. if (st->info->duration_count < 2)
  2125. memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
  2126. for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
  2127. int framerate= get_std_framerate(i);
  2128. int ticks= lrintf(dur*framerate/(1001*12));
  2129. double error= dur - ticks*1001*12/(double)framerate;
  2130. st->info->duration_error[i] += error*error;
  2131. }
  2132. st->info->duration_count++;
  2133. // ignore the first 4 values, they might have some random jitter
  2134. if (st->info->duration_count > 3)
  2135. st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
  2136. }
  2137. if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
  2138. st->info->last_dts = pkt->dts;
  2139. }
  2140. if(st->parser && st->parser->parser->split && !st->codec->extradata){
  2141. int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
  2142. if(i){
  2143. st->codec->extradata_size= i;
  2144. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  2145. memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
  2146. memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  2147. }
  2148. }
  2149. /* if still no information, we try to open the codec and to
  2150. decompress the frame. We try to avoid that in most cases as
  2151. it takes longer and uses more memory. For MPEG-4, we need to
  2152. decompress for QuickTime.
  2153. If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
  2154. least one frame of codec data, this makes sure the codec initializes
  2155. the channel configuration and does not only trust the values from the container.
  2156. */
  2157. try_decode_frame(st, pkt, (options && i < orig_nb_streams )? &options[i] : NULL);
  2158. st->codec_info_nb_frames++;
  2159. count++;
  2160. }
  2161. // close codecs which were opened in try_decode_frame()
  2162. for(i=0;i<ic->nb_streams;i++) {
  2163. st = ic->streams[i];
  2164. if(st->codec->codec)
  2165. avcodec_close(st->codec);
  2166. }
  2167. for(i=0;i<ic->nb_streams;i++) {
  2168. st = ic->streams[i];
  2169. if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
  2170. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  2171. (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
  2172. st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
  2173. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2174. if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample){
  2175. uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  2176. if(ff_find_pix_fmt(ff_raw_pix_fmt_tags, tag) == st->codec->pix_fmt)
  2177. st->codec->codec_tag= tag;
  2178. }
  2179. // the check for tb_unreliable() is not completely correct, since this is not about handling
  2180. // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
  2181. // ipmovie.c produces.
  2182. if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num)
  2183. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);
  2184. if (st->info->duration_count && !st->r_frame_rate.num
  2185. && tb_unreliable(st->codec) /*&&
  2186. //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
  2187. st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
  2188. int num = 0;
  2189. double best_error= 2*av_q2d(st->time_base);
  2190. best_error = best_error*best_error*st->info->duration_count*1000*12*30;
  2191. for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
  2192. double error = st->info->duration_error[j] * get_std_framerate(j);
  2193. // if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  2194. // av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
  2195. if(error < best_error){
  2196. best_error= error;
  2197. num = get_std_framerate(j);
  2198. }
  2199. }
  2200. // do not increase frame rate by more than 1 % in order to match a standard rate.
  2201. if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
  2202. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
  2203. }
  2204. if (!st->r_frame_rate.num){
  2205. if( st->codec->time_base.den * (int64_t)st->time_base.num
  2206. <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
  2207. st->r_frame_rate.num = st->codec->time_base.den;
  2208. st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
  2209. }else{
  2210. st->r_frame_rate.num = st->time_base.den;
  2211. st->r_frame_rate.den = st->time_base.num;
  2212. }
  2213. }
  2214. }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  2215. if(!st->codec->bits_per_coded_sample)
  2216. st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
  2217. // set stream disposition based on audio service type
  2218. switch (st->codec->audio_service_type) {
  2219. case AV_AUDIO_SERVICE_TYPE_EFFECTS:
  2220. st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
  2221. case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
  2222. st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
  2223. case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
  2224. st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
  2225. case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
  2226. st->disposition = AV_DISPOSITION_COMMENT; break;
  2227. case AV_AUDIO_SERVICE_TYPE_KARAOKE:
  2228. st->disposition = AV_DISPOSITION_KARAOKE; break;
  2229. }
  2230. }
  2231. }
  2232. estimate_timings(ic, old_offset);
  2233. compute_chapters_end(ic);
  2234. #if 0
  2235. /* correct DTS for B-frame streams with no timestamps */
  2236. for(i=0;i<ic->nb_streams;i++) {
  2237. st = ic->streams[i];
  2238. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2239. if(b-frames){
  2240. ppktl = &ic->packet_buffer;
  2241. while(ppkt1){
  2242. if(ppkt1->stream_index != i)
  2243. continue;
  2244. if(ppkt1->pkt->dts < 0)
  2245. break;
  2246. if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
  2247. break;
  2248. ppkt1->pkt->dts -= delta;
  2249. ppkt1= ppkt1->next;
  2250. }
  2251. if(ppkt1)
  2252. continue;
  2253. st->cur_dts -= delta;
  2254. }
  2255. }
  2256. }
  2257. #endif
  2258. find_stream_info_err:
  2259. for (i=0; i < ic->nb_streams; i++)
  2260. av_freep(&ic->streams[i]->info);
  2261. return ret;
  2262. }
  2263. AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
  2264. {
  2265. int i, j;
  2266. for (i = 0; i < ic->nb_programs; i++) {
  2267. if (ic->programs[i] == last) {
  2268. last = NULL;
  2269. } else {
  2270. if (!last)
  2271. for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
  2272. if (ic->programs[i]->stream_index[j] == s)
  2273. return ic->programs[i];
  2274. }
  2275. }
  2276. return NULL;
  2277. }
  2278. int av_find_best_stream(AVFormatContext *ic,
  2279. enum AVMediaType type,
  2280. int wanted_stream_nb,
  2281. int related_stream,
  2282. AVCodec **decoder_ret,
  2283. int flags)
  2284. {
  2285. int i, nb_streams = ic->nb_streams;
  2286. int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
  2287. unsigned *program = NULL;
  2288. AVCodec *decoder = NULL, *best_decoder = NULL;
  2289. if (related_stream >= 0 && wanted_stream_nb < 0) {
  2290. AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
  2291. if (p) {
  2292. program = p->stream_index;
  2293. nb_streams = p->nb_stream_indexes;
  2294. }
  2295. }
  2296. for (i = 0; i < nb_streams; i++) {
  2297. int real_stream_index = program ? program[i] : i;
  2298. AVStream *st = ic->streams[real_stream_index];
  2299. AVCodecContext *avctx = st->codec;
  2300. if (avctx->codec_type != type)
  2301. continue;
  2302. if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
  2303. continue;
  2304. if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
  2305. continue;
  2306. if (decoder_ret) {
  2307. decoder = avcodec_find_decoder(st->codec->codec_id);
  2308. if (!decoder) {
  2309. if (ret < 0)
  2310. ret = AVERROR_DECODER_NOT_FOUND;
  2311. continue;
  2312. }
  2313. }
  2314. if (best_count >= st->codec_info_nb_frames)
  2315. continue;
  2316. best_count = st->codec_info_nb_frames;
  2317. ret = real_stream_index;
  2318. best_decoder = decoder;
  2319. if (program && i == nb_streams - 1 && ret < 0) {
  2320. program = NULL;
  2321. nb_streams = ic->nb_streams;
  2322. i = 0; /* no related stream found, try again with everything */
  2323. }
  2324. }
  2325. if (decoder_ret)
  2326. *decoder_ret = best_decoder;
  2327. return ret;
  2328. }
  2329. /*******************************************************/
  2330. int av_read_play(AVFormatContext *s)
  2331. {
  2332. if (s->iformat->read_play)
  2333. return s->iformat->read_play(s);
  2334. if (s->pb)
  2335. return avio_pause(s->pb, 0);
  2336. return AVERROR(ENOSYS);
  2337. }
  2338. int av_read_pause(AVFormatContext *s)
  2339. {
  2340. if (s->iformat->read_pause)
  2341. return s->iformat->read_pause(s);
  2342. if (s->pb)
  2343. return avio_pause(s->pb, 1);
  2344. return AVERROR(ENOSYS);
  2345. }
  2346. void av_close_input_stream(AVFormatContext *s)
  2347. {
  2348. flush_packet_queue(s);
  2349. if (s->iformat->read_close)
  2350. s->iformat->read_close(s);
  2351. avformat_free_context(s);
  2352. }
  2353. void avformat_free_context(AVFormatContext *s)
  2354. {
  2355. int i;
  2356. AVStream *st;
  2357. av_opt_free(s);
  2358. if (s->iformat && s->iformat->priv_class && s->priv_data)
  2359. av_opt_free(s->priv_data);
  2360. for(i=0;i<s->nb_streams;i++) {
  2361. /* free all data in a stream component */
  2362. st = s->streams[i];
  2363. if (st->parser) {
  2364. av_parser_close(st->parser);
  2365. av_free_packet(&st->cur_pkt);
  2366. }
  2367. av_dict_free(&st->metadata);
  2368. av_free(st->index_entries);
  2369. av_free(st->codec->extradata);
  2370. av_free(st->codec->subtitle_header);
  2371. av_free(st->codec);
  2372. av_free(st->priv_data);
  2373. av_free(st->info);
  2374. av_free(st);
  2375. }
  2376. for(i=s->nb_programs-1; i>=0; i--) {
  2377. av_dict_free(&s->programs[i]->metadata);
  2378. av_freep(&s->programs[i]->stream_index);
  2379. av_freep(&s->programs[i]);
  2380. }
  2381. av_freep(&s->programs);
  2382. av_freep(&s->priv_data);
  2383. while(s->nb_chapters--) {
  2384. av_dict_free(&s->chapters[s->nb_chapters]->metadata);
  2385. av_free(s->chapters[s->nb_chapters]);
  2386. }
  2387. av_freep(&s->chapters);
  2388. av_dict_free(&s->metadata);
  2389. av_freep(&s->streams);
  2390. av_free(s);
  2391. }
  2392. void av_close_input_file(AVFormatContext *s)
  2393. {
  2394. AVIOContext *pb = (s->iformat->flags & AVFMT_NOFILE) || (s->flags & AVFMT_FLAG_CUSTOM_IO) ?
  2395. NULL : s->pb;
  2396. av_close_input_stream(s);
  2397. if (pb)
  2398. avio_close(pb);
  2399. }
  2400. AVStream *av_new_stream(AVFormatContext *s, int id)
  2401. {
  2402. AVStream *st;
  2403. int i;
  2404. AVStream **streams;
  2405. if (s->nb_streams >= INT_MAX/sizeof(*streams))
  2406. return NULL;
  2407. streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
  2408. if (!streams)
  2409. return NULL;
  2410. s->streams = streams;
  2411. st = av_mallocz(sizeof(AVStream));
  2412. if (!st)
  2413. return NULL;
  2414. if (!(st->info = av_mallocz(sizeof(*st->info)))) {
  2415. av_free(st);
  2416. return NULL;
  2417. }
  2418. st->codec = avcodec_alloc_context3(NULL);
  2419. if (s->iformat) {
  2420. /* no default bitrate if decoding */
  2421. st->codec->bit_rate = 0;
  2422. }
  2423. st->index = s->nb_streams;
  2424. st->id = id;
  2425. st->start_time = AV_NOPTS_VALUE;
  2426. st->duration = AV_NOPTS_VALUE;
  2427. /* we set the current DTS to 0 so that formats without any timestamps
  2428. but durations get some timestamps, formats with some unknown
  2429. timestamps have their first few packets buffered and the
  2430. timestamps corrected before they are returned to the user */
  2431. st->cur_dts = 0;
  2432. st->first_dts = AV_NOPTS_VALUE;
  2433. st->probe_packets = MAX_PROBE_PACKETS;
  2434. /* default pts setting is MPEG-like */
  2435. av_set_pts_info(st, 33, 1, 90000);
  2436. st->last_IP_pts = AV_NOPTS_VALUE;
  2437. for(i=0; i<MAX_REORDER_DELAY+1; i++)
  2438. st->pts_buffer[i]= AV_NOPTS_VALUE;
  2439. st->reference_dts = AV_NOPTS_VALUE;
  2440. st->sample_aspect_ratio = (AVRational){0,1};
  2441. s->streams[s->nb_streams++] = st;
  2442. return st;
  2443. }
  2444. AVProgram *av_new_program(AVFormatContext *ac, int id)
  2445. {
  2446. AVProgram *program=NULL;
  2447. int i;
  2448. av_dlog(ac, "new_program: id=0x%04x\n", id);
  2449. for(i=0; i<ac->nb_programs; i++)
  2450. if(ac->programs[i]->id == id)
  2451. program = ac->programs[i];
  2452. if(!program){
  2453. program = av_mallocz(sizeof(AVProgram));
  2454. if (!program)
  2455. return NULL;
  2456. dynarray_add(&ac->programs, &ac->nb_programs, program);
  2457. program->discard = AVDISCARD_NONE;
  2458. }
  2459. program->id = id;
  2460. return program;
  2461. }
  2462. AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
  2463. {
  2464. AVChapter *chapter = NULL;
  2465. int i;
  2466. for(i=0; i<s->nb_chapters; i++)
  2467. if(s->chapters[i]->id == id)
  2468. chapter = s->chapters[i];
  2469. if(!chapter){
  2470. chapter= av_mallocz(sizeof(AVChapter));
  2471. if(!chapter)
  2472. return NULL;
  2473. dynarray_add(&s->chapters, &s->nb_chapters, chapter);
  2474. }
  2475. av_dict_set(&chapter->metadata, "title", title, 0);
  2476. chapter->id = id;
  2477. chapter->time_base= time_base;
  2478. chapter->start = start;
  2479. chapter->end = end;
  2480. return chapter;
  2481. }
  2482. /************************************************************/
  2483. /* output media file */
  2484. #if FF_API_FORMAT_PARAMETERS
  2485. int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
  2486. {
  2487. if (s->oformat->priv_data_size > 0) {
  2488. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  2489. if (!s->priv_data)
  2490. return AVERROR(ENOMEM);
  2491. if (s->oformat->priv_class) {
  2492. *(const AVClass**)s->priv_data= s->oformat->priv_class;
  2493. av_opt_set_defaults(s->priv_data);
  2494. }
  2495. } else
  2496. s->priv_data = NULL;
  2497. return 0;
  2498. }
  2499. #endif
  2500. int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
  2501. const char *format, const char *filename)
  2502. {
  2503. AVFormatContext *s = avformat_alloc_context();
  2504. int ret = 0;
  2505. *avctx = NULL;
  2506. if (!s)
  2507. goto nomem;
  2508. if (!oformat) {
  2509. if (format) {
  2510. oformat = av_guess_format(format, NULL, NULL);
  2511. if (!oformat) {
  2512. av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
  2513. ret = AVERROR(EINVAL);
  2514. goto error;
  2515. }
  2516. } else {
  2517. oformat = av_guess_format(NULL, filename, NULL);
  2518. if (!oformat) {
  2519. ret = AVERROR(EINVAL);
  2520. av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
  2521. filename);
  2522. goto error;
  2523. }
  2524. }
  2525. }
  2526. s->oformat = oformat;
  2527. if (s->oformat->priv_data_size > 0) {
  2528. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  2529. if (!s->priv_data)
  2530. goto nomem;
  2531. if (s->oformat->priv_class) {
  2532. *(const AVClass**)s->priv_data= s->oformat->priv_class;
  2533. av_opt_set_defaults(s->priv_data);
  2534. }
  2535. } else
  2536. s->priv_data = NULL;
  2537. if (filename)
  2538. av_strlcpy(s->filename, filename, sizeof(s->filename));
  2539. *avctx = s;
  2540. return 0;
  2541. nomem:
  2542. av_log(s, AV_LOG_ERROR, "Out of memory\n");
  2543. ret = AVERROR(ENOMEM);
  2544. error:
  2545. avformat_free_context(s);
  2546. return ret;
  2547. }
  2548. #if FF_API_ALLOC_OUTPUT_CONTEXT
  2549. AVFormatContext *avformat_alloc_output_context(const char *format,
  2550. AVOutputFormat *oformat, const char *filename)
  2551. {
  2552. AVFormatContext *avctx;
  2553. int ret = avformat_alloc_output_context2(&avctx, oformat, format, filename);
  2554. return ret < 0 ? NULL : avctx;
  2555. }
  2556. #endif
  2557. static int validate_codec_tag(AVFormatContext *s, AVStream *st)
  2558. {
  2559. const AVCodecTag *avctag;
  2560. int n;
  2561. enum CodecID id = CODEC_ID_NONE;
  2562. unsigned int tag = 0;
  2563. /**
  2564. * Check that tag + id is in the table
  2565. * If neither is in the table -> OK
  2566. * If tag is in the table with another id -> FAIL
  2567. * If id is in the table with another tag -> FAIL unless strict < normal
  2568. */
  2569. for (n = 0; s->oformat->codec_tag[n]; n++) {
  2570. avctag = s->oformat->codec_tag[n];
  2571. while (avctag->id != CODEC_ID_NONE) {
  2572. if (ff_toupper4(avctag->tag) == ff_toupper4(st->codec->codec_tag)) {
  2573. id = avctag->id;
  2574. if (id == st->codec->codec_id)
  2575. return 1;
  2576. }
  2577. if (avctag->id == st->codec->codec_id)
  2578. tag = avctag->tag;
  2579. avctag++;
  2580. }
  2581. }
  2582. if (id != CODEC_ID_NONE)
  2583. return 0;
  2584. if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
  2585. return 0;
  2586. return 1;
  2587. }
  2588. #if FF_API_FORMAT_PARAMETERS
  2589. int av_write_header(AVFormatContext *s)
  2590. {
  2591. return avformat_write_header(s, NULL);
  2592. }
  2593. #endif
  2594. int avformat_write_header(AVFormatContext *s, AVDictionary **options)
  2595. {
  2596. int ret = 0, i;
  2597. AVStream *st;
  2598. AVDictionary *tmp = NULL;
  2599. if (options)
  2600. av_dict_copy(&tmp, *options, 0);
  2601. if ((ret = av_opt_set_dict(s, &tmp)) < 0)
  2602. goto fail;
  2603. if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
  2604. (ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  2605. goto fail;
  2606. // some sanity checks
  2607. if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
  2608. av_log(s, AV_LOG_ERROR, "no streams\n");
  2609. ret = AVERROR(EINVAL);
  2610. goto fail;
  2611. }
  2612. for(i=0;i<s->nb_streams;i++) {
  2613. st = s->streams[i];
  2614. switch (st->codec->codec_type) {
  2615. case AVMEDIA_TYPE_AUDIO:
  2616. if(st->codec->sample_rate<=0){
  2617. av_log(s, AV_LOG_ERROR, "sample rate not set\n");
  2618. ret = AVERROR(EINVAL);
  2619. goto fail;
  2620. }
  2621. if(!st->codec->block_align)
  2622. st->codec->block_align = st->codec->channels *
  2623. av_get_bits_per_sample(st->codec->codec_id) >> 3;
  2624. break;
  2625. case AVMEDIA_TYPE_VIDEO:
  2626. if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
  2627. av_log(s, AV_LOG_ERROR, "time base not set\n");
  2628. ret = AVERROR(EINVAL);
  2629. goto fail;
  2630. }
  2631. if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
  2632. av_log(s, AV_LOG_ERROR, "dimensions not set\n");
  2633. ret = AVERROR(EINVAL);
  2634. goto fail;
  2635. }
  2636. if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
  2637. av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
  2638. ret = AVERROR(EINVAL);
  2639. goto fail;
  2640. }
  2641. break;
  2642. }
  2643. if(s->oformat->codec_tag){
  2644. if(st->codec->codec_tag && st->codec->codec_id == CODEC_ID_RAWVIDEO && av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id) == 0 && !validate_codec_tag(s, st)){
  2645. //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
  2646. st->codec->codec_tag= 0;
  2647. }
  2648. if(st->codec->codec_tag){
  2649. if (!validate_codec_tag(s, st)) {
  2650. char tagbuf[32];
  2651. av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
  2652. av_log(s, AV_LOG_ERROR,
  2653. "Tag %s/0x%08x incompatible with output codec id '%d'\n",
  2654. tagbuf, st->codec->codec_tag, st->codec->codec_id);
  2655. ret = AVERROR_INVALIDDATA;
  2656. goto fail;
  2657. }
  2658. }else
  2659. st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
  2660. }
  2661. if(s->oformat->flags & AVFMT_GLOBALHEADER &&
  2662. !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
  2663. av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
  2664. }
  2665. if (!s->priv_data && s->oformat->priv_data_size > 0) {
  2666. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  2667. if (!s->priv_data) {
  2668. ret = AVERROR(ENOMEM);
  2669. goto fail;
  2670. }
  2671. if (s->oformat->priv_class) {
  2672. *(const AVClass**)s->priv_data= s->oformat->priv_class;
  2673. av_opt_set_defaults(s->priv_data);
  2674. if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  2675. goto fail;
  2676. }
  2677. }
  2678. /* set muxer identification string */
  2679. if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  2680. av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
  2681. }
  2682. if(s->oformat->write_header){
  2683. ret = s->oformat->write_header(s);
  2684. if (ret < 0)
  2685. goto fail;
  2686. }
  2687. /* init PTS generation */
  2688. for(i=0;i<s->nb_streams;i++) {
  2689. int64_t den = AV_NOPTS_VALUE;
  2690. st = s->streams[i];
  2691. switch (st->codec->codec_type) {
  2692. case AVMEDIA_TYPE_AUDIO:
  2693. den = (int64_t)st->time_base.num * st->codec->sample_rate;
  2694. break;
  2695. case AVMEDIA_TYPE_VIDEO:
  2696. den = (int64_t)st->time_base.num * st->codec->time_base.den;
  2697. break;
  2698. default:
  2699. break;
  2700. }
  2701. if (den != AV_NOPTS_VALUE) {
  2702. if (den <= 0) {
  2703. ret = AVERROR_INVALIDDATA;
  2704. goto fail;
  2705. }
  2706. frac_init(&st->pts, 0, 0, den);
  2707. }
  2708. }
  2709. if (options) {
  2710. av_dict_free(options);
  2711. *options = tmp;
  2712. }
  2713. return 0;
  2714. fail:
  2715. av_dict_free(&tmp);
  2716. return ret;
  2717. }
  2718. //FIXME merge with compute_pkt_fields
  2719. static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
  2720. int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
  2721. int num, den, frame_size, i;
  2722. av_dlog(s, "compute_pkt_fields2: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n",
  2723. pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
  2724. /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
  2725. return AVERROR(EINVAL);*/
  2726. /* duration field */
  2727. if (pkt->duration == 0) {
  2728. compute_frame_duration(&num, &den, st, NULL, pkt);
  2729. if (den && num) {
  2730. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  2731. }
  2732. }
  2733. if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
  2734. pkt->pts= pkt->dts;
  2735. //XXX/FIXME this is a temporary hack until all encoders output pts
  2736. if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
  2737. pkt->dts=
  2738. // pkt->pts= st->cur_dts;
  2739. pkt->pts= st->pts.val;
  2740. }
  2741. //calculate dts from pts
  2742. if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
  2743. st->pts_buffer[0]= pkt->pts;
  2744. for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  2745. st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
  2746. for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
  2747. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
  2748. pkt->dts= st->pts_buffer[0];
  2749. }
  2750. if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)){
  2751. av_log(s, AV_LOG_ERROR,
  2752. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",
  2753. st->index, st->cur_dts, pkt->dts);
  2754. return AVERROR(EINVAL);
  2755. }
  2756. if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
  2757. av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
  2758. return AVERROR(EINVAL);
  2759. }
  2760. // av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
  2761. st->cur_dts= pkt->dts;
  2762. st->pts.val= pkt->dts;
  2763. /* update pts */
  2764. switch (st->codec->codec_type) {
  2765. case AVMEDIA_TYPE_AUDIO:
  2766. frame_size = get_audio_frame_size(st->codec, pkt->size);
  2767. /* HACK/FIXME, we skip the initial 0 size packets as they are most
  2768. likely equal to the encoder delay, but it would be better if we
  2769. had the real timestamps from the encoder */
  2770. if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
  2771. frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
  2772. }
  2773. break;
  2774. case AVMEDIA_TYPE_VIDEO:
  2775. frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
  2776. break;
  2777. default:
  2778. break;
  2779. }
  2780. return 0;
  2781. }
  2782. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  2783. {
  2784. int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
  2785. if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  2786. return ret;
  2787. ret= s->oformat->write_packet(s, pkt);
  2788. if (ret >= 0)
  2789. s->streams[pkt->stream_index]->nb_frames++;
  2790. return ret;
  2791. }
  2792. void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  2793. int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
  2794. {
  2795. AVPacketList **next_point, *this_pktl;
  2796. this_pktl = av_mallocz(sizeof(AVPacketList));
  2797. this_pktl->pkt= *pkt;
  2798. pkt->destruct= NULL; // do not free original but only the copy
  2799. av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
  2800. if(s->streams[pkt->stream_index]->last_in_packet_buffer){
  2801. next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
  2802. }else
  2803. next_point = &s->packet_buffer;
  2804. if(*next_point){
  2805. if(compare(s, &s->packet_buffer_end->pkt, pkt)){
  2806. while(!compare(s, &(*next_point)->pkt, pkt)){
  2807. next_point= &(*next_point)->next;
  2808. }
  2809. goto next_non_null;
  2810. }else{
  2811. next_point = &(s->packet_buffer_end->next);
  2812. }
  2813. }
  2814. assert(!*next_point);
  2815. s->packet_buffer_end= this_pktl;
  2816. next_non_null:
  2817. this_pktl->next= *next_point;
  2818. s->streams[pkt->stream_index]->last_in_packet_buffer=
  2819. *next_point= this_pktl;
  2820. }
  2821. static int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
  2822. {
  2823. AVStream *st = s->streams[ pkt ->stream_index];
  2824. AVStream *st2= s->streams[ next->stream_index];
  2825. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  2826. st->time_base);
  2827. if (comp == 0)
  2828. return pkt->stream_index < next->stream_index;
  2829. return comp > 0;
  2830. }
  2831. int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
  2832. AVPacketList *pktl;
  2833. int stream_count=0, noninterleaved_count=0;
  2834. int64_t delta_dts_min = INT64_MAX;
  2835. int i;
  2836. if(pkt){
  2837. ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
  2838. }
  2839. for(i=0; i < s->nb_streams; i++) {
  2840. if (s->streams[i]->last_in_packet_buffer) {
  2841. ++stream_count;
  2842. } else if(s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2843. ++noninterleaved_count;
  2844. }
  2845. }
  2846. if (s->nb_streams == stream_count) {
  2847. flush = 1;
  2848. } else if (!flush){
  2849. for(i=0; i < s->nb_streams; i++) {
  2850. if (s->streams[i]->last_in_packet_buffer) {
  2851. int64_t delta_dts =
  2852. av_rescale_q(s->streams[i]->last_in_packet_buffer->pkt.dts,
  2853. s->streams[i]->time_base,
  2854. AV_TIME_BASE_Q) -
  2855. av_rescale_q(s->packet_buffer->pkt.dts,
  2856. s->streams[s->packet_buffer->pkt.stream_index]->time_base,
  2857. AV_TIME_BASE_Q);
  2858. delta_dts_min = FFMIN(delta_dts_min, delta_dts);
  2859. }
  2860. }
  2861. if(s->nb_streams == stream_count+noninterleaved_count &&
  2862. delta_dts_min > 20*AV_TIME_BASE) {
  2863. av_log(s, AV_LOG_DEBUG, "flushing with %d noninterleaved\n", noninterleaved_count);
  2864. flush = 1;
  2865. }
  2866. }
  2867. if(stream_count && flush){
  2868. pktl= s->packet_buffer;
  2869. *out= pktl->pkt;
  2870. s->packet_buffer= pktl->next;
  2871. if(!s->packet_buffer)
  2872. s->packet_buffer_end= NULL;
  2873. if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
  2874. s->streams[out->stream_index]->last_in_packet_buffer= NULL;
  2875. av_freep(&pktl);
  2876. return 1;
  2877. }else{
  2878. av_init_packet(out);
  2879. return 0;
  2880. }
  2881. }
  2882. /**
  2883. * Interleave an AVPacket correctly so it can be muxed.
  2884. * @param out the interleaved packet will be output here
  2885. * @param in the input packet
  2886. * @param flush 1 if no further packets are available as input and all
  2887. * remaining packets should be output
  2888. * @return 1 if a packet was output, 0 if no packet could be output,
  2889. * < 0 if an error occurred
  2890. */
  2891. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
  2892. if(s->oformat->interleave_packet)
  2893. return s->oformat->interleave_packet(s, out, in, flush);
  2894. else
  2895. return av_interleave_packet_per_dts(s, out, in, flush);
  2896. }
  2897. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
  2898. AVStream *st= s->streams[ pkt->stream_index];
  2899. int ret;
  2900. //FIXME/XXX/HACK drop zero sized packets
  2901. if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
  2902. return 0;
  2903. av_dlog(s, "av_interleaved_write_frame size:%d dts:%"PRId64" pts:%"PRId64"\n",
  2904. pkt->size, pkt->dts, pkt->pts);
  2905. if((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  2906. return ret;
  2907. if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  2908. return AVERROR(EINVAL);
  2909. for(;;){
  2910. AVPacket opkt;
  2911. int ret= interleave_packet(s, &opkt, pkt, 0);
  2912. if(ret<=0) //FIXME cleanup needed for ret<0 ?
  2913. return ret;
  2914. ret= s->oformat->write_packet(s, &opkt);
  2915. if (ret >= 0)
  2916. s->streams[opkt.stream_index]->nb_frames++;
  2917. av_free_packet(&opkt);
  2918. pkt= NULL;
  2919. if(ret<0)
  2920. return ret;
  2921. if(url_ferror(s->pb))
  2922. return url_ferror(s->pb);
  2923. }
  2924. }
  2925. int av_write_trailer(AVFormatContext *s)
  2926. {
  2927. int ret, i;
  2928. for(;;){
  2929. AVPacket pkt;
  2930. ret= interleave_packet(s, &pkt, NULL, 1);
  2931. if(ret<0) //FIXME cleanup needed for ret<0 ?
  2932. goto fail;
  2933. if(!ret)
  2934. break;
  2935. ret= s->oformat->write_packet(s, &pkt);
  2936. if (ret >= 0)
  2937. s->streams[pkt.stream_index]->nb_frames++;
  2938. av_free_packet(&pkt);
  2939. if(ret<0)
  2940. goto fail;
  2941. if(url_ferror(s->pb))
  2942. goto fail;
  2943. }
  2944. if(s->oformat->write_trailer)
  2945. ret = s->oformat->write_trailer(s);
  2946. fail:
  2947. if(ret == 0)
  2948. ret=url_ferror(s->pb);
  2949. for(i=0;i<s->nb_streams;i++) {
  2950. av_freep(&s->streams[i]->priv_data);
  2951. av_freep(&s->streams[i]->index_entries);
  2952. }
  2953. if (s->iformat && s->iformat->priv_class)
  2954. av_opt_free(s->priv_data);
  2955. av_freep(&s->priv_data);
  2956. return ret;
  2957. }
  2958. int av_get_output_timestamp(struct AVFormatContext *s, int stream,
  2959. int64_t *dts, int64_t *wall)
  2960. {
  2961. if (!s->oformat || !s->oformat->get_output_timestamp)
  2962. return AVERROR(ENOSYS);
  2963. s->oformat->get_output_timestamp(s, stream, dts, wall);
  2964. return 0;
  2965. }
  2966. void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
  2967. {
  2968. int i, j;
  2969. AVProgram *program=NULL;
  2970. void *tmp;
  2971. if (idx >= ac->nb_streams) {
  2972. av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
  2973. return;
  2974. }
  2975. for(i=0; i<ac->nb_programs; i++){
  2976. if(ac->programs[i]->id != progid)
  2977. continue;
  2978. program = ac->programs[i];
  2979. for(j=0; j<program->nb_stream_indexes; j++)
  2980. if(program->stream_index[j] == idx)
  2981. return;
  2982. tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
  2983. if(!tmp)
  2984. return;
  2985. program->stream_index = tmp;
  2986. program->stream_index[program->nb_stream_indexes++] = idx;
  2987. return;
  2988. }
  2989. }
  2990. static void print_fps(double d, const char *postfix){
  2991. uint64_t v= lrintf(d*100);
  2992. if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
  2993. else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
  2994. else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
  2995. }
  2996. static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
  2997. {
  2998. if(m && !(m->count == 1 && av_dict_get(m, "language", NULL, 0))){
  2999. AVDictionaryEntry *tag=NULL;
  3000. av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
  3001. while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  3002. if(strcmp("language", tag->key)){
  3003. char tmp[256];
  3004. int i;
  3005. av_strlcpy(tmp, tag->value, sizeof(tmp));
  3006. for(i=0; i<strlen(tmp); i++) if(tmp[i]==0xd) tmp[i]=' ';
  3007. av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tmp);
  3008. }
  3009. }
  3010. }
  3011. }
  3012. /* "user interface" functions */
  3013. static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
  3014. {
  3015. char buf[256];
  3016. int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
  3017. AVStream *st = ic->streams[i];
  3018. int g = av_gcd(st->time_base.num, st->time_base.den);
  3019. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
  3020. avcodec_string(buf, sizeof(buf), st->codec, is_output);
  3021. av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
  3022. /* the pid is an important information, so we display it */
  3023. /* XXX: add a generic system */
  3024. if (flags & AVFMT_SHOW_IDS)
  3025. av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
  3026. if (lang)
  3027. av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
  3028. av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
  3029. av_log(NULL, AV_LOG_INFO, ": %s", buf);
  3030. if (st->sample_aspect_ratio.num && // default
  3031. av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
  3032. AVRational display_aspect_ratio;
  3033. av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
  3034. st->codec->width*st->sample_aspect_ratio.num,
  3035. st->codec->height*st->sample_aspect_ratio.den,
  3036. 1024*1024);
  3037. av_log(NULL, AV_LOG_INFO, ", SAR %d:%d DAR %d:%d",
  3038. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  3039. display_aspect_ratio.num, display_aspect_ratio.den);
  3040. }
  3041. if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
  3042. if(st->avg_frame_rate.den && st->avg_frame_rate.num)
  3043. print_fps(av_q2d(st->avg_frame_rate), "fps");
  3044. if(st->r_frame_rate.den && st->r_frame_rate.num)
  3045. print_fps(av_q2d(st->r_frame_rate), "tbr");
  3046. if(st->time_base.den && st->time_base.num)
  3047. print_fps(1/av_q2d(st->time_base), "tbn");
  3048. if(st->codec->time_base.den && st->codec->time_base.num)
  3049. print_fps(1/av_q2d(st->codec->time_base), "tbc");
  3050. }
  3051. if (st->disposition & AV_DISPOSITION_DEFAULT)
  3052. av_log(NULL, AV_LOG_INFO, " (default)");
  3053. if (st->disposition & AV_DISPOSITION_DUB)
  3054. av_log(NULL, AV_LOG_INFO, " (dub)");
  3055. if (st->disposition & AV_DISPOSITION_ORIGINAL)
  3056. av_log(NULL, AV_LOG_INFO, " (original)");
  3057. if (st->disposition & AV_DISPOSITION_COMMENT)
  3058. av_log(NULL, AV_LOG_INFO, " (comment)");
  3059. if (st->disposition & AV_DISPOSITION_LYRICS)
  3060. av_log(NULL, AV_LOG_INFO, " (lyrics)");
  3061. if (st->disposition & AV_DISPOSITION_KARAOKE)
  3062. av_log(NULL, AV_LOG_INFO, " (karaoke)");
  3063. if (st->disposition & AV_DISPOSITION_FORCED)
  3064. av_log(NULL, AV_LOG_INFO, " (forced)");
  3065. if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
  3066. av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
  3067. if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
  3068. av_log(NULL, AV_LOG_INFO, " (visual impaired)");
  3069. if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
  3070. av_log(NULL, AV_LOG_INFO, " (clean effects)");
  3071. av_log(NULL, AV_LOG_INFO, "\n");
  3072. dump_metadata(NULL, st->metadata, " ");
  3073. }
  3074. #if FF_API_DUMP_FORMAT
  3075. void dump_format(AVFormatContext *ic,
  3076. int index,
  3077. const char *url,
  3078. int is_output)
  3079. {
  3080. av_dump_format(ic, index, url, is_output);
  3081. }
  3082. #endif
  3083. void av_dump_format(AVFormatContext *ic,
  3084. int index,
  3085. const char *url,
  3086. int is_output)
  3087. {
  3088. int i;
  3089. uint8_t *printed = av_mallocz(ic->nb_streams);
  3090. if (ic->nb_streams && !printed)
  3091. return;
  3092. av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
  3093. is_output ? "Output" : "Input",
  3094. index,
  3095. is_output ? ic->oformat->name : ic->iformat->name,
  3096. is_output ? "to" : "from", url);
  3097. dump_metadata(NULL, ic->metadata, " ");
  3098. if (!is_output) {
  3099. av_log(NULL, AV_LOG_INFO, " Duration: ");
  3100. if (ic->duration != AV_NOPTS_VALUE) {
  3101. int hours, mins, secs, us;
  3102. secs = ic->duration / AV_TIME_BASE;
  3103. us = ic->duration % AV_TIME_BASE;
  3104. mins = secs / 60;
  3105. secs %= 60;
  3106. hours = mins / 60;
  3107. mins %= 60;
  3108. av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
  3109. (100 * us) / AV_TIME_BASE);
  3110. } else {
  3111. av_log(NULL, AV_LOG_INFO, "N/A");
  3112. }
  3113. if (ic->start_time != AV_NOPTS_VALUE) {
  3114. int secs, us;
  3115. av_log(NULL, AV_LOG_INFO, ", start: ");
  3116. secs = ic->start_time / AV_TIME_BASE;
  3117. us = abs(ic->start_time % AV_TIME_BASE);
  3118. av_log(NULL, AV_LOG_INFO, "%d.%06d",
  3119. secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
  3120. }
  3121. av_log(NULL, AV_LOG_INFO, ", bitrate: ");
  3122. if (ic->bit_rate) {
  3123. av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
  3124. } else {
  3125. av_log(NULL, AV_LOG_INFO, "N/A");
  3126. }
  3127. av_log(NULL, AV_LOG_INFO, "\n");
  3128. }
  3129. for (i = 0; i < ic->nb_chapters; i++) {
  3130. AVChapter *ch = ic->chapters[i];
  3131. av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
  3132. av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
  3133. av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
  3134. dump_metadata(NULL, ch->metadata, " ");
  3135. }
  3136. if(ic->nb_programs) {
  3137. int j, k, total = 0;
  3138. for(j=0; j<ic->nb_programs; j++) {
  3139. AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
  3140. "name", NULL, 0);
  3141. av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
  3142. name ? name->value : "");
  3143. dump_metadata(NULL, ic->programs[j]->metadata, " ");
  3144. for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
  3145. dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
  3146. printed[ic->programs[j]->stream_index[k]] = 1;
  3147. }
  3148. total += ic->programs[j]->nb_stream_indexes;
  3149. }
  3150. if (total < ic->nb_streams)
  3151. av_log(NULL, AV_LOG_INFO, " No Program\n");
  3152. }
  3153. for(i=0;i<ic->nb_streams;i++)
  3154. if (!printed[i])
  3155. dump_stream_format(ic, i, index, is_output);
  3156. av_free(printed);
  3157. }
  3158. int64_t av_gettime(void)
  3159. {
  3160. struct timeval tv;
  3161. gettimeofday(&tv,NULL);
  3162. return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
  3163. }
  3164. uint64_t ff_ntp_time(void)
  3165. {
  3166. return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
  3167. }
  3168. #if FF_API_PARSE_DATE
  3169. #include "libavutil/parseutils.h"
  3170. int64_t parse_date(const char *timestr, int duration)
  3171. {
  3172. int64_t timeval;
  3173. av_parse_time(&timeval, timestr, duration);
  3174. return timeval;
  3175. }
  3176. #endif
  3177. #if FF_API_FIND_INFO_TAG
  3178. #include "libavutil/parseutils.h"
  3179. int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
  3180. {
  3181. return av_find_info_tag(arg, arg_size, tag1, info);
  3182. }
  3183. #endif
  3184. int av_get_frame_filename(char *buf, int buf_size,
  3185. const char *path, int number)
  3186. {
  3187. const char *p;
  3188. char *q, buf1[20], c;
  3189. int nd, len, percentd_found;
  3190. q = buf;
  3191. p = path;
  3192. percentd_found = 0;
  3193. for(;;) {
  3194. c = *p++;
  3195. if (c == '\0')
  3196. break;
  3197. if (c == '%') {
  3198. do {
  3199. nd = 0;
  3200. while (isdigit(*p)) {
  3201. nd = nd * 10 + *p++ - '0';
  3202. }
  3203. c = *p++;
  3204. } while (isdigit(c));
  3205. switch(c) {
  3206. case '%':
  3207. goto addchar;
  3208. case 'd':
  3209. if (percentd_found)
  3210. goto fail;
  3211. percentd_found = 1;
  3212. snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
  3213. len = strlen(buf1);
  3214. if ((q - buf + len) > buf_size - 1)
  3215. goto fail;
  3216. memcpy(q, buf1, len);
  3217. q += len;
  3218. break;
  3219. default:
  3220. goto fail;
  3221. }
  3222. } else {
  3223. addchar:
  3224. if ((q - buf) < buf_size - 1)
  3225. *q++ = c;
  3226. }
  3227. }
  3228. if (!percentd_found)
  3229. goto fail;
  3230. *q = '\0';
  3231. return 0;
  3232. fail:
  3233. *q = '\0';
  3234. return -1;
  3235. }
  3236. static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
  3237. {
  3238. int len, i, j, c;
  3239. #undef fprintf
  3240. #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
  3241. for(i=0;i<size;i+=16) {
  3242. len = size - i;
  3243. if (len > 16)
  3244. len = 16;
  3245. PRINT("%08x ", i);
  3246. for(j=0;j<16;j++) {
  3247. if (j < len)
  3248. PRINT(" %02x", buf[i+j]);
  3249. else
  3250. PRINT(" ");
  3251. }
  3252. PRINT(" ");
  3253. for(j=0;j<len;j++) {
  3254. c = buf[i+j];
  3255. if (c < ' ' || c > '~')
  3256. c = '.';
  3257. PRINT("%c", c);
  3258. }
  3259. PRINT("\n");
  3260. }
  3261. #undef PRINT
  3262. }
  3263. void av_hex_dump(FILE *f, uint8_t *buf, int size)
  3264. {
  3265. hex_dump_internal(NULL, f, 0, buf, size);
  3266. }
  3267. void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
  3268. {
  3269. hex_dump_internal(avcl, NULL, level, buf, size);
  3270. }
  3271. static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
  3272. {
  3273. #undef fprintf
  3274. #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
  3275. PRINT("stream #%d:\n", pkt->stream_index);
  3276. PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
  3277. PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
  3278. /* DTS is _always_ valid after av_read_frame() */
  3279. PRINT(" dts=");
  3280. if (pkt->dts == AV_NOPTS_VALUE)
  3281. PRINT("N/A");
  3282. else
  3283. PRINT("%0.3f", pkt->dts * av_q2d(time_base));
  3284. /* PTS may not be known if B-frames are present. */
  3285. PRINT(" pts=");
  3286. if (pkt->pts == AV_NOPTS_VALUE)
  3287. PRINT("N/A");
  3288. else
  3289. PRINT("%0.3f", pkt->pts * av_q2d(time_base));
  3290. PRINT("\n");
  3291. PRINT(" size=%d\n", pkt->size);
  3292. #undef PRINT
  3293. if (dump_payload)
  3294. av_hex_dump(f, pkt->data, pkt->size);
  3295. }
  3296. #if FF_API_PKT_DUMP
  3297. void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
  3298. {
  3299. AVRational tb = { 1, AV_TIME_BASE };
  3300. pkt_dump_internal(NULL, f, 0, pkt, dump_payload, tb);
  3301. }
  3302. #endif
  3303. void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
  3304. {
  3305. pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
  3306. }
  3307. #if FF_API_PKT_DUMP
  3308. void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
  3309. {
  3310. AVRational tb = { 1, AV_TIME_BASE };
  3311. pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, tb);
  3312. }
  3313. #endif
  3314. void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
  3315. AVStream *st)
  3316. {
  3317. pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
  3318. }
  3319. void av_url_split(char *proto, int proto_size,
  3320. char *authorization, int authorization_size,
  3321. char *hostname, int hostname_size,
  3322. int *port_ptr,
  3323. char *path, int path_size,
  3324. const char *url)
  3325. {
  3326. const char *p, *ls, *at, *col, *brk;
  3327. if (port_ptr) *port_ptr = -1;
  3328. if (proto_size > 0) proto[0] = 0;
  3329. if (authorization_size > 0) authorization[0] = 0;
  3330. if (hostname_size > 0) hostname[0] = 0;
  3331. if (path_size > 0) path[0] = 0;
  3332. /* parse protocol */
  3333. if ((p = strchr(url, ':'))) {
  3334. av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
  3335. p++; /* skip ':' */
  3336. if (*p == '/') p++;
  3337. if (*p == '/') p++;
  3338. } else {
  3339. /* no protocol means plain filename */
  3340. av_strlcpy(path, url, path_size);
  3341. return;
  3342. }
  3343. /* separate path from hostname */
  3344. ls = strchr(p, '/');
  3345. if(!ls)
  3346. ls = strchr(p, '?');
  3347. if(ls)
  3348. av_strlcpy(path, ls, path_size);
  3349. else
  3350. ls = &p[strlen(p)]; // XXX
  3351. /* the rest is hostname, use that to parse auth/port */
  3352. if (ls != p) {
  3353. /* authorization (user[:pass]@hostname) */
  3354. if ((at = strchr(p, '@')) && at < ls) {
  3355. av_strlcpy(authorization, p,
  3356. FFMIN(authorization_size, at + 1 - p));
  3357. p = at + 1; /* skip '@' */
  3358. }
  3359. if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
  3360. /* [host]:port */
  3361. av_strlcpy(hostname, p + 1,
  3362. FFMIN(hostname_size, brk - p));
  3363. if (brk[1] == ':' && port_ptr)
  3364. *port_ptr = atoi(brk + 2);
  3365. } else if ((col = strchr(p, ':')) && col < ls) {
  3366. av_strlcpy(hostname, p,
  3367. FFMIN(col + 1 - p, hostname_size));
  3368. if (port_ptr) *port_ptr = atoi(col + 1);
  3369. } else
  3370. av_strlcpy(hostname, p,
  3371. FFMIN(ls + 1 - p, hostname_size));
  3372. }
  3373. }
  3374. char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
  3375. {
  3376. int i;
  3377. static const char hex_table_uc[16] = { '0', '1', '2', '3',
  3378. '4', '5', '6', '7',
  3379. '8', '9', 'A', 'B',
  3380. 'C', 'D', 'E', 'F' };
  3381. static const char hex_table_lc[16] = { '0', '1', '2', '3',
  3382. '4', '5', '6', '7',
  3383. '8', '9', 'a', 'b',
  3384. 'c', 'd', 'e', 'f' };
  3385. const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
  3386. for(i = 0; i < s; i++) {
  3387. buff[i * 2] = hex_table[src[i] >> 4];
  3388. buff[i * 2 + 1] = hex_table[src[i] & 0xF];
  3389. }
  3390. return buff;
  3391. }
  3392. int ff_hex_to_data(uint8_t *data, const char *p)
  3393. {
  3394. int c, len, v;
  3395. len = 0;
  3396. v = 1;
  3397. for (;;) {
  3398. p += strspn(p, SPACE_CHARS);
  3399. if (*p == '\0')
  3400. break;
  3401. c = toupper((unsigned char) *p++);
  3402. if (c >= '0' && c <= '9')
  3403. c = c - '0';
  3404. else if (c >= 'A' && c <= 'F')
  3405. c = c - 'A' + 10;
  3406. else
  3407. break;
  3408. v = (v << 4) | c;
  3409. if (v & 0x100) {
  3410. if (data)
  3411. data[len] = v;
  3412. len++;
  3413. v = 1;
  3414. }
  3415. }
  3416. return len;
  3417. }
  3418. void av_set_pts_info(AVStream *s, int pts_wrap_bits,
  3419. unsigned int pts_num, unsigned int pts_den)
  3420. {
  3421. AVRational new_tb;
  3422. if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
  3423. if(new_tb.num != pts_num)
  3424. av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
  3425. }else
  3426. av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
  3427. if(new_tb.num <= 0 || new_tb.den <= 0) {
  3428. av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
  3429. return;
  3430. }
  3431. s->time_base = new_tb;
  3432. s->pts_wrap_bits = pts_wrap_bits;
  3433. }
  3434. int ff_url_join(char *str, int size, const char *proto,
  3435. const char *authorization, const char *hostname,
  3436. int port, const char *fmt, ...)
  3437. {
  3438. #if CONFIG_NETWORK
  3439. struct addrinfo hints, *ai;
  3440. #endif
  3441. str[0] = '\0';
  3442. if (proto)
  3443. av_strlcatf(str, size, "%s://", proto);
  3444. if (authorization && authorization[0])
  3445. av_strlcatf(str, size, "%s@", authorization);
  3446. #if CONFIG_NETWORK && defined(AF_INET6)
  3447. /* Determine if hostname is a numerical IPv6 address,
  3448. * properly escape it within [] in that case. */
  3449. memset(&hints, 0, sizeof(hints));
  3450. hints.ai_flags = AI_NUMERICHOST;
  3451. if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
  3452. if (ai->ai_family == AF_INET6) {
  3453. av_strlcat(str, "[", size);
  3454. av_strlcat(str, hostname, size);
  3455. av_strlcat(str, "]", size);
  3456. } else {
  3457. av_strlcat(str, hostname, size);
  3458. }
  3459. freeaddrinfo(ai);
  3460. } else
  3461. #endif
  3462. /* Not an IPv6 address, just output the plain string. */
  3463. av_strlcat(str, hostname, size);
  3464. if (port >= 0)
  3465. av_strlcatf(str, size, ":%d", port);
  3466. if (fmt) {
  3467. va_list vl;
  3468. int len = strlen(str);
  3469. va_start(vl, fmt);
  3470. vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
  3471. va_end(vl);
  3472. }
  3473. return strlen(str);
  3474. }
  3475. int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
  3476. AVFormatContext *src)
  3477. {
  3478. AVPacket local_pkt;
  3479. local_pkt = *pkt;
  3480. local_pkt.stream_index = dst_stream;
  3481. if (pkt->pts != AV_NOPTS_VALUE)
  3482. local_pkt.pts = av_rescale_q(pkt->pts,
  3483. src->streams[pkt->stream_index]->time_base,
  3484. dst->streams[dst_stream]->time_base);
  3485. if (pkt->dts != AV_NOPTS_VALUE)
  3486. local_pkt.dts = av_rescale_q(pkt->dts,
  3487. src->streams[pkt->stream_index]->time_base,
  3488. dst->streams[dst_stream]->time_base);
  3489. return av_write_frame(dst, &local_pkt);
  3490. }
  3491. void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
  3492. void *context)
  3493. {
  3494. const char *ptr = str;
  3495. /* Parse key=value pairs. */
  3496. for (;;) {
  3497. const char *key;
  3498. char *dest = NULL, *dest_end;
  3499. int key_len, dest_len = 0;
  3500. /* Skip whitespace and potential commas. */
  3501. while (*ptr && (isspace(*ptr) || *ptr == ','))
  3502. ptr++;
  3503. if (!*ptr)
  3504. break;
  3505. key = ptr;
  3506. if (!(ptr = strchr(key, '=')))
  3507. break;
  3508. ptr++;
  3509. key_len = ptr - key;
  3510. callback_get_buf(context, key, key_len, &dest, &dest_len);
  3511. dest_end = dest + dest_len - 1;
  3512. if (*ptr == '\"') {
  3513. ptr++;
  3514. while (*ptr && *ptr != '\"') {
  3515. if (*ptr == '\\') {
  3516. if (!ptr[1])
  3517. break;
  3518. if (dest && dest < dest_end)
  3519. *dest++ = ptr[1];
  3520. ptr += 2;
  3521. } else {
  3522. if (dest && dest < dest_end)
  3523. *dest++ = *ptr;
  3524. ptr++;
  3525. }
  3526. }
  3527. if (*ptr == '\"')
  3528. ptr++;
  3529. } else {
  3530. for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
  3531. if (dest && dest < dest_end)
  3532. *dest++ = *ptr;
  3533. }
  3534. if (dest)
  3535. *dest = 0;
  3536. }
  3537. }
  3538. int ff_find_stream_index(AVFormatContext *s, int id)
  3539. {
  3540. int i;
  3541. for (i = 0; i < s->nb_streams; i++) {
  3542. if (s->streams[i]->id == id)
  3543. return i;
  3544. }
  3545. return -1;
  3546. }
  3547. void ff_make_absolute_url(char *buf, int size, const char *base,
  3548. const char *rel)
  3549. {
  3550. char *sep;
  3551. /* Absolute path, relative to the current server */
  3552. if (base && strstr(base, "://") && rel[0] == '/') {
  3553. if (base != buf)
  3554. av_strlcpy(buf, base, size);
  3555. sep = strstr(buf, "://");
  3556. if (sep) {
  3557. sep += 3;
  3558. sep = strchr(sep, '/');
  3559. if (sep)
  3560. *sep = '\0';
  3561. }
  3562. av_strlcat(buf, rel, size);
  3563. return;
  3564. }
  3565. /* If rel actually is an absolute url, just copy it */
  3566. if (!base || strstr(rel, "://") || rel[0] == '/') {
  3567. av_strlcpy(buf, rel, size);
  3568. return;
  3569. }
  3570. if (base != buf)
  3571. av_strlcpy(buf, base, size);
  3572. /* Remove the file name from the base url */
  3573. sep = strrchr(buf, '/');
  3574. if (sep)
  3575. sep[1] = '\0';
  3576. else
  3577. buf[0] = '\0';
  3578. while (av_strstart(rel, "../", NULL) && sep) {
  3579. /* Remove the path delimiter at the end */
  3580. sep[0] = '\0';
  3581. sep = strrchr(buf, '/');
  3582. /* If the next directory name to pop off is "..", break here */
  3583. if (!strcmp(sep ? &sep[1] : buf, "..")) {
  3584. /* Readd the slash we just removed */
  3585. av_strlcat(buf, "/", size);
  3586. break;
  3587. }
  3588. /* Cut off the directory name */
  3589. if (sep)
  3590. sep[1] = '\0';
  3591. else
  3592. buf[0] = '\0';
  3593. rel += 3;
  3594. }
  3595. av_strlcat(buf, rel, size);
  3596. }
  3597. int64_t ff_iso8601_to_unix_time(const char *datestr)
  3598. {
  3599. #if HAVE_STRPTIME
  3600. struct tm time = {0};
  3601. strptime(datestr, "%Y - %m - %dT%T", &time);
  3602. return mktime(&time);
  3603. #else
  3604. av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
  3605. "the date string.\n");
  3606. return 0;
  3607. #endif
  3608. }
  3609. int avformat_query_codec(AVOutputFormat *ofmt, enum CodecID codec_id, int std_compliance)
  3610. {
  3611. if (ofmt) {
  3612. if (ofmt->query_codec)
  3613. return ofmt->query_codec(codec_id, std_compliance);
  3614. else if (ofmt->codec_tag)
  3615. return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
  3616. else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
  3617. codec_id == ofmt->subtitle_codec)
  3618. return 1;
  3619. }
  3620. return AVERROR_PATCHWELCOME;
  3621. }