vorbisfile.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  4. * USE, DISTRIBUTION AND REPRODUCTION OF THIS SOURCE IS GOVERNED BY *
  5. * THE GNU LESSER/LIBRARY PUBLIC LICENSE, WHICH IS INCLUDED WITH *
  6. * THIS SOURCE. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  7. * *
  8. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2000 *
  9. * by Monty <monty@xiph.org> and the XIPHOPHORUS Company *
  10. * http://www.xiph.org/ *
  11. * *
  12. ********************************************************************
  13. function: stdio-based convenience library for opening/seeking/decoding
  14. last mod: $Id: vorbisfile.c,v 1.30.2.5 2000/11/04 06:43:51 xiphmont Exp $
  15. ********************************************************************/
  16. #include <stdlib.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <math.h>
  20. #include "vorbis/codec.h"
  21. #include "vorbis/vorbisfile.h"
  22. #include "os.h"
  23. #include "misc.h"
  24. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  25. one logical bitstream arranged end to end (the only form of Ogg
  26. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  27. multiplexing] is not allowed in Vorbis) */
  28. /* A Vorbis file can be played beginning to end (streamed) without
  29. worrying ahead of time about chaining (see decoder_example.c). If
  30. we have the whole file, however, and want random access
  31. (seeking/scrubbing) or desire to know the total length/time of a
  32. file, we need to account for the possibility of chaining. */
  33. /* We can handle things a number of ways; we can determine the entire
  34. bitstream structure right off the bat, or find pieces on demand.
  35. This example determines and caches structure for the entire
  36. bitstream, but builds a virtual decoder on the fly when moving
  37. between links in the chain. */
  38. /* There are also different ways to implement seeking. Enough
  39. information exists in an Ogg bitstream to seek to
  40. sample-granularity positions in the output. Or, one can seek by
  41. picking some portion of the stream roughly in the desired area if
  42. we only want course navigation through the stream. */
  43. /*************************************************************************
  44. * Many, many internal helpers. The intention is not to be confusing;
  45. * rampant duplication and monolithic function implementation would be
  46. * harder to understand anyway. The high level functions are last. Begin
  47. * grokking near the end of the file */
  48. /* read a little more data from the file/pipe into the ogg_sync framer */
  49. #define CHUNKSIZE 4096
  50. static long _get_data(OggVorbis_File *vf){
  51. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  52. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  53. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  54. return(bytes);
  55. }
  56. /* save a tiny smidge of verbosity to make the code more readable */
  57. static void _seek_helper(OggVorbis_File *vf,long offset){
  58. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  59. vf->offset=offset;
  60. ogg_sync_reset(&vf->oy);
  61. }
  62. /* The read/seek functions track absolute position within the stream */
  63. /* from the head of the stream, get the next page. boundary specifies
  64. if the function is allowed to fetch more data from the stream (and
  65. how much) or only use internally buffered data.
  66. boundary: -1) unbounded search
  67. 0) read no additional data; use cached only
  68. n) search for a new page beginning for n bytes
  69. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  70. n) found a page at absolute offset n */
  71. static long _get_next_page(OggVorbis_File *vf,ogg_page *og,int boundary){
  72. if(boundary>0)boundary+=vf->offset;
  73. while(1){
  74. long more;
  75. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  76. more=ogg_sync_pageseek(&vf->oy,og);
  77. if(more<0){
  78. /* skipped n bytes */
  79. vf->offset-=more;
  80. }else{
  81. if(more==0){
  82. /* send more paramedics */
  83. if(!boundary)return(OV_FALSE);
  84. {
  85. long ret=_get_data(vf);
  86. if(ret==0)return(OV_EOF);
  87. if(ret<0)return(OV_EREAD);
  88. }
  89. }else{
  90. /* got a page. Return the offset at the page beginning,
  91. advance the internal offset past the page end */
  92. long ret=vf->offset;
  93. vf->offset+=more;
  94. return(ret);
  95. }
  96. }
  97. }
  98. }
  99. /* find the latest page beginning before the current stream cursor
  100. position. Much dirtier than the above as Ogg doesn't have any
  101. backward search linkage. no 'readp' as it will certainly have to
  102. read. */
  103. /* returns offset or OV_EREAD, OV_FAULT */
  104. static long _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  105. long begin=vf->offset;
  106. long ret;
  107. int offset=-1;
  108. while(offset==-1){
  109. begin-=CHUNKSIZE;
  110. _seek_helper(vf,begin);
  111. while(vf->offset<begin+CHUNKSIZE){
  112. ret=_get_next_page(vf,og,begin+CHUNKSIZE-vf->offset);
  113. if(ret==OV_EREAD)return(OV_EREAD);
  114. if(ret<0){
  115. break;
  116. }else{
  117. offset=ret;
  118. }
  119. }
  120. }
  121. /* we have the offset. Actually snork and hold the page now */
  122. _seek_helper(vf,offset);
  123. ret=_get_next_page(vf,og,CHUNKSIZE);
  124. if(ret<0)
  125. /* this shouldn't be possible */
  126. return(OV_EFAULT);
  127. return(offset);
  128. }
  129. /* finds each bitstream link one at a time using a bisection search
  130. (has to begin by knowing the offset of the lb's initial page).
  131. Recurses for each link so it can alloc the link storage after
  132. finding them all, then unroll and fill the cache at the same time */
  133. static int _bisect_forward_serialno(OggVorbis_File *vf,
  134. long begin,
  135. long searched,
  136. long end,
  137. long currentno,
  138. long m){
  139. long endsearched=end;
  140. long next=end;
  141. ogg_page og;
  142. long ret;
  143. /* the below guards against garbage seperating the last and
  144. first pages of two links. */
  145. while(searched<endsearched){
  146. long bisect;
  147. if(endsearched-searched<CHUNKSIZE){
  148. bisect=searched;
  149. }else{
  150. bisect=(searched+endsearched)/2;
  151. }
  152. _seek_helper(vf,bisect);
  153. ret=_get_next_page(vf,&og,-1);
  154. if(ret==OV_EREAD)return(OV_EREAD);
  155. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  156. endsearched=bisect;
  157. if(ret>=0)next=ret;
  158. }else{
  159. searched=ret+og.header_len+og.body_len;
  160. }
  161. }
  162. _seek_helper(vf,next);
  163. ret=_get_next_page(vf,&og,-1);
  164. if(ret==OV_EREAD)return(OV_EREAD);
  165. if(searched>=end || ret<0){
  166. vf->links=m+1;
  167. vf->offsets=_ogg_malloc((m+2)*sizeof(ogg_int64_t));
  168. vf->offsets[m+1]=searched;
  169. }else{
  170. ret=_bisect_forward_serialno(vf,next,vf->offset,
  171. end,ogg_page_serialno(&og),m+1);
  172. if(ret==OV_EREAD)return(OV_EREAD);
  173. }
  174. vf->offsets[m]=begin;
  175. return(0);
  176. }
  177. /* uses the local ogg_stream storage in vf; this is important for
  178. non-streaming input sources */
  179. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  180. long *serialno,ogg_page *og_ptr){
  181. ogg_page og;
  182. ogg_packet op;
  183. int i,ret=0;
  184. if(!og_ptr){
  185. ret=_get_next_page(vf,&og,CHUNKSIZE);
  186. if(ret==OV_EREAD)return(OV_EREAD);
  187. if(ret<0)return OV_ENOTVORBIS;
  188. og_ptr=&og;
  189. }
  190. if(serialno)*serialno=ogg_page_serialno(og_ptr);
  191. ogg_stream_init(&vf->os,ogg_page_serialno(og_ptr));
  192. /* extract the initial header from the first page and verify that the
  193. Ogg bitstream is in fact Vorbis data */
  194. vorbis_info_init(vi);
  195. vorbis_comment_init(vc);
  196. i=0;
  197. while(i<3){
  198. ogg_stream_pagein(&vf->os,og_ptr);
  199. while(i<3){
  200. int result=ogg_stream_packetout(&vf->os,&op);
  201. if(result==0)break;
  202. if(result==-1){
  203. ret=OV_EBADHEADER;
  204. goto bail_header;
  205. }
  206. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  207. goto bail_header;
  208. }
  209. i++;
  210. }
  211. if(i<3)
  212. if(_get_next_page(vf,og_ptr,1)<0){
  213. ret=OV_EBADHEADER;
  214. goto bail_header;
  215. }
  216. }
  217. return 0;
  218. bail_header:
  219. vorbis_info_clear(vi);
  220. vorbis_comment_clear(vc);
  221. ogg_stream_clear(&vf->os);
  222. return ret;
  223. }
  224. /* last step of the OggVorbis_File initialization; get all the
  225. vorbis_info structs and PCM positions. Only called by the seekable
  226. initialization (local stream storage is hacked slightly; pay
  227. attention to how that's done) */
  228. /* this is void and does not propogate errors up because we want to be
  229. able to open and use damaged bitstreams as well as we can. Just
  230. watch out for missing information for links in the OggVorbis_File
  231. struct */
  232. static void _prefetch_all_headers(OggVorbis_File *vf,vorbis_info *first_i,
  233. vorbis_comment *first_c,
  234. long dataoffset){
  235. ogg_page og;
  236. int i,ret;
  237. vf->vi=_ogg_calloc(vf->links,sizeof(vorbis_info));
  238. vf->vc=_ogg_calloc(vf->links,sizeof(vorbis_info));
  239. vf->dataoffsets=_ogg_malloc(vf->links*sizeof(ogg_int64_t));
  240. vf->pcmlengths=_ogg_malloc(vf->links*sizeof(ogg_int64_t));
  241. vf->serialnos=_ogg_malloc(vf->links*sizeof(long));
  242. for(i=0;i<vf->links;i++){
  243. if(first_i && first_c && i==0){
  244. /* we already grabbed the initial header earlier. This just
  245. saves the waste of grabbing it again */
  246. memcpy(vf->vi+i,first_i,sizeof(vorbis_info));
  247. memcpy(vf->vc+i,first_c,sizeof(vorbis_comment));
  248. vf->dataoffsets[i]=dataoffset;
  249. }else{
  250. /* seek to the location of the initial header */
  251. _seek_helper(vf,vf->offsets[i]);
  252. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  253. vf->dataoffsets[i]=-1;
  254. }else{
  255. vf->dataoffsets[i]=vf->offset;
  256. ogg_stream_clear(&vf->os);
  257. }
  258. }
  259. /* get the serial number and PCM length of this link. To do this,
  260. get the last page of the stream */
  261. {
  262. long end=vf->offsets[i+1];
  263. _seek_helper(vf,end);
  264. while(1){
  265. ret=_get_prev_page(vf,&og);
  266. if(ret<0){
  267. /* this should not be possible, actually */
  268. vorbis_info_clear(vf->vi+i);
  269. vorbis_comment_clear(vf->vc+i);
  270. break;
  271. }
  272. if(ogg_page_granulepos(&og)!=-1){
  273. vf->serialnos[i]=ogg_page_serialno(&og);
  274. vf->pcmlengths[i]=ogg_page_granulepos(&og);
  275. break;
  276. }
  277. }
  278. }
  279. }
  280. }
  281. static void _make_decode_ready(OggVorbis_File *vf){
  282. if(vf->decode_ready)return;
  283. if(vf->seekable){
  284. vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link);
  285. }else{
  286. vorbis_synthesis_init(&vf->vd,vf->vi);
  287. }
  288. vorbis_block_init(&vf->vd,&vf->vb);
  289. vf->decode_ready=1;
  290. return;
  291. }
  292. static int _open_seekable(OggVorbis_File *vf){
  293. vorbis_info initial_i;
  294. vorbis_comment initial_c;
  295. long serialno,end;
  296. int ret;
  297. long dataoffset;
  298. ogg_page og;
  299. /* is this even vorbis...? */
  300. ret=_fetch_headers(vf,&initial_i,&initial_c,&serialno,NULL);
  301. dataoffset=vf->offset;
  302. ogg_stream_clear(&vf->os);
  303. if(ret<0)return(ret);
  304. /* we can seek, so set out learning all about this file */
  305. vf->seekable=1;
  306. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  307. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  308. /* We get the offset for the last page of the physical bitstream.
  309. Most OggVorbis files will contain a single logical bitstream */
  310. end=_get_prev_page(vf,&og);
  311. if(end<0){
  312. ogg_stream_clear(&vf->os);
  313. return(end);
  314. }
  315. /* more than one logical bitstream? */
  316. if(ogg_page_serialno(&og)!=serialno){
  317. /* Chained bitstream. Bisect-search each logical bitstream
  318. section. Do so based on serial number only */
  319. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0){
  320. ogg_stream_clear(&vf->os);
  321. return(OV_EREAD);
  322. }
  323. }else{
  324. /* Only one logical bitstream */
  325. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0)){
  326. ogg_stream_clear(&vf->os);
  327. return(OV_EREAD);
  328. }
  329. }
  330. _prefetch_all_headers(vf,&initial_i,&initial_c,dataoffset);
  331. return(ov_raw_seek(vf,0));
  332. }
  333. static int _open_nonseekable(OggVorbis_File *vf){
  334. int ret;
  335. /* we cannot seek. Set up a 'single' (current) logical bitstream entry */
  336. vf->links=1;
  337. vf->vi=_ogg_calloc(vf->links,sizeof(vorbis_info));
  338. vf->vc=_ogg_calloc(vf->links,sizeof(vorbis_info));
  339. /* Try to fetch the headers, maintaining all the storage */
  340. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0)
  341. return(ret);
  342. _make_decode_ready(vf);
  343. return 0;
  344. }
  345. /* clear out the current logical bitstream decoder */
  346. static void _decode_clear(OggVorbis_File *vf){
  347. ogg_stream_clear(&vf->os);
  348. vorbis_dsp_clear(&vf->vd);
  349. vorbis_block_clear(&vf->vb);
  350. vf->decode_ready=0;
  351. vf->bittrack=0.;
  352. vf->samptrack=0.;
  353. }
  354. /* fetch and process a packet. Handles the case where we're at a
  355. bitstream boundary and dumps the decoding machine. If the decoding
  356. machine is unloaded, it loads it. It also keeps pcm_offset up to
  357. date (seek and read both use this. seek uses a special hack with
  358. readp).
  359. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  360. 0) need more data (only if readp==0)
  361. 1) got a packet
  362. */
  363. static int _process_packet(OggVorbis_File *vf,int readp){
  364. ogg_page og;
  365. /* handle one packet. Try to fetch it from current stream state */
  366. /* extract packets from page */
  367. while(1){
  368. /* process a packet if we can. If the machine isn't loaded,
  369. neither is a page */
  370. if(vf->decode_ready){
  371. ogg_packet op;
  372. int result=ogg_stream_packetout(&vf->os,&op);
  373. ogg_int64_t granulepos;
  374. if(result==-1)return(OV_HOLE); /* hole in the data. */
  375. if(result>0){
  376. /* got a packet. process it */
  377. granulepos=op.granulepos;
  378. if(!vorbis_synthesis(&vf->vb,&op)){ /* lazy check for lazy
  379. header handling. The
  380. header packets aren't
  381. audio, so if/when we
  382. submit them,
  383. vorbis_synthesis will
  384. reject them */
  385. /* suck in the synthesis data and track bitrate */
  386. {
  387. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  388. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  389. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  390. vf->bittrack+=op.bytes*8;
  391. }
  392. /* update the pcm offset. */
  393. if(granulepos!=-1 && !op.e_o_s){
  394. int link=(vf->seekable?vf->current_link:0);
  395. int i,samples;
  396. /* this packet has a pcm_offset on it (the last packet
  397. completed on a page carries the offset) After processing
  398. (above), we know the pcm position of the *last* sample
  399. ready to be returned. Find the offset of the *first*
  400. As an aside, this trick is inaccurate if we begin
  401. reading anew right at the last page; the end-of-stream
  402. granulepos declares the last frame in the stream, and the
  403. last packet of the last page may be a partial frame.
  404. So, we need a previous granulepos from an in-sequence page
  405. to have a reference point. Thus the !op.e_o_s clause
  406. above */
  407. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  408. granulepos-=samples;
  409. for(i=0;i<link;i++)
  410. granulepos+=vf->pcmlengths[i];
  411. vf->pcm_offset=granulepos;
  412. }
  413. return(1);
  414. }
  415. }
  416. }
  417. if(!readp)return(0);
  418. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* eof. leave unitialized */
  419. /* bitrate tracking; add the header's bytes here, the body bytes
  420. are done by packet above */
  421. vf->bittrack+=og.header_len*8;
  422. /* has our decoding just traversed a bitstream boundary? */
  423. if(vf->decode_ready){
  424. if(vf->current_serialno!=ogg_page_serialno(&og)){
  425. _decode_clear(vf);
  426. }
  427. }
  428. /* Do we need to load a new machine before submitting the page? */
  429. /* This is different in the seekable and non-seekable cases.
  430. In the seekable case, we already have all the header
  431. information loaded and cached; we just initialize the machine
  432. with it and continue on our merry way.
  433. In the non-seekable (streaming) case, we'll only be at a
  434. boundary if we just left the previous logical bitstream and
  435. we're now nominally at the header of the next bitstream
  436. */
  437. if(!vf->decode_ready){
  438. int link;
  439. if(vf->seekable){
  440. vf->current_serialno=ogg_page_serialno(&og);
  441. /* match the serialno to bitstream section. We use this rather than
  442. offset positions to avoid problems near logical bitstream
  443. boundaries */
  444. for(link=0;link<vf->links;link++)
  445. if(vf->serialnos[link]==vf->current_serialno)break;
  446. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  447. stream. error out,
  448. leave machine
  449. uninitialized */
  450. vf->current_link=link;
  451. ogg_stream_init(&vf->os,vf->current_serialno);
  452. ogg_stream_reset(&vf->os);
  453. }else{
  454. /* we're streaming */
  455. /* fetch the three header packets, build the info struct */
  456. _fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  457. vf->current_link++;
  458. link=0;
  459. }
  460. _make_decode_ready(vf);
  461. }
  462. ogg_stream_pagein(&vf->os,&og);
  463. }
  464. }
  465. /**********************************************************************
  466. * The helpers are over; it's all toplevel interface from here on out */
  467. /* clear out the OggVorbis_File struct */
  468. int ov_clear(OggVorbis_File *vf){
  469. if(vf){
  470. vorbis_block_clear(&vf->vb);
  471. vorbis_dsp_clear(&vf->vd);
  472. ogg_stream_clear(&vf->os);
  473. if(vf->vi && vf->links){
  474. int i;
  475. for(i=0;i<vf->links;i++){
  476. vorbis_info_clear(vf->vi+i);
  477. vorbis_comment_clear(vf->vc+i);
  478. }
  479. free(vf->vi);
  480. free(vf->vc);
  481. }
  482. if(vf->dataoffsets)free(vf->dataoffsets);
  483. if(vf->pcmlengths)free(vf->pcmlengths);
  484. if(vf->serialnos)free(vf->serialnos);
  485. if(vf->offsets)free(vf->offsets);
  486. ogg_sync_clear(&vf->oy);
  487. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  488. memset(vf,0,sizeof(OggVorbis_File));
  489. }
  490. #ifdef DEBUG_LEAKS
  491. _VDBG_dump();
  492. #endif
  493. return(0);
  494. }
  495. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  496. return fseek(f,(int)off,whence);
  497. }
  498. /* inspects the OggVorbis file and finds/documents all the logical
  499. bitstreams contained in it. Tries to be tolerant of logical
  500. bitstream sections that are truncated/woogie.
  501. return: -1) error
  502. 0) OK
  503. */
  504. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  505. ov_callbacks callbacks = {
  506. (size_t (*)(void *, size_t, size_t, void *)) fread,
  507. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  508. (int (*)(void *)) fclose,
  509. (long (*)(void *)) ftell
  510. };
  511. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  512. }
  513. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  514. ov_callbacks callbacks)
  515. {
  516. long offset=callbacks.seek_func(f,0,SEEK_CUR);
  517. int ret;
  518. memset(vf,0,sizeof(OggVorbis_File));
  519. vf->datasource=f;
  520. vf->callbacks = callbacks;
  521. /* init the framing state */
  522. ogg_sync_init(&vf->oy);
  523. /* perhaps some data was previously read into a buffer for testing
  524. against other stream types. Allow initialization from this
  525. previously read data (as we may be reading from a non-seekable
  526. stream) */
  527. if(initial){
  528. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  529. memcpy(buffer,initial,ibytes);
  530. ogg_sync_wrote(&vf->oy,ibytes);
  531. }
  532. /* can we seek? Stevens suggests the seek test was portable */
  533. if(offset!=-1){
  534. ret=_open_seekable(vf);
  535. }else{
  536. ret=_open_nonseekable(vf);
  537. }
  538. if(ret){
  539. vf->datasource=NULL;
  540. ov_clear(vf);
  541. }
  542. return(ret);
  543. }
  544. /* How many logical bitstreams in this physical bitstream? */
  545. long ov_streams(OggVorbis_File *vf){
  546. return vf->links;
  547. }
  548. /* Is the FILE * associated with vf seekable? */
  549. long ov_seekable(OggVorbis_File *vf){
  550. return vf->seekable;
  551. }
  552. /* returns the bitrate for a given logical bitstream or the entire
  553. physical bitstream. If the file is open for random access, it will
  554. find the *actual* average bitrate. If the file is streaming, it
  555. returns the nominal bitrate (if set) else the average of the
  556. upper/lower bounds (if set) else -1 (unset).
  557. If you want the actual bitrate field settings, get them from the
  558. vorbis_info structs */
  559. long ov_bitrate(OggVorbis_File *vf,int i){
  560. if(i>=vf->links)return(OV_EINVAL);
  561. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  562. if(i<0){
  563. ogg_int64_t bits=0;
  564. int i;
  565. for(i=0;i<vf->links;i++)
  566. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  567. return(rint(bits/ov_time_total(vf,-1)));
  568. }else{
  569. if(vf->seekable){
  570. /* return the actual bitrate */
  571. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  572. }else{
  573. /* return nominal if set */
  574. if(vf->vi[i].bitrate_nominal>0){
  575. return vf->vi[i].bitrate_nominal;
  576. }else{
  577. if(vf->vi[i].bitrate_upper>0){
  578. if(vf->vi[i].bitrate_lower>0){
  579. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  580. }else{
  581. return vf->vi[i].bitrate_upper;
  582. }
  583. }
  584. return(OV_FALSE);
  585. }
  586. }
  587. }
  588. }
  589. /* returns the actual bitrate since last call. returns -1 if no
  590. additional data to offer since last call (or at beginning of stream) */
  591. long ov_bitrate_instant(OggVorbis_File *vf){
  592. int link=(vf->seekable?vf->current_link:0);
  593. long ret;
  594. if(vf->samptrack==0)return(OV_FALSE);
  595. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  596. vf->bittrack=0.;
  597. vf->samptrack=0.;
  598. return(ret);
  599. }
  600. /* Guess */
  601. long ov_serialnumber(OggVorbis_File *vf,int i){
  602. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  603. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  604. if(i<0){
  605. return(vf->current_serialno);
  606. }else{
  607. return(vf->serialnos[i]);
  608. }
  609. }
  610. /* returns: total raw (compressed) length of content if i==-1
  611. raw (compressed) length of that logical bitstream for i==0 to n
  612. -1 if the stream is not seekable (we can't know the length)
  613. */
  614. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  615. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  616. if(i<0){
  617. long acc=0;
  618. int i;
  619. for(i=0;i<vf->links;i++)
  620. acc+=ov_raw_total(vf,i);
  621. return(acc);
  622. }else{
  623. return(vf->offsets[i+1]-vf->offsets[i]);
  624. }
  625. }
  626. /* returns: total PCM length (samples) of content if i==-1
  627. PCM length (samples) of that logical bitstream for i==0 to n
  628. -1 if the stream is not seekable (we can't know the length)
  629. */
  630. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  631. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  632. if(i<0){
  633. ogg_int64_t acc=0;
  634. int i;
  635. for(i=0;i<vf->links;i++)
  636. acc+=ov_pcm_total(vf,i);
  637. return(acc);
  638. }else{
  639. return(vf->pcmlengths[i]);
  640. }
  641. }
  642. /* returns: total seconds of content if i==-1
  643. seconds in that logical bitstream for i==0 to n
  644. -1 if the stream is not seekable (we can't know the length)
  645. */
  646. double ov_time_total(OggVorbis_File *vf,int i){
  647. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  648. if(i<0){
  649. double acc=0;
  650. int i;
  651. for(i=0;i<vf->links;i++)
  652. acc+=ov_time_total(vf,i);
  653. return(acc);
  654. }else{
  655. return((float)(vf->pcmlengths[i])/vf->vi[i].rate);
  656. }
  657. }
  658. /* seek to an offset relative to the *compressed* data. This also
  659. immediately sucks in and decodes pages to update the PCM cursor. It
  660. will cross a logical bitstream boundary, but only if it can't get
  661. any packets out of the tail of the bitstream we seek to (so no
  662. surprises).
  663. returns zero on success, nonzero on failure */
  664. int ov_raw_seek(OggVorbis_File *vf,long pos){
  665. int flag=0;
  666. if(!vf->seekable)return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  667. if(pos<0 || pos>vf->offsets[vf->links])return(OV_EINVAL);
  668. /* clear out decoding machine state */
  669. vf->pcm_offset=-1;
  670. _decode_clear(vf);
  671. /* seek */
  672. _seek_helper(vf,pos);
  673. /* we need to make sure the pcm_offset is set. We use the
  674. _fetch_packet helper to process one packet with readp set, then
  675. call it until it returns '0' with readp not set (the last packet
  676. from a page has the 'granulepos' field set, and that's how the
  677. helper updates the offset */
  678. while(!flag){
  679. switch(_process_packet(vf,1)){
  680. case 0:case OV_EOF:
  681. /* oh, eof. There are no packets remaining. Set the pcm offset to
  682. the end of file */
  683. vf->pcm_offset=ov_pcm_total(vf,-1);
  684. return(0);
  685. case OV_HOLE:
  686. break;
  687. case OV_EBADLINK:
  688. goto seek_error;
  689. default:
  690. /* all OK */
  691. flag=1;
  692. break;
  693. }
  694. }
  695. while(1){
  696. /* don't have to check each time through for the updated granule;
  697. it's always the last complete packet on a page */
  698. switch(_process_packet(vf,0)){
  699. case 0:case OV_EOF:
  700. /* the offset is set unless it's a bogus bitstream with no
  701. offset information but that's not our fault. We still run
  702. gracefully, we're just missing the offset */
  703. return(0);
  704. case OV_EBADLINK:
  705. goto seek_error;
  706. default:
  707. /* continue processing packets */
  708. break;
  709. }
  710. }
  711. seek_error:
  712. /* dump the machine so we're in a known state */
  713. vf->pcm_offset=-1;
  714. _decode_clear(vf);
  715. return OV_EBADLINK;
  716. }
  717. /* Page granularity seek (faster than sample granularity because we
  718. don't do the last bit of decode to find a specific sample).
  719. Seek to the last [granule marked] page preceeding the specified pos
  720. location, such that decoding past the returned point will quickly
  721. arrive at the requested position. */
  722. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  723. int link=-1;
  724. long ret;
  725. ogg_int64_t total=ov_pcm_total(vf,-1);
  726. if(!vf->seekable)return(OV_ENOSEEK);
  727. if(pos<0 || pos>total)return(OV_EINVAL);
  728. /* which bitstream section does this pcm offset occur in? */
  729. for(link=vf->links-1;link>=0;link--){
  730. total-=vf->pcmlengths[link];
  731. if(pos>=total)break;
  732. }
  733. /* search within the logical bitstream for the page with the highest
  734. pcm_pos preceeding (or equal to) pos. There is a danger here;
  735. missing pages or incorrect frame number information in the
  736. bitstream could make our task impossible. Account for that (it
  737. would be an error condition) */
  738. {
  739. ogg_int64_t target=pos-total;
  740. long end=vf->offsets[link+1];
  741. long begin=vf->offsets[link];
  742. long best=begin;
  743. ogg_page og;
  744. while(begin<end){
  745. long bisect;
  746. if(end-begin<CHUNKSIZE){
  747. bisect=begin;
  748. }else{
  749. bisect=(end+begin)/2;
  750. }
  751. _seek_helper(vf,bisect);
  752. ret=_get_next_page(vf,&og,end-bisect);
  753. switch(ret){
  754. case OV_FALSE: case OV_EOF:
  755. end=bisect;
  756. break;
  757. case OV_EREAD:
  758. goto seek_error;
  759. default:
  760. {
  761. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  762. if(granulepos<target){
  763. best=ret; /* raw offset of packet with granulepos */
  764. begin=vf->offset; /* raw offset of next packet */
  765. }else{
  766. end=bisect;
  767. }
  768. }
  769. }
  770. }
  771. /* found our page. seek to it (call raw_seek). */
  772. if((ret=ov_raw_seek(vf,best)))goto seek_error;
  773. }
  774. /* verify result */
  775. if(vf->pcm_offset>=pos || pos>ov_pcm_total(vf,-1)){
  776. ret=OV_EFAULT;
  777. goto seek_error;
  778. }
  779. return(0);
  780. seek_error:
  781. /* dump machine so we're in a known state */
  782. vf->pcm_offset=-1;
  783. _decode_clear(vf);
  784. return ret;
  785. }
  786. /* seek to a sample offset relative to the decompressed pcm stream
  787. returns zero on success, nonzero on failure */
  788. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  789. int ret=ov_pcm_seek_page(vf,pos);
  790. if(ret<0)return(ret);
  791. /* discard samples until we reach the desired position. Crossing a
  792. logical bitstream boundary with abandon is OK. */
  793. while(vf->pcm_offset<pos){
  794. float **pcm;
  795. long target=pos-vf->pcm_offset;
  796. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  797. if(samples>target)samples=target;
  798. vorbis_synthesis_read(&vf->vd,samples);
  799. vf->pcm_offset+=samples;
  800. if(samples<target)
  801. if(_process_packet(vf,1)==0)
  802. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  803. }
  804. return 0;
  805. }
  806. /* seek to a playback time relative to the decompressed pcm stream
  807. returns zero on success, nonzero on failure */
  808. int ov_time_seek(OggVorbis_File *vf,double seconds){
  809. /* translate time to PCM position and call ov_pcm_seek */
  810. int link=-1;
  811. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  812. double time_total=ov_time_total(vf,-1);
  813. if(!vf->seekable)return(OV_ENOSEEK);
  814. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  815. /* which bitstream section does this time offset occur in? */
  816. for(link=vf->links-1;link>=0;link--){
  817. pcm_total-=vf->pcmlengths[link];
  818. time_total-=ov_time_total(vf,link);
  819. if(seconds>=time_total)break;
  820. }
  821. /* enough information to convert time offset to pcm offset */
  822. {
  823. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  824. return(ov_pcm_seek(vf,target));
  825. }
  826. }
  827. /* page-granularity version of ov_time_seek
  828. returns zero on success, nonzero on failure */
  829. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  830. /* translate time to PCM position and call ov_pcm_seek */
  831. int link=-1;
  832. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  833. double time_total=ov_time_total(vf,-1);
  834. if(!vf->seekable)return(OV_ENOSEEK);
  835. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  836. /* which bitstream section does this time offset occur in? */
  837. for(link=vf->links-1;link>=0;link--){
  838. pcm_total-=vf->pcmlengths[link];
  839. time_total-=ov_time_total(vf,link);
  840. if(seconds>=time_total)break;
  841. }
  842. /* enough information to convert time offset to pcm offset */
  843. {
  844. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  845. return(ov_pcm_seek_page(vf,target));
  846. }
  847. }
  848. /* tell the current stream offset cursor. Note that seek followed by
  849. tell will likely not give the set offset due to caching */
  850. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  851. return(vf->offset);
  852. }
  853. /* return PCM offset (sample) of next PCM sample to be read */
  854. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  855. return(vf->pcm_offset);
  856. }
  857. /* return time offset (seconds) of next PCM sample to be read */
  858. double ov_time_tell(OggVorbis_File *vf){
  859. /* translate time to PCM position and call ov_pcm_seek */
  860. int link=-1;
  861. ogg_int64_t pcm_total=0;
  862. double time_total=0.;
  863. if(vf->seekable){
  864. pcm_total=ov_pcm_total(vf,-1);
  865. time_total=ov_time_total(vf,-1);
  866. /* which bitstream section does this time offset occur in? */
  867. for(link=vf->links-1;link>=0;link--){
  868. pcm_total-=vf->pcmlengths[link];
  869. time_total-=ov_time_total(vf,link);
  870. if(vf->pcm_offset>=pcm_total)break;
  871. }
  872. }
  873. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  874. }
  875. /* link: -1) return the vorbis_info struct for the bitstream section
  876. currently being decoded
  877. 0-n) to request information for a specific bitstream section
  878. In the case of a non-seekable bitstream, any call returns the
  879. current bitstream. NULL in the case that the machine is not
  880. initialized */
  881. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  882. if(vf->seekable){
  883. if(link<0)
  884. if(vf->decode_ready)
  885. return vf->vi+vf->current_link;
  886. else
  887. return NULL;
  888. else
  889. if(link>=vf->links)
  890. return NULL;
  891. else
  892. return vf->vi+link;
  893. }else{
  894. if(vf->decode_ready)
  895. return vf->vi;
  896. else
  897. return NULL;
  898. }
  899. }
  900. /* grr, strong typing, grr, no templates/inheritence, grr */
  901. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  902. if(vf->seekable){
  903. if(link<0)
  904. if(vf->decode_ready)
  905. return vf->vc+vf->current_link;
  906. else
  907. return NULL;
  908. else
  909. if(link>=vf->links)
  910. return NULL;
  911. else
  912. return vf->vc+link;
  913. }else{
  914. if(vf->decode_ready)
  915. return vf->vc;
  916. else
  917. return NULL;
  918. }
  919. }
  920. int host_is_big_endian() {
  921. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  922. unsigned char *bytewise = (unsigned char *)&pattern;
  923. if (bytewise[0] == 0xfe) return 1;
  924. return 0;
  925. }
  926. /* up to this point, everything could more or less hide the multiple
  927. logical bitstream nature of chaining from the toplevel application
  928. if the toplevel application didn't particularly care. However, at
  929. the point that we actually read audio back, the multiple-section
  930. nature must surface: Multiple bitstream sections do not necessarily
  931. have to have the same number of channels or sampling rate.
  932. ov_read returns the sequential logical bitstream number currently
  933. being decoded along with the PCM data in order that the toplevel
  934. application can take action on channel/sample rate changes. This
  935. number will be incremented even for streamed (non-seekable) streams
  936. (for seekable streams, it represents the actual logical bitstream
  937. index within the physical bitstream. Note that the accessor
  938. functions above are aware of this dichotomy).
  939. input values: buffer) a buffer to hold packed PCM data for return
  940. length) the byte length requested to be placed into buffer
  941. bigendianp) should the data be packed LSB first (0) or
  942. MSB first (1)
  943. word) word size for output. currently 1 (byte) or
  944. 2 (16 bit short)
  945. return values: -1) error/hole in data (OV_HOLE)
  946. 0) EOF
  947. n) number of bytes of PCM actually returned. The
  948. below works on a packet-by-packet basis, so the
  949. return length is not related to the 'length' passed
  950. in, just guaranteed to fit.
  951. *section) set to the logical bitstream number */
  952. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  953. int bigendianp,int word,int sgned,int *bitstream){
  954. int i,j;
  955. int host_endian = host_is_big_endian();
  956. while(1){
  957. if(vf->decode_ready){
  958. float **pcm;
  959. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  960. if(samples){
  961. /* yay! proceed to pack data into the byte buffer */
  962. long channels=ov_info(vf,-1)->channels;
  963. long bytespersample=word * channels;
  964. vorbis_fpu_control fpu;
  965. if(samples>length/bytespersample)samples=length/bytespersample;
  966. /* a tight loop to pack each size */
  967. {
  968. int val;
  969. if(word==1){
  970. int off=(sgned?0:128);
  971. vorbis_fpu_setround(&fpu);
  972. for(j=0;j<samples;j++)
  973. for(i=0;i<channels;i++){
  974. val=vorbis_ftoi(pcm[i][j]*128.);
  975. if(val>127)val=127;
  976. else if(val<-128)val=-128;
  977. *buffer++=val+off;
  978. }
  979. vorbis_fpu_restore(fpu);
  980. }else{
  981. int off=(sgned?0:32768);
  982. if(host_endian==bigendianp){
  983. if(sgned){
  984. vorbis_fpu_setround(&fpu);
  985. for(i=0;i<channels;i++) { /* It's faster in this order */
  986. float *src=pcm[i];
  987. short *dest=((short *)buffer)+i;
  988. for(j=0;j<samples;j++) {
  989. val=vorbis_ftoi(src[j]*32768.);
  990. if(val>32767)val=32767;
  991. else if(val<-32768)val=-32768;
  992. *dest=val;
  993. dest+=channels;
  994. }
  995. }
  996. vorbis_fpu_restore(fpu);
  997. }else{
  998. vorbis_fpu_setround(&fpu);
  999. for(i=0;i<channels;i++) {
  1000. float *src=pcm[i];
  1001. short *dest=((short *)buffer)+i;
  1002. for(j=0;j<samples;j++) {
  1003. val=vorbis_ftoi(src[j]*32768.);
  1004. if(val>32767)val=32767;
  1005. else if(val<-32768)val=-32768;
  1006. *dest=val+off;
  1007. dest+=channels;
  1008. }
  1009. }
  1010. vorbis_fpu_restore(fpu);
  1011. }
  1012. }else if(bigendianp){
  1013. vorbis_fpu_setround(&fpu);
  1014. for(j=0;j<samples;j++)
  1015. for(i=0;i<channels;i++){
  1016. val=vorbis_ftoi(pcm[i][j]*32768.);
  1017. if(val>32767)val=32767;
  1018. else if(val<-32768)val=-32768;
  1019. val+=off;
  1020. *buffer++=(val>>8);
  1021. *buffer++=(val&0xff);
  1022. }
  1023. vorbis_fpu_restore(fpu);
  1024. }else{
  1025. int val;
  1026. vorbis_fpu_setround(&fpu);
  1027. for(j=0;j<samples;j++)
  1028. for(i=0;i<channels;i++){
  1029. val=vorbis_ftoi(pcm[i][j]*32768.);
  1030. if(val>32767)val=32767;
  1031. else if(val<-32768)val=-32768;
  1032. val+=off;
  1033. *buffer++=(val&0xff);
  1034. *buffer++=(val>>8);
  1035. }
  1036. vorbis_fpu_restore(fpu);
  1037. }
  1038. }
  1039. }
  1040. vorbis_synthesis_read(&vf->vd,samples);
  1041. vf->pcm_offset+=samples;
  1042. if(bitstream)*bitstream=vf->current_link;
  1043. return(samples*bytespersample);
  1044. }
  1045. }
  1046. /* suck in another packet */
  1047. switch(_process_packet(vf,1)){
  1048. case 0:case OV_EOF:
  1049. return(0);
  1050. case OV_HOLE:
  1051. return(OV_HOLE);
  1052. case OV_EBADLINK:
  1053. return(OV_EBADLINK);
  1054. }
  1055. }
  1056. }