vorbisfile.c 74 KB

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