vorbisfile.c 71 KB

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