vorbisfile.c 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  4. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  5. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  6. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  7. * *
  8. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2015 *
  9. * by the Xiph.Org Foundation https://xiph.org/ *
  10. * *
  11. ********************************************************************
  12. function: stdio-based convenience library for opening/seeking/decoding
  13. ********************************************************************/
  14. #include <stdlib.h>
  15. #include <stdio.h>
  16. #include <errno.h>
  17. #include <string.h>
  18. #include <math.h>
  19. #include "vorbis/codec.h"
  20. /* we don't need or want the static callback symbols here */
  21. #define OV_EXCLUDE_STATIC_CALLBACKS
  22. #include "vorbis/vorbisfile.h"
  23. #include "os.h"
  24. #include "misc.h"
  25. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  26. one logical bitstream arranged end to end (the only form of Ogg
  27. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  28. multiplexing] is not allowed in Vorbis) */
  29. /* A Vorbis file can be played beginning to end (streamed) without
  30. worrying ahead of time about chaining (see decoder_example.c). If
  31. we have the whole file, however, and want random access
  32. (seeking/scrubbing) or desire to know the total length/time of a
  33. file, we need to account for the possibility of chaining. */
  34. /* We can handle things a number of ways; we can determine the entire
  35. bitstream structure right off the bat, or find pieces on demand.
  36. This example determines and caches structure for the entire
  37. bitstream, but builds a virtual decoder on the fly when moving
  38. between links in the chain. */
  39. /* There are also different ways to implement seeking. Enough
  40. information exists in an Ogg bitstream to seek to
  41. sample-granularity positions in the output. Or, one can seek by
  42. picking some portion of the stream roughly in the desired area if
  43. we only want coarse navigation through the stream. */
  44. /*************************************************************************
  45. * Many, many internal helpers. The intention is not to be confusing;
  46. * rampant duplication and monolithic function implementation would be
  47. * harder to understand anyway. The high level functions are last. Begin
  48. * grokking near the end of the file */
  49. /* read a little more data from the file/pipe into the ogg_sync framer
  50. */
  51. #define CHUNKSIZE 65536 /* greater-than-page-size granularity seeking */
  52. #define READSIZE 2048 /* a smaller read size is needed for low-rate streaming. */
  53. static long _get_data(OggVorbis_File *vf){
  54. errno=0;
  55. if(!(vf->callbacks.read_func))return(-1);
  56. if(vf->datasource){
  57. char *buffer=ogg_sync_buffer(&vf->oy,READSIZE);
  58. long bytes=(vf->callbacks.read_func)(buffer,1,READSIZE,vf->datasource);
  59. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  60. if(bytes==0 && errno)return(-1);
  61. return(bytes);
  62. }else
  63. return(0);
  64. }
  65. /* save a tiny smidge of verbosity to make the code more readable */
  66. static int _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  67. if(vf->datasource){
  68. /* only seek if the file position isn't already there */
  69. if(vf->offset != offset){
  70. if(!(vf->callbacks.seek_func)||
  71. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET) == -1)
  72. return OV_EREAD;
  73. vf->offset=offset;
  74. ogg_sync_reset(&vf->oy);
  75. }
  76. }else{
  77. /* shouldn't happen unless someone writes a broken callback */
  78. return OV_EFAULT;
  79. }
  80. return 0;
  81. }
  82. /* The read/seek functions track absolute position within the stream */
  83. /* from the head of the stream, get the next page. boundary specifies
  84. if the function is allowed to fetch more data from the stream (and
  85. how much) or only use internally buffered data.
  86. boundary: -1) unbounded search
  87. 0) read no additional data; use cached only
  88. n) search for a new page beginning for n bytes
  89. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  90. n) found a page at absolute offset n */
  91. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  92. ogg_int64_t boundary){
  93. if(boundary>0)boundary+=vf->offset;
  94. while(1){
  95. long more;
  96. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  97. more=ogg_sync_pageseek(&vf->oy,og);
  98. if(more<0){
  99. /* skipped n bytes */
  100. vf->offset-=more;
  101. }else{
  102. if(more==0){
  103. /* send more paramedics */
  104. if(!boundary)return(OV_FALSE);
  105. {
  106. long ret=_get_data(vf);
  107. if(ret==0)return(OV_EOF);
  108. if(ret<0)return(OV_EREAD);
  109. }
  110. }else{
  111. /* got a page. Return the offset at the page beginning,
  112. advance the internal offset past the page end */
  113. ogg_int64_t ret=vf->offset;
  114. vf->offset+=more;
  115. return(ret);
  116. }
  117. }
  118. }
  119. }
  120. /* find the latest page beginning before the passed in position. Much
  121. dirtier than the above as Ogg doesn't have any backward search
  122. linkage. no 'readp' as it will certainly have to read. */
  123. /* returns offset or OV_EREAD, OV_FAULT */
  124. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_int64_t begin,ogg_page *og){
  125. ogg_int64_t end = begin;
  126. ogg_int64_t ret;
  127. ogg_int64_t offset=-1;
  128. while(offset==-1){
  129. begin-=CHUNKSIZE;
  130. if(begin<0)
  131. begin=0;
  132. ret=_seek_helper(vf,begin);
  133. if(ret)return(ret);
  134. while(vf->offset<end){
  135. memset(og,0,sizeof(*og));
  136. ret=_get_next_page(vf,og,end-vf->offset);
  137. if(ret==OV_EREAD)return(OV_EREAD);
  138. if(ret<0){
  139. break;
  140. }else{
  141. offset=ret;
  142. }
  143. }
  144. }
  145. /* In a fully compliant, non-multiplexed stream, we'll still be
  146. holding the last page. In multiplexed (or noncompliant streams),
  147. we will probably have to re-read the last page we saw */
  148. if(og->header_len==0){
  149. ret=_seek_helper(vf,offset);
  150. if(ret)return(ret);
  151. ret=_get_next_page(vf,og,CHUNKSIZE);
  152. if(ret<0)
  153. /* this shouldn't be possible */
  154. return(OV_EFAULT);
  155. }
  156. return(offset);
  157. }
  158. static void _add_serialno(ogg_page *og,long **serialno_list, int *n){
  159. long s = ogg_page_serialno(og);
  160. (*n)++;
  161. if(*serialno_list){
  162. *serialno_list = _ogg_realloc(*serialno_list, sizeof(**serialno_list)*(*n));
  163. }else{
  164. *serialno_list = _ogg_malloc(sizeof(**serialno_list));
  165. }
  166. (*serialno_list)[(*n)-1] = s;
  167. }
  168. /* returns nonzero if found */
  169. static int _lookup_serialno(long s, long *serialno_list, int n){
  170. if(serialno_list){
  171. while(n--){
  172. if(*serialno_list == s) return 1;
  173. serialno_list++;
  174. }
  175. }
  176. return 0;
  177. }
  178. static int _lookup_page_serialno(ogg_page *og, long *serialno_list, int n){
  179. long s = ogg_page_serialno(og);
  180. return _lookup_serialno(s,serialno_list,n);
  181. }
  182. /* performs the same search as _get_prev_page, but prefers pages of
  183. the specified serial number. If a page of the specified serialno is
  184. spotted during the seek-back-and-read-forward, it will return the
  185. info of last page of the matching serial number instead of the very
  186. last page. If no page of the specified serialno is seen, it will
  187. return the info of last page and alter *serialno. */
  188. static ogg_int64_t _get_prev_page_serial(OggVorbis_File *vf, ogg_int64_t begin,
  189. long *serial_list, int serial_n,
  190. int *serialno, ogg_int64_t *granpos){
  191. ogg_page og;
  192. ogg_int64_t end=begin;
  193. ogg_int64_t ret;
  194. ogg_int64_t prefoffset=-1;
  195. ogg_int64_t offset=-1;
  196. ogg_int64_t ret_serialno=-1;
  197. ogg_int64_t ret_gran=-1;
  198. while(offset==-1){
  199. begin-=CHUNKSIZE;
  200. if(begin<0)
  201. begin=0;
  202. ret=_seek_helper(vf,begin);
  203. if(ret)return(ret);
  204. while(vf->offset<end){
  205. ret=_get_next_page(vf,&og,end-vf->offset);
  206. if(ret==OV_EREAD)return(OV_EREAD);
  207. if(ret<0){
  208. break;
  209. }else{
  210. ret_serialno=ogg_page_serialno(&og);
  211. ret_gran=ogg_page_granulepos(&og);
  212. offset=ret;
  213. if(ret_serialno == *serialno){
  214. prefoffset=ret;
  215. *granpos=ret_gran;
  216. }
  217. if(!_lookup_serialno(ret_serialno,serial_list,serial_n)){
  218. /* we fell off the end of the link, which means we seeked
  219. back too far and shouldn't have been looking in that link
  220. to begin with. If we found the preferred serial number,
  221. forget that we saw it. */
  222. prefoffset=-1;
  223. }
  224. }
  225. }
  226. /*We started from the beginning of the stream and found nothing.
  227. This should be impossible unless the contents of the stream changed out
  228. from under us after we read from it.*/
  229. if(!begin&&vf->offset<0)return OV_EBADLINK;
  230. }
  231. /* we're not interested in the page... just the serialno and granpos. */
  232. if(prefoffset>=0)return(prefoffset);
  233. *serialno = ret_serialno;
  234. *granpos = ret_gran;
  235. return(offset);
  236. }
  237. /* uses the local ogg_stream storage in vf; this is important for
  238. non-streaming input sources */
  239. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  240. long **serialno_list, int *serialno_n,
  241. ogg_page *og_ptr){
  242. ogg_page og;
  243. ogg_packet op;
  244. int i,ret;
  245. int allbos=0;
  246. if(!og_ptr){
  247. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  248. if(llret==OV_EREAD)return(OV_EREAD);
  249. if(llret<0)return(OV_ENOTVORBIS);
  250. og_ptr=&og;
  251. }
  252. vorbis_info_init(vi);
  253. vorbis_comment_init(vc);
  254. vf->ready_state=OPENED;
  255. /* extract the serialnos of all BOS pages + the first set of vorbis
  256. headers we see in the link */
  257. while(ogg_page_bos(og_ptr)){
  258. if(serialno_list){
  259. if(_lookup_page_serialno(og_ptr,*serialno_list,*serialno_n)){
  260. /* a dupe serialnumber in an initial header packet set == invalid stream */
  261. if(*serialno_list)_ogg_free(*serialno_list);
  262. *serialno_list=0;
  263. *serialno_n=0;
  264. ret=OV_EBADHEADER;
  265. goto bail_header;
  266. }
  267. _add_serialno(og_ptr,serialno_list,serialno_n);
  268. }
  269. if(vf->ready_state<STREAMSET){
  270. /* we don't have a vorbis stream in this link yet, so begin
  271. prospective stream setup. We need a stream to get packets */
  272. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  273. ogg_stream_pagein(&vf->os,og_ptr);
  274. if(ogg_stream_packetout(&vf->os,&op) > 0 &&
  275. vorbis_synthesis_idheader(&op)){
  276. /* vorbis header; continue setup */
  277. vf->ready_state=STREAMSET;
  278. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  279. ret=OV_EBADHEADER;
  280. goto bail_header;
  281. }
  282. }
  283. }
  284. /* get next page */
  285. {
  286. ogg_int64_t llret=_get_next_page(vf,og_ptr,CHUNKSIZE);
  287. if(llret==OV_EREAD){
  288. ret=OV_EREAD;
  289. goto bail_header;
  290. }
  291. if(llret<0){
  292. ret=OV_ENOTVORBIS;
  293. goto bail_header;
  294. }
  295. /* if this page also belongs to our vorbis stream, submit it and break */
  296. if(vf->ready_state==STREAMSET &&
  297. vf->os.serialno == ogg_page_serialno(og_ptr)){
  298. ogg_stream_pagein(&vf->os,og_ptr);
  299. break;
  300. }
  301. }
  302. }
  303. if(vf->ready_state!=STREAMSET){
  304. ret = OV_ENOTVORBIS;
  305. goto bail_header;
  306. }
  307. while(1){
  308. i=0;
  309. while(i<2){ /* get a page loop */
  310. while(i<2){ /* get a packet loop */
  311. int result=ogg_stream_packetout(&vf->os,&op);
  312. if(result==0)break;
  313. if(result==-1){
  314. ret=OV_EBADHEADER;
  315. goto bail_header;
  316. }
  317. if((ret=vorbis_synthesis_headerin(vi,vc,&op)))
  318. goto bail_header;
  319. i++;
  320. }
  321. while(i<2){
  322. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  323. ret=OV_EBADHEADER;
  324. goto bail_header;
  325. }
  326. /* if this page belongs to the correct stream, go parse it */
  327. if(vf->os.serialno == ogg_page_serialno(og_ptr)){
  328. ogg_stream_pagein(&vf->os,og_ptr);
  329. break;
  330. }
  331. /* if we never see the final vorbis headers before the link
  332. ends, abort */
  333. if(ogg_page_bos(og_ptr)){
  334. if(allbos){
  335. ret = OV_EBADHEADER;
  336. goto bail_header;
  337. }else
  338. allbos=1;
  339. }
  340. /* otherwise, keep looking */
  341. }
  342. }
  343. return 0;
  344. }
  345. bail_header:
  346. vorbis_info_clear(vi);
  347. vorbis_comment_clear(vc);
  348. vf->ready_state=OPENED;
  349. return ret;
  350. }
  351. /* Starting from current cursor position, get initial PCM offset of
  352. next page. Consumes the page in the process without decoding
  353. audio, however this is only called during stream parsing upon
  354. seekable open. */
  355. static ogg_int64_t _initial_pcmoffset(OggVorbis_File *vf, vorbis_info *vi){
  356. ogg_page og;
  357. ogg_int64_t accumulated=0;
  358. long lastblock=-1;
  359. int result;
  360. int serialno = vf->os.serialno;
  361. while(1){
  362. ogg_packet op;
  363. if(_get_next_page(vf,&og,-1)<0)
  364. break; /* should not be possible unless the file is truncated/mangled */
  365. if(ogg_page_bos(&og)) break;
  366. if(ogg_page_serialno(&og)!=serialno) continue;
  367. /* count blocksizes of all frames in the page */
  368. ogg_stream_pagein(&vf->os,&og);
  369. while((result=ogg_stream_packetout(&vf->os,&op))){
  370. if(result>0){ /* ignore holes */
  371. long thisblock=vorbis_packet_blocksize(vi,&op);
  372. if(thisblock>=0){
  373. if(lastblock!=-1)
  374. accumulated+=(lastblock+thisblock)>>2;
  375. lastblock=thisblock;
  376. }
  377. }
  378. }
  379. if(ogg_page_granulepos(&og)!=-1){
  380. /* pcm offset of last packet on the first audio page */
  381. accumulated= ogg_page_granulepos(&og)-accumulated;
  382. break;
  383. }
  384. }
  385. /* less than zero? Either a corrupt file or a stream with samples
  386. trimmed off the beginning, a normal occurrence; in both cases set
  387. the offset to zero */
  388. if(accumulated<0)accumulated=0;
  389. return accumulated;
  390. }
  391. /* finds each bitstream link one at a time using a bisection search
  392. (has to begin by knowing the offset of the lb's initial page).
  393. Recurses for each link so it can alloc the link storage after
  394. finding them all, then unroll and fill the cache at the same time */
  395. static int _bisect_forward_serialno(OggVorbis_File *vf,
  396. ogg_int64_t begin,
  397. ogg_int64_t searched,
  398. ogg_int64_t end,
  399. ogg_int64_t endgran,
  400. int endserial,
  401. long *currentno_list,
  402. int currentnos,
  403. long m){
  404. ogg_int64_t pcmoffset;
  405. ogg_int64_t dataoffset=searched;
  406. ogg_int64_t endsearched=end;
  407. ogg_int64_t next=end;
  408. ogg_int64_t searchgran=-1;
  409. ogg_page og;
  410. ogg_int64_t ret,last;
  411. int serialno = vf->os.serialno;
  412. /* invariants:
  413. we have the headers and serialnos for the link beginning at 'begin'
  414. we have the offset and granpos of the last page in the file (potentially
  415. not a page we care about)
  416. */
  417. /* Is the last page in our list of current serialnumbers? */
  418. if(_lookup_serialno(endserial,currentno_list,currentnos)){
  419. /* last page is in the starting serialno list, so we've bisected
  420. down to (or just started with) a single link. Now we need to
  421. find the last vorbis page belonging to the first vorbis stream
  422. for this link. */
  423. searched = end;
  424. while(endserial != serialno){
  425. endserial = serialno;
  426. searched=_get_prev_page_serial(vf,searched,currentno_list,currentnos,&endserial,&endgran);
  427. }
  428. vf->links=m+1;
  429. if(vf->offsets)_ogg_free(vf->offsets);
  430. if(vf->serialnos)_ogg_free(vf->serialnos);
  431. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  432. vf->offsets=_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  433. vf->vi=_ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  434. vf->vc=_ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  435. vf->serialnos=_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  436. vf->dataoffsets=_ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  437. vf->pcmlengths=_ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  438. vf->offsets[m+1]=end;
  439. vf->offsets[m]=begin;
  440. vf->pcmlengths[m*2+1]=(endgran<0?0:endgran);
  441. }else{
  442. /* last page is not in the starting stream's serial number list,
  443. so we have multiple links. Find where the stream that begins
  444. our bisection ends. */
  445. long *next_serialno_list=NULL;
  446. int next_serialnos=0;
  447. vorbis_info vi;
  448. vorbis_comment vc;
  449. int testserial = serialno+1;
  450. /* the below guards against garbage seperating the last and
  451. first pages of two links. */
  452. while(searched<endsearched){
  453. ogg_int64_t bisect;
  454. if(endsearched-searched<CHUNKSIZE){
  455. bisect=searched;
  456. }else{
  457. bisect=(searched+endsearched)/2;
  458. }
  459. ret=_seek_helper(vf,bisect);
  460. if(ret)return(ret);
  461. last=_get_next_page(vf,&og,-1);
  462. if(last==OV_EREAD)return(OV_EREAD);
  463. if(last<0 || !_lookup_page_serialno(&og,currentno_list,currentnos)){
  464. endsearched=bisect;
  465. if(last>=0)next=last;
  466. }else{
  467. searched=vf->offset;
  468. }
  469. }
  470. /* Bisection point found */
  471. /* for the time being, fetch end PCM offset the simple way */
  472. searched = next;
  473. while(testserial != serialno){
  474. testserial = serialno;
  475. searched = _get_prev_page_serial(vf,searched,currentno_list,currentnos,&testserial,&searchgran);
  476. }
  477. ret=_seek_helper(vf,next);
  478. if(ret)return(ret);
  479. ret=_fetch_headers(vf,&vi,&vc,&next_serialno_list,&next_serialnos,NULL);
  480. if(ret)return(ret);
  481. serialno = vf->os.serialno;
  482. dataoffset = vf->offset;
  483. /* this will consume a page, however the next bisection always
  484. starts with a raw seek */
  485. pcmoffset = _initial_pcmoffset(vf,&vi);
  486. ret=_bisect_forward_serialno(vf,next,vf->offset,end,endgran,endserial,
  487. next_serialno_list,next_serialnos,m+1);
  488. if(ret)return(ret);
  489. if(next_serialno_list)_ogg_free(next_serialno_list);
  490. vf->offsets[m+1]=next;
  491. vf->serialnos[m+1]=serialno;
  492. vf->dataoffsets[m+1]=dataoffset;
  493. vf->vi[m+1]=vi;
  494. vf->vc[m+1]=vc;
  495. vf->pcmlengths[m*2+1]=searchgran;
  496. vf->pcmlengths[m*2+2]=pcmoffset;
  497. vf->pcmlengths[m*2+3]-=pcmoffset;
  498. if(vf->pcmlengths[m*2+3]<0)vf->pcmlengths[m*2+3]=0;
  499. }
  500. return(0);
  501. }
  502. static int _make_decode_ready(OggVorbis_File *vf){
  503. if(vf->ready_state>STREAMSET)return 0;
  504. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  505. if(vf->seekable){
  506. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  507. return OV_EBADLINK;
  508. }else{
  509. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  510. return OV_EBADLINK;
  511. }
  512. vorbis_block_init(&vf->vd,&vf->vb);
  513. vf->ready_state=INITSET;
  514. vf->bittrack=0.f;
  515. vf->samptrack=0.f;
  516. return 0;
  517. }
  518. static int _open_seekable2(OggVorbis_File *vf){
  519. ogg_int64_t dataoffset=vf->dataoffsets[0],end,endgran=-1;
  520. int endserial=vf->os.serialno;
  521. int serialno=vf->os.serialno;
  522. /* we're partially open and have a first link header state in
  523. storage in vf */
  524. /* fetch initial PCM offset */
  525. ogg_int64_t pcmoffset = _initial_pcmoffset(vf,vf->vi);
  526. /* we can seek, so set out learning all about this file */
  527. if(vf->callbacks.seek_func && vf->callbacks.tell_func){
  528. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  529. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  530. }else{
  531. vf->offset=vf->end=-1;
  532. }
  533. /* If seek_func is implemented, tell_func must also be implemented */
  534. if(vf->end==-1) return(OV_EINVAL);
  535. /* Get the offset of the last page of the physical bitstream, or, if
  536. we're lucky the last vorbis page of this link as most OggVorbis
  537. files will contain a single logical bitstream */
  538. end=_get_prev_page_serial(vf,vf->end,vf->serialnos+2,vf->serialnos[1],&endserial,&endgran);
  539. if(end<0)return(end);
  540. /* now determine bitstream structure recursively */
  541. if(_bisect_forward_serialno(vf,0,dataoffset,end,endgran,endserial,
  542. vf->serialnos+2,vf->serialnos[1],0)<0)return(OV_EREAD);
  543. vf->offsets[0]=0;
  544. vf->serialnos[0]=serialno;
  545. vf->dataoffsets[0]=dataoffset;
  546. vf->pcmlengths[0]=pcmoffset;
  547. vf->pcmlengths[1]-=pcmoffset;
  548. if(vf->pcmlengths[1]<0)vf->pcmlengths[1]=0;
  549. return(ov_raw_seek(vf,dataoffset));
  550. }
  551. /* clear out the current logical bitstream decoder */
  552. static void _decode_clear(OggVorbis_File *vf){
  553. vorbis_dsp_clear(&vf->vd);
  554. vorbis_block_clear(&vf->vb);
  555. vf->ready_state=OPENED;
  556. }
  557. /* fetch and process a packet. Handles the case where we're at a
  558. bitstream boundary and dumps the decoding machine. If the decoding
  559. machine is unloaded, it loads it. It also keeps pcm_offset up to
  560. date (seek and read both use this. seek uses a special hack with
  561. readp).
  562. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  563. 0) need more data (only if readp==0)
  564. 1) got a packet
  565. */
  566. static int _fetch_and_process_packet(OggVorbis_File *vf,
  567. ogg_packet *op_in,
  568. int readp,
  569. int spanp){
  570. ogg_page og;
  571. /* handle one packet. Try to fetch it from current stream state */
  572. /* extract packets from page */
  573. while(1){
  574. if(vf->ready_state==STREAMSET){
  575. int ret=_make_decode_ready(vf);
  576. if(ret<0)return ret;
  577. }
  578. /* process a packet if we can. */
  579. if(vf->ready_state==INITSET){
  580. int hs=vorbis_synthesis_halfrate_p(vf->vi);
  581. while(1) {
  582. ogg_packet op;
  583. ogg_packet *op_ptr=(op_in?op_in:&op);
  584. int result=ogg_stream_packetout(&vf->os,op_ptr);
  585. ogg_int64_t granulepos;
  586. op_in=NULL;
  587. if(result==-1)return(OV_HOLE); /* hole in the data. */
  588. if(result>0){
  589. /* got a packet. process it */
  590. granulepos=op_ptr->granulepos;
  591. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  592. header handling. The
  593. header packets aren't
  594. audio, so if/when we
  595. submit them,
  596. vorbis_synthesis will
  597. reject them */
  598. /* suck in the synthesis data and track bitrate */
  599. {
  600. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  601. /* for proper use of libvorbis within libvorbisfile,
  602. oldsamples will always be zero. */
  603. if(oldsamples)return(OV_EFAULT);
  604. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  605. vf->samptrack+=(vorbis_synthesis_pcmout(&vf->vd,NULL)<<hs);
  606. vf->bittrack+=op_ptr->bytes*8;
  607. }
  608. /* update the pcm offset. */
  609. if(granulepos!=-1 && !op_ptr->e_o_s){
  610. int link=(vf->seekable?vf->current_link:0);
  611. int i,samples;
  612. /* this packet has a pcm_offset on it (the last packet
  613. completed on a page carries the offset) After processing
  614. (above), we know the pcm position of the *last* sample
  615. ready to be returned. Find the offset of the *first*
  616. As an aside, this trick is inaccurate if we begin
  617. reading anew right at the last page; the end-of-stream
  618. granulepos declares the last frame in the stream, and the
  619. last packet of the last page may be a partial frame.
  620. So, we need a previous granulepos from an in-sequence page
  621. to have a reference point. Thus the !op_ptr->e_o_s clause
  622. above */
  623. if(vf->seekable && link>0)
  624. granulepos-=vf->pcmlengths[link*2];
  625. if(granulepos<0)granulepos=0; /* actually, this
  626. shouldn't be possible
  627. here unless the stream
  628. is very broken */
  629. samples=(vorbis_synthesis_pcmout(&vf->vd,NULL)<<hs);
  630. granulepos-=samples;
  631. for(i=0;i<link;i++)
  632. granulepos+=vf->pcmlengths[i*2+1];
  633. vf->pcm_offset=granulepos;
  634. }
  635. return(1);
  636. }
  637. }
  638. else
  639. break;
  640. }
  641. }
  642. if(vf->ready_state>=OPENED){
  643. ogg_int64_t ret;
  644. while(1){
  645. /* the loop is not strictly necessary, but there's no sense in
  646. doing the extra checks of the larger loop for the common
  647. case in a multiplexed bistream where the page is simply
  648. part of a different logical bitstream; keep reading until
  649. we get one with the correct serialno */
  650. if(!readp)return(0);
  651. if((ret=_get_next_page(vf,&og,-1))<0){
  652. return(OV_EOF); /* eof. leave unitialized */
  653. }
  654. /* bitrate tracking; add the header's bytes here, the body bytes
  655. are done by packet above */
  656. vf->bittrack+=og.header_len*8;
  657. if(vf->ready_state==INITSET){
  658. if(vf->current_serialno!=ogg_page_serialno(&og)){
  659. /* two possibilities:
  660. 1) our decoding just traversed a bitstream boundary
  661. 2) another stream is multiplexed into this logical section */
  662. if(ogg_page_bos(&og)){
  663. /* boundary case */
  664. if(!spanp)
  665. return(OV_EOF);
  666. _decode_clear(vf);
  667. if(!vf->seekable){
  668. vorbis_info_clear(vf->vi);
  669. vorbis_comment_clear(vf->vc);
  670. }
  671. break;
  672. }else
  673. continue; /* possibility #2 */
  674. }
  675. }
  676. break;
  677. }
  678. }
  679. /* Do we need to load a new machine before submitting the page? */
  680. /* This is different in the seekable and non-seekable cases.
  681. In the seekable case, we already have all the header
  682. information loaded and cached; we just initialize the machine
  683. with it and continue on our merry way.
  684. In the non-seekable (streaming) case, we'll only be at a
  685. boundary if we just left the previous logical bitstream and
  686. we're now nominally at the header of the next bitstream
  687. */
  688. if(vf->ready_state!=INITSET){
  689. int link;
  690. if(vf->ready_state<STREAMSET){
  691. if(vf->seekable){
  692. long serialno = ogg_page_serialno(&og);
  693. /* match the serialno to bitstream section. We use this rather than
  694. offset positions to avoid problems near logical bitstream
  695. boundaries */
  696. for(link=0;link<vf->links;link++)
  697. if(vf->serialnos[link]==serialno)break;
  698. if(link==vf->links) continue; /* not the desired Vorbis
  699. bitstream section; keep
  700. trying */
  701. vf->current_serialno=serialno;
  702. vf->current_link=link;
  703. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  704. vf->ready_state=STREAMSET;
  705. }else{
  706. /* we're streaming */
  707. /* fetch the three header packets, build the info struct */
  708. int ret=_fetch_headers(vf,vf->vi,vf->vc,NULL,NULL,&og);
  709. if(ret)return(ret);
  710. vf->current_serialno=vf->os.serialno;
  711. vf->current_link++;
  712. link=0;
  713. }
  714. }
  715. }
  716. /* the buffered page is the data we want, and we're ready for it;
  717. add it to the stream state */
  718. ogg_stream_pagein(&vf->os,&og);
  719. }
  720. }
  721. /* if, eg, 64 bit stdio is configured by default, this will build with
  722. fseek64 */
  723. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  724. if(f==NULL)return(-1);
  725. return fseek(f,off,whence);
  726. }
  727. static int _ov_open1(void *f,OggVorbis_File *vf,const char *initial,
  728. long ibytes, ov_callbacks callbacks){
  729. int offsettest=((f && callbacks.seek_func)?callbacks.seek_func(f,0,SEEK_CUR):-1);
  730. long *serialno_list=NULL;
  731. int serialno_list_size=0;
  732. int ret;
  733. memset(vf,0,sizeof(*vf));
  734. vf->datasource=f;
  735. vf->callbacks = callbacks;
  736. /* init the framing state */
  737. ogg_sync_init(&vf->oy);
  738. /* perhaps some data was previously read into a buffer for testing
  739. against other stream types. Allow initialization from this
  740. previously read data (especially as we may be reading from a
  741. non-seekable stream) */
  742. if(initial){
  743. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  744. memcpy(buffer,initial,ibytes);
  745. ogg_sync_wrote(&vf->oy,ibytes);
  746. }
  747. /* can we seek? Stevens suggests the seek test was portable */
  748. if(offsettest!=-1)vf->seekable=1;
  749. /* No seeking yet; Set up a 'single' (current) logical bitstream
  750. entry for partial open */
  751. vf->links=1;
  752. vf->vi=_ogg_calloc(vf->links,sizeof(*vf->vi));
  753. vf->vc=_ogg_calloc(vf->links,sizeof(*vf->vc));
  754. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  755. /* Fetch all BOS pages, store the vorbis header and all seen serial
  756. numbers, load subsequent vorbis setup headers */
  757. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&serialno_list,&serialno_list_size,NULL))<0){
  758. vf->datasource=NULL;
  759. ov_clear(vf);
  760. }else{
  761. /* serial number list for first link needs to be held somewhere
  762. for second stage of seekable stream open; this saves having to
  763. seek/reread first link's serialnumber data then. */
  764. vf->serialnos=_ogg_calloc(serialno_list_size+2,sizeof(*vf->serialnos));
  765. vf->serialnos[0]=vf->current_serialno=vf->os.serialno;
  766. vf->serialnos[1]=serialno_list_size;
  767. memcpy(vf->serialnos+2,serialno_list,serialno_list_size*sizeof(*vf->serialnos));
  768. vf->offsets=_ogg_calloc(1,sizeof(*vf->offsets));
  769. vf->dataoffsets=_ogg_calloc(1,sizeof(*vf->dataoffsets));
  770. vf->offsets[0]=0;
  771. vf->dataoffsets[0]=vf->offset;
  772. vf->ready_state=PARTOPEN;
  773. }
  774. if(serialno_list)_ogg_free(serialno_list);
  775. return(ret);
  776. }
  777. static int _ov_open2(OggVorbis_File *vf){
  778. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  779. vf->ready_state=OPENED;
  780. if(vf->seekable){
  781. int ret=_open_seekable2(vf);
  782. if(ret){
  783. vf->datasource=NULL;
  784. ov_clear(vf);
  785. }
  786. return(ret);
  787. }else
  788. vf->ready_state=STREAMSET;
  789. return 0;
  790. }
  791. /* clear out the OggVorbis_File struct */
  792. int ov_clear(OggVorbis_File *vf){
  793. if(vf){
  794. vorbis_block_clear(&vf->vb);
  795. vorbis_dsp_clear(&vf->vd);
  796. ogg_stream_clear(&vf->os);
  797. if(vf->vi && vf->links){
  798. int i;
  799. for(i=0;i<vf->links;i++){
  800. vorbis_info_clear(vf->vi+i);
  801. vorbis_comment_clear(vf->vc+i);
  802. }
  803. _ogg_free(vf->vi);
  804. _ogg_free(vf->vc);
  805. }
  806. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  807. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  808. if(vf->serialnos)_ogg_free(vf->serialnos);
  809. if(vf->offsets)_ogg_free(vf->offsets);
  810. ogg_sync_clear(&vf->oy);
  811. if(vf->datasource && vf->callbacks.close_func)
  812. (vf->callbacks.close_func)(vf->datasource);
  813. memset(vf,0,sizeof(*vf));
  814. }
  815. #ifdef DEBUG_LEAKS
  816. _VDBG_dump();
  817. #endif
  818. return(0);
  819. }
  820. /* inspects the OggVorbis file and finds/documents all the logical
  821. bitstreams contained in it. Tries to be tolerant of logical
  822. bitstream sections that are truncated/woogie.
  823. return: -1) error
  824. 0) OK
  825. */
  826. int ov_open_callbacks(void *f,OggVorbis_File *vf,
  827. const char *initial,long ibytes,ov_callbacks callbacks){
  828. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  829. if(ret)return ret;
  830. return _ov_open2(vf);
  831. }
  832. int ov_open(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes){
  833. ov_callbacks callbacks = {
  834. (size_t (*)(void *, size_t, size_t, void *)) fread,
  835. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  836. (int (*)(void *)) fclose,
  837. (long (*)(void *)) ftell
  838. };
  839. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  840. }
  841. int ov_fopen(const char *path,OggVorbis_File *vf){
  842. int ret;
  843. FILE *f = fopen(path,"rb");
  844. if(!f) return -1;
  845. ret = ov_open(f,vf,NULL,0);
  846. if(ret) fclose(f);
  847. return ret;
  848. }
  849. /* cheap hack for game usage where downsampling is desirable; there's
  850. no need for SRC as we can just do it cheaply in libvorbis. */
  851. int ov_halfrate(OggVorbis_File *vf,int flag){
  852. int i;
  853. if(vf->vi==NULL)return OV_EINVAL;
  854. if(vf->ready_state>STREAMSET){
  855. /* clear out stream state; dumping the decode machine is needed to
  856. reinit the MDCT lookups. */
  857. vorbis_dsp_clear(&vf->vd);
  858. vorbis_block_clear(&vf->vb);
  859. vf->ready_state=STREAMSET;
  860. if(vf->pcm_offset>=0){
  861. ogg_int64_t pos=vf->pcm_offset;
  862. vf->pcm_offset=-1; /* make sure the pos is dumped if unseekable */
  863. ov_pcm_seek(vf,pos);
  864. }
  865. }
  866. for(i=0;i<vf->links;i++){
  867. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  868. if(flag) ov_halfrate(vf,0);
  869. return OV_EINVAL;
  870. }
  871. }
  872. return 0;
  873. }
  874. int ov_halfrate_p(OggVorbis_File *vf){
  875. if(vf->vi==NULL)return OV_EINVAL;
  876. return vorbis_synthesis_halfrate_p(vf->vi);
  877. }
  878. /* Only partially open the vorbis file; test for Vorbisness, and load
  879. the headers for the first chain. Do not seek (although test for
  880. seekability). Use ov_test_open to finish opening the file, else
  881. ov_clear to close/free it. Same return codes as open.
  882. Note that vorbisfile does _not_ take ownership of the file if the
  883. call fails; the calling applicaiton is responsible for closing the file
  884. if this call returns an error. */
  885. int ov_test_callbacks(void *f,OggVorbis_File *vf,
  886. const char *initial,long ibytes,ov_callbacks callbacks)
  887. {
  888. return _ov_open1(f,vf,initial,ibytes,callbacks);
  889. }
  890. int ov_test(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes){
  891. ov_callbacks callbacks = {
  892. (size_t (*)(void *, size_t, size_t, void *)) fread,
  893. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  894. (int (*)(void *)) fclose,
  895. (long (*)(void *)) ftell
  896. };
  897. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  898. }
  899. int ov_test_open(OggVorbis_File *vf){
  900. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  901. return _ov_open2(vf);
  902. }
  903. /* How many logical bitstreams in this physical bitstream? */
  904. long ov_streams(OggVorbis_File *vf){
  905. return vf->links;
  906. }
  907. /* Is the FILE * associated with vf seekable? */
  908. long ov_seekable(OggVorbis_File *vf){
  909. return vf->seekable;
  910. }
  911. /* returns the bitrate for a given logical bitstream or the entire
  912. physical bitstream. If the file is open for random access, it will
  913. find the *actual* average bitrate. If the file is streaming, it
  914. returns the nominal bitrate (if set) else the average of the
  915. upper/lower bounds (if set) else -1 (unset).
  916. If you want the actual bitrate field settings, get them from the
  917. vorbis_info structs */
  918. long ov_bitrate(OggVorbis_File *vf,int i){
  919. if(vf->ready_state<OPENED)return(OV_EINVAL);
  920. if(i>=vf->links)return(OV_EINVAL);
  921. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  922. if(i<0){
  923. ogg_int64_t bits=0;
  924. int i;
  925. float br;
  926. for(i=0;i<vf->links;i++)
  927. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  928. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  929. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  930. * so this is slightly transformed to make it work.
  931. */
  932. br = bits/ov_time_total(vf,-1);
  933. return(rint(br));
  934. }else{
  935. if(vf->seekable){
  936. /* return the actual bitrate */
  937. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  938. }else{
  939. /* return nominal if set */
  940. if(vf->vi[i].bitrate_nominal>0){
  941. return vf->vi[i].bitrate_nominal;
  942. }else{
  943. if(vf->vi[i].bitrate_upper>0){
  944. if(vf->vi[i].bitrate_lower>0){
  945. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  946. }else{
  947. return vf->vi[i].bitrate_upper;
  948. }
  949. }
  950. return(OV_FALSE);
  951. }
  952. }
  953. }
  954. }
  955. /* returns the actual bitrate since last call. returns -1 if no
  956. additional data to offer since last call (or at beginning of stream),
  957. EINVAL if stream is only partially open
  958. */
  959. long ov_bitrate_instant(OggVorbis_File *vf){
  960. int link=(vf->seekable?vf->current_link:0);
  961. long ret;
  962. if(vf->ready_state<OPENED)return(OV_EINVAL);
  963. if(vf->samptrack==0)return(OV_FALSE);
  964. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  965. vf->bittrack=0.f;
  966. vf->samptrack=0.f;
  967. return(ret);
  968. }
  969. /* Guess */
  970. long ov_serialnumber(OggVorbis_File *vf,int i){
  971. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  972. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  973. if(i<0){
  974. return(vf->current_serialno);
  975. }else{
  976. return(vf->serialnos[i]);
  977. }
  978. }
  979. /* returns: total raw (compressed) length of content if i==-1
  980. raw (compressed) length of that logical bitstream for i==0 to n
  981. OV_EINVAL if the stream is not seekable (we can't know the length)
  982. or if stream is only partially open
  983. */
  984. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  985. if(vf->ready_state<OPENED)return(OV_EINVAL);
  986. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  987. if(i<0){
  988. ogg_int64_t acc=0;
  989. int i;
  990. for(i=0;i<vf->links;i++)
  991. acc+=ov_raw_total(vf,i);
  992. return(acc);
  993. }else{
  994. return(vf->offsets[i+1]-vf->offsets[i]);
  995. }
  996. }
  997. /* returns: total PCM length (samples) of content if i==-1 PCM length
  998. (samples) of that logical bitstream for i==0 to n
  999. OV_EINVAL if the stream is not seekable (we can't know the
  1000. length) or only partially open
  1001. */
  1002. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  1003. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1004. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  1005. if(i<0){
  1006. ogg_int64_t acc=0;
  1007. int i;
  1008. for(i=0;i<vf->links;i++)
  1009. acc+=ov_pcm_total(vf,i);
  1010. return(acc);
  1011. }else{
  1012. return(vf->pcmlengths[i*2+1]);
  1013. }
  1014. }
  1015. /* returns: total seconds of content if i==-1
  1016. seconds in that logical bitstream for i==0 to n
  1017. OV_EINVAL if the stream is not seekable (we can't know the
  1018. length) or only partially open
  1019. */
  1020. double ov_time_total(OggVorbis_File *vf,int i){
  1021. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1022. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  1023. if(i<0){
  1024. double acc=0;
  1025. int i;
  1026. for(i=0;i<vf->links;i++)
  1027. acc+=ov_time_total(vf,i);
  1028. return(acc);
  1029. }else{
  1030. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  1031. }
  1032. }
  1033. /* seek to an offset relative to the *compressed* data. This also
  1034. scans packets to update the PCM cursor. It will cross a logical
  1035. bitstream boundary, but only if it can't get any packets out of the
  1036. tail of the bitstream we seek to (so no surprises).
  1037. returns zero on success, nonzero on failure */
  1038. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  1039. ogg_stream_state work_os;
  1040. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1041. if(!vf->seekable)
  1042. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  1043. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  1044. /* is the seek position outside our current link [if any]? */
  1045. if(vf->ready_state>=STREAMSET){
  1046. if(pos<vf->offsets[vf->current_link] || pos>=vf->offsets[vf->current_link+1])
  1047. _decode_clear(vf); /* clear out stream state */
  1048. }
  1049. /* don't yet clear out decoding machine (if it's initialized), in
  1050. the case we're in the same link. Restart the decode lapping, and
  1051. let _fetch_and_process_packet deal with a potential bitstream
  1052. boundary */
  1053. vf->pcm_offset=-1;
  1054. ogg_stream_reset_serialno(&vf->os,
  1055. vf->current_serialno); /* must set serialno */
  1056. vorbis_synthesis_restart(&vf->vd);
  1057. if(_seek_helper(vf,pos)) {
  1058. /* dump the machine so we're in a known state */
  1059. vf->pcm_offset=-1;
  1060. _decode_clear(vf);
  1061. return OV_EBADLINK;
  1062. }
  1063. /* we need to make sure the pcm_offset is set, but we don't want to
  1064. advance the raw cursor past good packets just to get to the first
  1065. with a granulepos. That's not equivalent behavior to beginning
  1066. decoding as immediately after the seek position as possible.
  1067. So, a hack. We use two stream states; a local scratch state and
  1068. the shared vf->os stream state. We use the local state to
  1069. scan, and the shared state as a buffer for later decode.
  1070. Unfortuantely, on the last page we still advance to last packet
  1071. because the granulepos on the last page is not necessarily on a
  1072. packet boundary, and we need to make sure the granpos is
  1073. correct.
  1074. */
  1075. {
  1076. ogg_page og;
  1077. ogg_packet op;
  1078. int lastblock=0;
  1079. int accblock=0;
  1080. int thisblock=0;
  1081. int lastflag=0;
  1082. int firstflag=0;
  1083. ogg_int64_t pagepos=-1;
  1084. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  1085. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  1086. return from not necessarily
  1087. starting from the beginning */
  1088. while(1){
  1089. if(vf->ready_state>=STREAMSET){
  1090. /* snarf/scan a packet if we can */
  1091. int result=ogg_stream_packetout(&work_os,&op);
  1092. if(result>0){
  1093. if(vf->vi[vf->current_link].codec_setup){
  1094. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  1095. if(thisblock<0){
  1096. ogg_stream_packetout(&vf->os,NULL);
  1097. thisblock=0;
  1098. }else{
  1099. /* We can't get a guaranteed correct pcm position out of the
  1100. last page in a stream because it might have a 'short'
  1101. granpos, which can only be detected in the presence of a
  1102. preceding page. However, if the last page is also the first
  1103. page, the granpos rules of a first page take precedence. Not
  1104. only that, but for first==last, the EOS page must be treated
  1105. as if its a normal first page for the stream to open/play. */
  1106. if(lastflag && !firstflag)
  1107. ogg_stream_packetout(&vf->os,NULL);
  1108. else
  1109. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  1110. }
  1111. if(op.granulepos!=-1){
  1112. int i,link=vf->current_link;
  1113. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  1114. if(granulepos<0)granulepos=0;
  1115. for(i=0;i<link;i++)
  1116. granulepos+=vf->pcmlengths[i*2+1];
  1117. vf->pcm_offset=granulepos-accblock;
  1118. if(vf->pcm_offset<0)vf->pcm_offset=0;
  1119. break;
  1120. }
  1121. lastblock=thisblock;
  1122. continue;
  1123. }else
  1124. ogg_stream_packetout(&vf->os,NULL);
  1125. }
  1126. }
  1127. if(!lastblock){
  1128. pagepos=_get_next_page(vf,&og,-1);
  1129. if(pagepos<0){
  1130. vf->pcm_offset=ov_pcm_total(vf,-1);
  1131. break;
  1132. }
  1133. }else{
  1134. /* huh? Bogus stream with packets but no granulepos */
  1135. vf->pcm_offset=-1;
  1136. break;
  1137. }
  1138. /* has our decoding just traversed a bitstream boundary? */
  1139. if(vf->ready_state>=STREAMSET){
  1140. if(vf->current_serialno!=ogg_page_serialno(&og)){
  1141. /* two possibilities:
  1142. 1) our decoding just traversed a bitstream boundary
  1143. 2) another stream is multiplexed into this logical section? */
  1144. if(ogg_page_bos(&og)){
  1145. /* we traversed */
  1146. _decode_clear(vf); /* clear out stream state */
  1147. ogg_stream_clear(&work_os);
  1148. } /* else, do nothing; next loop will scoop another page */
  1149. }
  1150. }
  1151. if(vf->ready_state<STREAMSET){
  1152. int link;
  1153. long serialno = ogg_page_serialno(&og);
  1154. for(link=0;link<vf->links;link++)
  1155. if(vf->serialnos[link]==serialno)break;
  1156. if(link==vf->links) continue; /* not the desired Vorbis
  1157. bitstream section; keep
  1158. trying */
  1159. vf->current_link=link;
  1160. vf->current_serialno=serialno;
  1161. ogg_stream_reset_serialno(&vf->os,serialno);
  1162. ogg_stream_reset_serialno(&work_os,serialno);
  1163. vf->ready_state=STREAMSET;
  1164. firstflag=(pagepos<=vf->dataoffsets[link]);
  1165. }
  1166. ogg_stream_pagein(&vf->os,&og);
  1167. ogg_stream_pagein(&work_os,&og);
  1168. lastflag=ogg_page_eos(&og);
  1169. }
  1170. }
  1171. ogg_stream_clear(&work_os);
  1172. vf->bittrack=0.f;
  1173. vf->samptrack=0.f;
  1174. return(0);
  1175. }
  1176. /* Page granularity seek (faster than sample granularity because we
  1177. don't do the last bit of decode to find a specific sample).
  1178. Seek to the last [granule marked] page preceding the specified pos
  1179. location, such that decoding past the returned point will quickly
  1180. arrive at the requested position. */
  1181. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  1182. int link=-1;
  1183. ogg_int64_t result=0;
  1184. ogg_int64_t total=ov_pcm_total(vf,-1);
  1185. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1186. if(!vf->seekable)return(OV_ENOSEEK);
  1187. if(pos<0 || pos>total)return(OV_EINVAL);
  1188. /* which bitstream section does this pcm offset occur in? */
  1189. for(link=vf->links-1;link>=0;link--){
  1190. total-=vf->pcmlengths[link*2+1];
  1191. if(pos>=total)break;
  1192. }
  1193. /* Search within the logical bitstream for the page with the highest
  1194. pcm_pos preceding pos. If we're looking for a position on the
  1195. first page, bisection will halt without finding our position as
  1196. it's before the first explicit granulepos fencepost. That case is
  1197. handled separately below.
  1198. There is a danger here; missing pages or incorrect frame number
  1199. information in the bitstream could make our task impossible.
  1200. Account for that (it would be an error condition) */
  1201. /* new search algorithm originally by HB (Nicholas Vinen) */
  1202. {
  1203. ogg_int64_t end=vf->offsets[link+1];
  1204. ogg_int64_t begin=vf->dataoffsets[link];
  1205. ogg_int64_t begintime = vf->pcmlengths[link*2];
  1206. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  1207. ogg_int64_t target=pos-total+begintime;
  1208. ogg_int64_t best=-1;
  1209. int got_page=0;
  1210. ogg_page og;
  1211. /* if we have only one page, there will be no bisection. Grab the page here */
  1212. if(begin==end){
  1213. result=_seek_helper(vf,begin);
  1214. if(result) goto seek_error;
  1215. result=_get_next_page(vf,&og,1);
  1216. if(result<0) goto seek_error;
  1217. got_page=1;
  1218. }
  1219. /* bisection loop */
  1220. while(begin<end){
  1221. ogg_int64_t bisect;
  1222. if(end-begin<CHUNKSIZE){
  1223. bisect=begin;
  1224. }else{
  1225. /* take a (pretty decent) guess. */
  1226. bisect=begin +
  1227. (ogg_int64_t)((double)(target-begintime)*(end-begin)/(endtime-begintime))
  1228. - CHUNKSIZE;
  1229. if(bisect<begin+CHUNKSIZE)
  1230. bisect=begin;
  1231. }
  1232. result=_seek_helper(vf,bisect);
  1233. if(result) goto seek_error;
  1234. /* read loop within the bisection loop */
  1235. while(begin<end){
  1236. result=_get_next_page(vf,&og,end-vf->offset);
  1237. if(result==OV_EREAD) goto seek_error;
  1238. if(result<0){
  1239. /* there is no next page! */
  1240. if(bisect<=begin+1)
  1241. /* No bisection left to perform. We've either found the
  1242. best candidate already or failed. Exit loop. */
  1243. end=begin;
  1244. else{
  1245. /* We tried to load a fraction of the last page; back up a
  1246. bit and try to get the whole last page */
  1247. if(bisect==0) goto seek_error;
  1248. bisect-=CHUNKSIZE;
  1249. /* don't repeat/loop on a read we've already performed */
  1250. if(bisect<=begin)bisect=begin+1;
  1251. /* seek and cntinue bisection */
  1252. result=_seek_helper(vf,bisect);
  1253. if(result) goto seek_error;
  1254. }
  1255. }else{
  1256. ogg_int64_t granulepos;
  1257. got_page=1;
  1258. /* got a page. analyze it */
  1259. /* only consider pages from primary vorbis stream */
  1260. if(ogg_page_serialno(&og)!=vf->serialnos[link])
  1261. continue;
  1262. /* only consider pages with the granulepos set */
  1263. granulepos=ogg_page_granulepos(&og);
  1264. if(granulepos==-1)continue;
  1265. if(granulepos<target){
  1266. /* this page is a successful candidate! Set state */
  1267. best=result; /* raw offset of packet with granulepos */
  1268. begin=vf->offset; /* raw offset of next page */
  1269. begintime=granulepos;
  1270. /* if we're before our target but within a short distance,
  1271. don't bisect; read forward */
  1272. if(target-begintime>44100)break;
  1273. bisect=begin; /* *not* begin + 1 as above */
  1274. }else{
  1275. /* This is one of our pages, but the granpos is
  1276. post-target; it is not a bisection return
  1277. candidate. (The only way we'd use it is if it's the
  1278. first page in the stream; we handle that case later
  1279. outside the bisection) */
  1280. if(bisect<=begin+1){
  1281. /* No bisection left to perform. We've either found the
  1282. best candidate already or failed. Exit loop. */
  1283. end=begin;
  1284. }else{
  1285. if(end==vf->offset){
  1286. /* bisection read to the end; use the known page
  1287. boundary (result) to update bisection, back up a
  1288. little bit, and try again */
  1289. end=result;
  1290. bisect-=CHUNKSIZE;
  1291. if(bisect<=begin)bisect=begin+1;
  1292. result=_seek_helper(vf,bisect);
  1293. if(result) goto seek_error;
  1294. }else{
  1295. /* Normal bisection */
  1296. end=bisect;
  1297. endtime=granulepos;
  1298. break;
  1299. }
  1300. }
  1301. }
  1302. }
  1303. }
  1304. }
  1305. /* Out of bisection: did it 'fail?' */
  1306. if(best == -1){
  1307. /* Check the 'looking for data in first page' special case;
  1308. bisection would 'fail' because our search target was before the
  1309. first PCM granule position fencepost. */
  1310. if(got_page &&
  1311. begin == vf->dataoffsets[link] &&
  1312. ogg_page_serialno(&og)==vf->serialnos[link]){
  1313. /* Yes, this is the beginning-of-stream case. We already have
  1314. our page, right at the beginning of PCM data. Set state
  1315. and return. */
  1316. vf->pcm_offset=total;
  1317. if(link!=vf->current_link){
  1318. /* Different link; dump entire decode machine */
  1319. _decode_clear(vf);
  1320. vf->current_link=link;
  1321. vf->current_serialno=vf->serialnos[link];
  1322. vf->ready_state=STREAMSET;
  1323. }else{
  1324. vorbis_synthesis_restart(&vf->vd);
  1325. }
  1326. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  1327. ogg_stream_pagein(&vf->os,&og);
  1328. }else
  1329. goto seek_error;
  1330. }else{
  1331. /* Bisection found our page. seek to it, update pcm offset. Easier case than
  1332. raw_seek, don't keep packets preceding granulepos. */
  1333. ogg_page og;
  1334. ogg_packet op;
  1335. /* seek */
  1336. result=_seek_helper(vf,best);
  1337. vf->pcm_offset=-1;
  1338. if(result) goto seek_error;
  1339. result=_get_next_page(vf,&og,-1);
  1340. if(result<0) goto seek_error;
  1341. if(link!=vf->current_link){
  1342. /* Different link; dump entire decode machine */
  1343. _decode_clear(vf);
  1344. vf->current_link=link;
  1345. vf->current_serialno=vf->serialnos[link];
  1346. vf->ready_state=STREAMSET;
  1347. }else{
  1348. vorbis_synthesis_restart(&vf->vd);
  1349. }
  1350. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  1351. ogg_stream_pagein(&vf->os,&og);
  1352. /* pull out all but last packet; the one with granulepos */
  1353. while(1){
  1354. result=ogg_stream_packetpeek(&vf->os,&op);
  1355. if(result==0){
  1356. /* No packet returned; we exited the bisection with 'best'
  1357. pointing to a page with a granule position, so the packet
  1358. finishing this page ('best') originated on a preceding
  1359. page. Keep fetching previous pages until we get one with
  1360. a granulepos or without the 'continued' flag set. Then
  1361. just use raw_seek for simplicity. */
  1362. /* Do not rewind past the beginning of link data; if we do,
  1363. it's either a bug or a broken stream */
  1364. result=best;
  1365. while(result>vf->dataoffsets[link]){
  1366. result=_get_prev_page(vf,result,&og);
  1367. if(result<0) goto seek_error;
  1368. if(ogg_page_serialno(&og)==vf->current_serialno &&
  1369. (ogg_page_granulepos(&og)>-1 ||
  1370. !ogg_page_continued(&og))){
  1371. return ov_raw_seek(vf,result);
  1372. }
  1373. }
  1374. }
  1375. if(result<0){
  1376. result = OV_EBADPACKET;
  1377. goto seek_error;
  1378. }
  1379. if(op.granulepos!=-1){
  1380. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  1381. if(vf->pcm_offset<0)vf->pcm_offset=0;
  1382. vf->pcm_offset+=total;
  1383. break;
  1384. }else
  1385. result=ogg_stream_packetout(&vf->os,NULL);
  1386. }
  1387. }
  1388. }
  1389. /* verify result */
  1390. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  1391. result=OV_EFAULT;
  1392. goto seek_error;
  1393. }
  1394. vf->bittrack=0.f;
  1395. vf->samptrack=0.f;
  1396. return(0);
  1397. seek_error:
  1398. /* dump machine so we're in a known state */
  1399. vf->pcm_offset=-1;
  1400. _decode_clear(vf);
  1401. return (int)result;
  1402. }
  1403. /* seek to a sample offset relative to the decompressed pcm stream
  1404. returns zero on success, nonzero on failure */
  1405. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  1406. int thisblock,lastblock=0;
  1407. int ret=ov_pcm_seek_page(vf,pos);
  1408. if(ret<0)return(ret);
  1409. if((ret=_make_decode_ready(vf)))return ret;
  1410. /* discard leading packets we don't need for the lapping of the
  1411. position we want; don't decode them */
  1412. while(1){
  1413. ogg_packet op;
  1414. ogg_page og;
  1415. int ret=ogg_stream_packetpeek(&vf->os,&op);
  1416. if(ret>0){
  1417. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  1418. if(thisblock<0){
  1419. ogg_stream_packetout(&vf->os,NULL);
  1420. continue; /* non audio packet */
  1421. }
  1422. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  1423. if(vf->pcm_offset+((thisblock+
  1424. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  1425. /* remove the packet from packet queue and track its granulepos */
  1426. ogg_stream_packetout(&vf->os,NULL);
  1427. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  1428. only tracking, no
  1429. pcm_decode */
  1430. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  1431. /* end of logical stream case is hard, especially with exact
  1432. length positioning. */
  1433. if(op.granulepos>-1){
  1434. int i;
  1435. /* always believe the stream markers */
  1436. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  1437. if(vf->pcm_offset<0)vf->pcm_offset=0;
  1438. for(i=0;i<vf->current_link;i++)
  1439. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  1440. }
  1441. lastblock=thisblock;
  1442. }else{
  1443. if(ret<0 && ret!=OV_HOLE)break;
  1444. /* suck in a new page */
  1445. if(_get_next_page(vf,&og,-1)<0)break;
  1446. if(ogg_page_bos(&og))_decode_clear(vf);
  1447. if(vf->ready_state<STREAMSET){
  1448. long serialno=ogg_page_serialno(&og);
  1449. int link;
  1450. for(link=0;link<vf->links;link++)
  1451. if(vf->serialnos[link]==serialno)break;
  1452. if(link==vf->links) continue;
  1453. vf->current_link=link;
  1454. vf->ready_state=STREAMSET;
  1455. vf->current_serialno=ogg_page_serialno(&og);
  1456. ogg_stream_reset_serialno(&vf->os,serialno);
  1457. ret=_make_decode_ready(vf);
  1458. if(ret)return ret;
  1459. lastblock=0;
  1460. }
  1461. ogg_stream_pagein(&vf->os,&og);
  1462. }
  1463. }
  1464. vf->bittrack=0.f;
  1465. vf->samptrack=0.f;
  1466. /* discard samples until we reach the desired position. Crossing a
  1467. logical bitstream boundary with abandon is OK. */
  1468. {
  1469. /* note that halfrate could be set differently in each link, but
  1470. vorbisfile encoforces all links are set or unset */
  1471. int hs=vorbis_synthesis_halfrate_p(vf->vi);
  1472. while(vf->pcm_offset<((pos>>hs)<<hs)){
  1473. ogg_int64_t target=(pos-vf->pcm_offset)>>hs;
  1474. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  1475. if(samples>target)samples=target;
  1476. vorbis_synthesis_read(&vf->vd,samples);
  1477. vf->pcm_offset+=samples<<hs;
  1478. if(samples<target)
  1479. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  1480. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  1481. }
  1482. }
  1483. return 0;
  1484. }
  1485. /* seek to a playback time relative to the decompressed pcm stream
  1486. returns zero on success, nonzero on failure */
  1487. int ov_time_seek(OggVorbis_File *vf,double seconds){
  1488. /* translate time to PCM position and call ov_pcm_seek */
  1489. int link=-1;
  1490. ogg_int64_t pcm_total=0;
  1491. double time_total=0.;
  1492. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1493. if(!vf->seekable)return(OV_ENOSEEK);
  1494. if(seconds<0)return(OV_EINVAL);
  1495. /* which bitstream section does this time offset occur in? */
  1496. for(link=0;link<vf->links;link++){
  1497. double addsec = ov_time_total(vf,link);
  1498. if(seconds<time_total+addsec)break;
  1499. time_total+=addsec;
  1500. pcm_total+=vf->pcmlengths[link*2+1];
  1501. }
  1502. if(link==vf->links)return(OV_EINVAL);
  1503. /* enough information to convert time offset to pcm offset */
  1504. {
  1505. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  1506. return(ov_pcm_seek(vf,target));
  1507. }
  1508. }
  1509. /* page-granularity version of ov_time_seek
  1510. returns zero on success, nonzero on failure */
  1511. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  1512. /* translate time to PCM position and call ov_pcm_seek */
  1513. int link=-1;
  1514. ogg_int64_t pcm_total=0;
  1515. double time_total=0.;
  1516. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1517. if(!vf->seekable)return(OV_ENOSEEK);
  1518. if(seconds<0)return(OV_EINVAL);
  1519. /* which bitstream section does this time offset occur in? */
  1520. for(link=0;link<vf->links;link++){
  1521. double addsec = ov_time_total(vf,link);
  1522. if(seconds<time_total+addsec)break;
  1523. time_total+=addsec;
  1524. pcm_total+=vf->pcmlengths[link*2+1];
  1525. }
  1526. if(link==vf->links)return(OV_EINVAL);
  1527. /* enough information to convert time offset to pcm offset */
  1528. {
  1529. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  1530. return(ov_pcm_seek_page(vf,target));
  1531. }
  1532. }
  1533. /* tell the current stream offset cursor. Note that seek followed by
  1534. tell will likely not give the set offset due to caching */
  1535. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  1536. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1537. return(vf->offset);
  1538. }
  1539. /* return PCM offset (sample) of next PCM sample to be read */
  1540. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  1541. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1542. return(vf->pcm_offset);
  1543. }
  1544. /* return time offset (seconds) of next PCM sample to be read */
  1545. double ov_time_tell(OggVorbis_File *vf){
  1546. int link=0;
  1547. ogg_int64_t pcm_total=0;
  1548. double time_total=0.f;
  1549. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1550. if(vf->seekable){
  1551. pcm_total=ov_pcm_total(vf,-1);
  1552. time_total=ov_time_total(vf,-1);
  1553. /* which bitstream section does this time offset occur in? */
  1554. for(link=vf->links-1;link>=0;link--){
  1555. pcm_total-=vf->pcmlengths[link*2+1];
  1556. time_total-=ov_time_total(vf,link);
  1557. if(vf->pcm_offset>=pcm_total)break;
  1558. }
  1559. }
  1560. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  1561. }
  1562. /* link: -1) return the vorbis_info struct for the bitstream section
  1563. currently being decoded
  1564. 0-n) to request information for a specific bitstream section
  1565. In the case of a non-seekable bitstream, any call returns the
  1566. current bitstream. NULL in the case that the machine is not
  1567. initialized */
  1568. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  1569. if(vf->seekable){
  1570. if(link<0)
  1571. if(vf->ready_state>=STREAMSET)
  1572. return vf->vi+vf->current_link;
  1573. else
  1574. return vf->vi;
  1575. else
  1576. if(link>=vf->links)
  1577. return NULL;
  1578. else
  1579. return vf->vi+link;
  1580. }else{
  1581. return vf->vi;
  1582. }
  1583. }
  1584. /* grr, strong typing, grr, no templates/inheritence, grr */
  1585. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  1586. if(vf->seekable){
  1587. if(link<0)
  1588. if(vf->ready_state>=STREAMSET)
  1589. return vf->vc+vf->current_link;
  1590. else
  1591. return vf->vc;
  1592. else
  1593. if(link>=vf->links)
  1594. return NULL;
  1595. else
  1596. return vf->vc+link;
  1597. }else{
  1598. return vf->vc;
  1599. }
  1600. }
  1601. static int host_is_big_endian() {
  1602. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  1603. unsigned char *bytewise = (unsigned char *)&pattern;
  1604. if (bytewise[0] == 0xfe) return 1;
  1605. return 0;
  1606. }
  1607. /* up to this point, everything could more or less hide the multiple
  1608. logical bitstream nature of chaining from the toplevel application
  1609. if the toplevel application didn't particularly care. However, at
  1610. the point that we actually read audio back, the multiple-section
  1611. nature must surface: Multiple bitstream sections do not necessarily
  1612. have to have the same number of channels or sampling rate.
  1613. ov_read returns the sequential logical bitstream number currently
  1614. being decoded along with the PCM data in order that the toplevel
  1615. application can take action on channel/sample rate changes. This
  1616. number will be incremented even for streamed (non-seekable) streams
  1617. (for seekable streams, it represents the actual logical bitstream
  1618. index within the physical bitstream. Note that the accessor
  1619. functions above are aware of this dichotomy).
  1620. ov_read_filter is exactly the same as ov_read except that it processes
  1621. the decoded audio data through a filter before packing it into the
  1622. requested format. This gives greater accuracy than applying a filter
  1623. after the audio has been converted into integral PCM.
  1624. input values: buffer) a buffer to hold packed PCM data for return
  1625. length) the byte length requested to be placed into buffer
  1626. bigendianp) should the data be packed LSB first (0) or
  1627. MSB first (1)
  1628. word) word size for output. currently 1 (byte) or
  1629. 2 (16 bit short)
  1630. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  1631. 0) EOF
  1632. n) number of bytes of PCM actually returned. The
  1633. below works on a packet-by-packet basis, so the
  1634. return length is not related to the 'length' passed
  1635. in, just guaranteed to fit.
  1636. *section) set to the logical bitstream number */
  1637. long ov_read_filter(OggVorbis_File *vf,char *buffer,int length,
  1638. int bigendianp,int word,int sgned,int *bitstream,
  1639. void (*filter)(float **pcm,long channels,long samples,void *filter_param),void *filter_param){
  1640. int i,j;
  1641. int host_endian = host_is_big_endian();
  1642. int hs;
  1643. float **pcm;
  1644. long samples;
  1645. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1646. if(word<=0)return(OV_EINVAL);
  1647. while(1){
  1648. if(vf->ready_state==INITSET){
  1649. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  1650. if(samples)break;
  1651. }
  1652. /* suck in another packet */
  1653. {
  1654. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  1655. if(ret==OV_EOF)
  1656. return(0);
  1657. if(ret<=0)
  1658. return(ret);
  1659. }
  1660. }
  1661. if(samples>0){
  1662. /* yay! proceed to pack data into the byte buffer */
  1663. long channels=ov_info(vf,-1)->channels;
  1664. long bytespersample=word * channels;
  1665. vorbis_fpu_control fpu;
  1666. if(channels<1||channels>255)return(OV_EINVAL);
  1667. if(samples>length/bytespersample)samples=length/bytespersample;
  1668. if(samples <= 0)
  1669. return OV_EINVAL;
  1670. /* Here. */
  1671. if(filter)
  1672. filter(pcm,channels,samples,filter_param);
  1673. /* a tight loop to pack each size */
  1674. {
  1675. int val;
  1676. if(word==1){
  1677. int off=(sgned?0:128);
  1678. vorbis_fpu_setround(&fpu);
  1679. for(j=0;j<samples;j++)
  1680. for(i=0;i<channels;i++){
  1681. val=vorbis_ftoi(pcm[i][j]*128.f);
  1682. if(val>127)val=127;
  1683. else if(val<-128)val=-128;
  1684. *buffer++=val+off;
  1685. }
  1686. vorbis_fpu_restore(fpu);
  1687. }else{
  1688. int off=(sgned?0:32768);
  1689. if(host_endian==bigendianp){
  1690. if(sgned){
  1691. vorbis_fpu_setround(&fpu);
  1692. for(i=0;i<channels;i++) { /* It's faster in this order */
  1693. float *src=pcm[i];
  1694. short *dest=((short *)buffer)+i;
  1695. for(j=0;j<samples;j++) {
  1696. val=vorbis_ftoi(src[j]*32768.f);
  1697. if(val>32767)val=32767;
  1698. else if(val<-32768)val=-32768;
  1699. *dest=val;
  1700. dest+=channels;
  1701. }
  1702. }
  1703. vorbis_fpu_restore(fpu);
  1704. }else{
  1705. vorbis_fpu_setround(&fpu);
  1706. for(i=0;i<channels;i++) {
  1707. float *src=pcm[i];
  1708. short *dest=((short *)buffer)+i;
  1709. for(j=0;j<samples;j++) {
  1710. val=vorbis_ftoi(src[j]*32768.f);
  1711. if(val>32767)val=32767;
  1712. else if(val<-32768)val=-32768;
  1713. *dest=val+off;
  1714. dest+=channels;
  1715. }
  1716. }
  1717. vorbis_fpu_restore(fpu);
  1718. }
  1719. }else if(bigendianp){
  1720. vorbis_fpu_setround(&fpu);
  1721. for(j=0;j<samples;j++)
  1722. for(i=0;i<channels;i++){
  1723. val=vorbis_ftoi(pcm[i][j]*32768.f);
  1724. if(val>32767)val=32767;
  1725. else if(val<-32768)val=-32768;
  1726. val+=off;
  1727. *buffer++=(val>>8);
  1728. *buffer++=(val&0xff);
  1729. }
  1730. vorbis_fpu_restore(fpu);
  1731. }else{
  1732. int val;
  1733. vorbis_fpu_setround(&fpu);
  1734. for(j=0;j<samples;j++)
  1735. for(i=0;i<channels;i++){
  1736. val=vorbis_ftoi(pcm[i][j]*32768.f);
  1737. if(val>32767)val=32767;
  1738. else if(val<-32768)val=-32768;
  1739. val+=off;
  1740. *buffer++=(val&0xff);
  1741. *buffer++=(val>>8);
  1742. }
  1743. vorbis_fpu_restore(fpu);
  1744. }
  1745. }
  1746. }
  1747. vorbis_synthesis_read(&vf->vd,samples);
  1748. hs=vorbis_synthesis_halfrate_p(vf->vi);
  1749. vf->pcm_offset+=(samples<<hs);
  1750. if(bitstream)*bitstream=vf->current_link;
  1751. return(samples*bytespersample);
  1752. }else{
  1753. return(samples);
  1754. }
  1755. }
  1756. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  1757. int bigendianp,int word,int sgned,int *bitstream){
  1758. return ov_read_filter(vf, buffer, length, bigendianp, word, sgned, bitstream, NULL, NULL);
  1759. }
  1760. /* input values: pcm_channels) a float vector per channel of output
  1761. length) the sample length being read by the app
  1762. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  1763. 0) EOF
  1764. n) number of samples of PCM actually returned. The
  1765. below works on a packet-by-packet basis, so the
  1766. return length is not related to the 'length' passed
  1767. in, just guaranteed to fit.
  1768. *section) set to the logical bitstream number */
  1769. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  1770. int *bitstream){
  1771. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1772. while(1){
  1773. if(vf->ready_state==INITSET){
  1774. float **pcm;
  1775. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  1776. if(samples){
  1777. int hs=vorbis_synthesis_halfrate_p(vf->vi);
  1778. if(pcm_channels)*pcm_channels=pcm;
  1779. if(samples>length)samples=length;
  1780. vorbis_synthesis_read(&vf->vd,samples);
  1781. vf->pcm_offset+=samples<<hs;
  1782. if(bitstream)*bitstream=vf->current_link;
  1783. return samples;
  1784. }
  1785. }
  1786. /* suck in another packet */
  1787. {
  1788. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  1789. if(ret==OV_EOF)return(0);
  1790. if(ret<=0)return(ret);
  1791. }
  1792. }
  1793. }
  1794. extern const float *vorbis_window(vorbis_dsp_state *v,int W);
  1795. static void _ov_splice(float **pcm,float **lappcm,
  1796. int n1, int n2,
  1797. int ch1, int ch2,
  1798. const float *w1, const float *w2){
  1799. int i,j;
  1800. const float *w=w1;
  1801. int n=n1;
  1802. if(n1>n2){
  1803. n=n2;
  1804. w=w2;
  1805. }
  1806. /* splice */
  1807. for(j=0;j<ch1 && j<ch2;j++){
  1808. float *s=lappcm[j];
  1809. float *d=pcm[j];
  1810. for(i=0;i<n;i++){
  1811. float wd=w[i]*w[i];
  1812. float ws=1.-wd;
  1813. d[i]=d[i]*wd + s[i]*ws;
  1814. }
  1815. }
  1816. /* window from zero */
  1817. for(;j<ch2;j++){
  1818. float *d=pcm[j];
  1819. for(i=0;i<n;i++){
  1820. float wd=w[i]*w[i];
  1821. d[i]=d[i]*wd;
  1822. }
  1823. }
  1824. }
  1825. /* make sure vf is INITSET */
  1826. static int _ov_initset(OggVorbis_File *vf){
  1827. while(1){
  1828. if(vf->ready_state==INITSET)break;
  1829. /* suck in another packet */
  1830. {
  1831. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  1832. if(ret<0 && ret!=OV_HOLE)return(ret);
  1833. }
  1834. }
  1835. return 0;
  1836. }
  1837. /* make sure vf is INITSET and that we have a primed buffer; if
  1838. we're crosslapping at a stream section boundary, this also makes
  1839. sure we're sanity checking against the right stream information */
  1840. static int _ov_initprime(OggVorbis_File *vf){
  1841. vorbis_dsp_state *vd=&vf->vd;
  1842. while(1){
  1843. if(vf->ready_state==INITSET)
  1844. if(vorbis_synthesis_pcmout(vd,NULL))break;
  1845. /* suck in another packet */
  1846. {
  1847. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  1848. if(ret<0 && ret!=OV_HOLE)return(ret);
  1849. }
  1850. }
  1851. return 0;
  1852. }
  1853. /* grab enough data for lapping from vf; this may be in the form of
  1854. unreturned, already-decoded pcm, remaining PCM we will need to
  1855. decode, or synthetic postextrapolation from last packets. */
  1856. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  1857. float **lappcm,int lapsize){
  1858. int lapcount=0,i;
  1859. float **pcm;
  1860. /* try first to decode the lapping data */
  1861. while(lapcount<lapsize){
  1862. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  1863. if(samples){
  1864. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  1865. for(i=0;i<vi->channels;i++)
  1866. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  1867. lapcount+=samples;
  1868. vorbis_synthesis_read(vd,samples);
  1869. }else{
  1870. /* suck in another packet */
  1871. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  1872. if(ret==OV_EOF)break;
  1873. }
  1874. }
  1875. if(lapcount<lapsize){
  1876. /* failed to get lapping data from normal decode; pry it from the
  1877. postextrapolation buffering, or the second half of the MDCT
  1878. from the last packet */
  1879. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  1880. if(samples==0){
  1881. for(i=0;i<vi->channels;i++)
  1882. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  1883. lapcount=lapsize;
  1884. }else{
  1885. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  1886. for(i=0;i<vi->channels;i++)
  1887. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  1888. lapcount+=samples;
  1889. }
  1890. }
  1891. }
  1892. /* this sets up crosslapping of a sample by using trailing data from
  1893. sample 1 and lapping it into the windowing buffer of sample 2 */
  1894. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  1895. vorbis_info *vi1,*vi2;
  1896. float **lappcm;
  1897. float **pcm;
  1898. const float *w1,*w2;
  1899. int n1,n2,i,ret,hs1,hs2;
  1900. if(vf1==vf2)return(0); /* degenerate case */
  1901. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  1902. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  1903. /* the relevant overlap buffers must be pre-checked and pre-primed
  1904. before looking at settings in the event that priming would cross
  1905. a bitstream boundary. So, do it now */
  1906. ret=_ov_initset(vf1);
  1907. if(ret)return(ret);
  1908. ret=_ov_initprime(vf2);
  1909. if(ret)return(ret);
  1910. vi1=ov_info(vf1,-1);
  1911. vi2=ov_info(vf2,-1);
  1912. hs1=ov_halfrate_p(vf1);
  1913. hs2=ov_halfrate_p(vf2);
  1914. lappcm=alloca(sizeof(*lappcm)*vi1->channels);
  1915. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  1916. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  1917. w1=vorbis_window(&vf1->vd,0);
  1918. w2=vorbis_window(&vf2->vd,0);
  1919. for(i=0;i<vi1->channels;i++)
  1920. lappcm[i]=alloca(sizeof(**lappcm)*n1);
  1921. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  1922. /* have a lapping buffer from vf1; now to splice it into the lapping
  1923. buffer of vf2 */
  1924. /* consolidate and expose the buffer. */
  1925. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  1926. #if 0
  1927. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  1928. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  1929. #endif
  1930. /* splice */
  1931. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  1932. /* done */
  1933. return(0);
  1934. }
  1935. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  1936. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  1937. vorbis_info *vi;
  1938. float **lappcm;
  1939. float **pcm;
  1940. const float *w1,*w2;
  1941. int n1,n2,ch1,ch2,hs;
  1942. int i,ret;
  1943. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1944. ret=_ov_initset(vf);
  1945. if(ret)return(ret);
  1946. vi=ov_info(vf,-1);
  1947. hs=ov_halfrate_p(vf);
  1948. ch1=vi->channels;
  1949. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  1950. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  1951. persistent; even if the decode state
  1952. from this link gets dumped, this
  1953. window array continues to exist */
  1954. lappcm=alloca(sizeof(*lappcm)*ch1);
  1955. for(i=0;i<ch1;i++)
  1956. lappcm[i]=alloca(sizeof(**lappcm)*n1);
  1957. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  1958. /* have lapping data; seek and prime the buffer */
  1959. ret=localseek(vf,pos);
  1960. if(ret)return ret;
  1961. ret=_ov_initprime(vf);
  1962. if(ret)return(ret);
  1963. /* Guard against cross-link changes; they're perfectly legal */
  1964. vi=ov_info(vf,-1);
  1965. ch2=vi->channels;
  1966. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  1967. w2=vorbis_window(&vf->vd,0);
  1968. /* consolidate and expose the buffer. */
  1969. vorbis_synthesis_lapout(&vf->vd,&pcm);
  1970. /* splice */
  1971. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  1972. /* done */
  1973. return(0);
  1974. }
  1975. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  1976. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  1977. }
  1978. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  1979. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  1980. }
  1981. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  1982. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  1983. }
  1984. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  1985. int (*localseek)(OggVorbis_File *,double)){
  1986. vorbis_info *vi;
  1987. float **lappcm;
  1988. float **pcm;
  1989. const float *w1,*w2;
  1990. int n1,n2,ch1,ch2,hs;
  1991. int i,ret;
  1992. if(vf->ready_state<OPENED)return(OV_EINVAL);
  1993. ret=_ov_initset(vf);
  1994. if(ret)return(ret);
  1995. vi=ov_info(vf,-1);
  1996. hs=ov_halfrate_p(vf);
  1997. ch1=vi->channels;
  1998. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  1999. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  2000. persistent; even if the decode state
  2001. from this link gets dumped, this
  2002. window array continues to exist */
  2003. lappcm=alloca(sizeof(*lappcm)*ch1);
  2004. for(i=0;i<ch1;i++)
  2005. lappcm[i]=alloca(sizeof(**lappcm)*n1);
  2006. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  2007. /* have lapping data; seek and prime the buffer */
  2008. ret=localseek(vf,pos);
  2009. if(ret)return ret;
  2010. ret=_ov_initprime(vf);
  2011. if(ret)return(ret);
  2012. /* Guard against cross-link changes; they're perfectly legal */
  2013. vi=ov_info(vf,-1);
  2014. ch2=vi->channels;
  2015. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  2016. w2=vorbis_window(&vf->vd,0);
  2017. /* consolidate and expose the buffer. */
  2018. vorbis_synthesis_lapout(&vf->vd,&pcm);
  2019. /* splice */
  2020. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  2021. /* done */
  2022. return(0);
  2023. }
  2024. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  2025. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  2026. }
  2027. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  2028. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  2029. }