utils.c 159 KB

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