utils.c 124 KB

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