utils.c 106 KB

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