1 /********************************************************************
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. *
8 * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2009 *
9 * by the Xiph.Org Foundation http://www.xiph.org/ *
11 ********************************************************************
13 function: stdio-based convenience library for opening/seeking/decoding
16 ********************************************************************/
24 #include "vorbis/codec.h"
26 /* we don't need or want the static callback symbols here */
27 #define OV_EXCLUDE_STATIC_CALLBACKS
28 #include "vorbis/vorbisfile.h"
33 /* A 'chained bitstream' is a Vorbis bitstream that contains more than
34 one logical bitstream arranged end to end (the only form of Ogg
35 multiplexing allowed in a Vorbis bitstream; grouping [parallel
36 multiplexing] is not allowed in Vorbis) */
38 /* A Vorbis file can be played beginning to end (streamed) without
39 worrying ahead of time about chaining (see decoder_example.c). If
40 we have the whole file, however, and want random access
41 (seeking/scrubbing) or desire to know the total length/time of a
42 file, we need to account for the possibility of chaining. */
44 /* We can handle things a number of ways; we can determine the entire
45 bitstream structure right off the bat, or find pieces on demand.
46 This example determines and caches structure for the entire
47 bitstream, but builds a virtual decoder on the fly when moving
48 between links in the chain. */
50 /* There are also different ways to implement seeking. Enough
51 information exists in an Ogg bitstream to seek to
52 sample-granularity positions in the output. Or, one can seek by
53 picking some portion of the stream roughly in the desired area if
54 we only want coarse navigation through the stream. */
56 /*************************************************************************
57 * Many, many internal helpers. The intention is not to be confusing;
58 * rampant duplication and monolithic function implementation would be
59 * harder to understand anyway. The high level functions are last. Begin
60 * grokking near the end of the file */
62 /* read a little more data from the file/pipe into the ogg_sync framer
64 #define CHUNKSIZE 65536 /* greater-than-page-size granularity seeking */
65 #define READSIZE 2048 /* a smaller read size is needed for low-rate streaming. */
67 static long _get_data(OggVorbis_File *vf){
69 if(!(vf->callbacks.read_func))return(-1);
71 char *buffer=ogg_sync_buffer(&vf->oy,READSIZE);
72 long bytes=(vf->callbacks.read_func)(buffer,1,READSIZE,vf->datasource);
73 if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
74 if(bytes==0 && errno)return(-1);
80 /* save a tiny smidge of verbosity to make the code more readable */
81 static int _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
83 if(!(vf->callbacks.seek_func)||
84 (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET) == -1)
87 ogg_sync_reset(&vf->oy);
89 /* shouldn't happen unless someone writes a broken callback */
95 /* The read/seek functions track absolute position within the stream */
97 /* from the head of the stream, get the next page. boundary specifies
98 if the function is allowed to fetch more data from the stream (and
99 how much) or only use internally buffered data.
101 boundary: -1) unbounded search
102 0) read no additional data; use cached only
103 n) search for a new page beginning for n bytes
105 return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
106 n) found a page at absolute offset n */
108 static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
109 ogg_int64_t boundary){
110 if(boundary>0)boundary+=vf->offset;
114 if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
115 more=ogg_sync_pageseek(&vf->oy,og);
118 /* skipped n bytes */
122 /* send more paramedics */
123 if(!boundary)return(OV_FALSE);
125 long ret=_get_data(vf);
126 if(ret==0)return(OV_EOF);
127 if(ret<0)return(OV_EREAD);
130 /* got a page. Return the offset at the page beginning,
131 advance the internal offset past the page end */
132 ogg_int64_t ret=vf->offset;
141 /* find the latest page beginning before the current stream cursor
142 position. Much dirtier than the above as Ogg doesn't have any
143 backward search linkage. no 'readp' as it will certainly have to
145 /* returns offset or OV_EREAD, OV_FAULT */
146 static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
147 ogg_int64_t begin=vf->offset;
148 ogg_int64_t end=begin;
150 ogg_int64_t offset=-1;
157 ret=_seek_helper(vf,begin);
160 while(vf->offset<end){
161 memset(og,0,sizeof(*og));
162 ret=_get_next_page(vf,og,end-vf->offset);
163 if(ret==OV_EREAD)return(OV_EREAD);
172 /* In a fully compliant, non-multiplexed stream, we'll still be
173 holding the last page. In multiplexed (or noncompliant streams),
174 we will probably have to re-read the last page we saw */
175 if(og->header_len==0){
176 ret=_seek_helper(vf,offset);
179 ret=_get_next_page(vf,og,CHUNKSIZE);
181 /* this shouldn't be possible */
188 static void _add_serialno(ogg_page *og,long **serialno_list, int *n){
189 long s = ogg_page_serialno(og);
193 *serialno_list = _ogg_realloc(*serialno_list, sizeof(**serialno_list)*(*n));
195 *serialno_list = _ogg_malloc(sizeof(**serialno_list));
198 (*serialno_list)[(*n)-1] = s;
201 /* returns nonzero if found */
202 static int _lookup_serialno(long s, long *serialno_list, int n){
205 if(*serialno_list == s) return 1;
212 static int _lookup_page_serialno(ogg_page *og, long *serialno_list, int n){
213 long s = ogg_page_serialno(og);
214 return _lookup_serialno(s,serialno_list,n);
217 /* performs the same search as _get_prev_page, but prefers pages of
218 the specified serial number. If a page of the specified serialno is
219 spotted during the seek-back-and-read-forward, it will return the
220 info of last page of the matching serial number instead of the very
221 last page. If no page of the specified serialno is seen, it will
222 return the info of last page and alter *serialno. */
223 static ogg_int64_t _get_prev_page_serial(OggVorbis_File *vf,
224 long *serial_list, int serial_n,
225 int *serialno, ogg_int64_t *granpos){
227 ogg_int64_t begin=vf->offset;
228 ogg_int64_t end=begin;
231 ogg_int64_t prefoffset=-1;
232 ogg_int64_t offset=-1;
233 ogg_int64_t ret_serialno=-1;
234 ogg_int64_t ret_gran=-1;
241 ret=_seek_helper(vf,begin);
244 while(vf->offset<end){
245 ret=_get_next_page(vf,&og,end-vf->offset);
246 if(ret==OV_EREAD)return(OV_EREAD);
250 ret_serialno=ogg_page_serialno(&og);
251 ret_gran=ogg_page_granulepos(&og);
254 if(ret_serialno == *serialno){
259 if(!_lookup_serialno(ret_serialno,serial_list,serial_n)){
260 /* we fell off the end of the link, which means we seeked
261 back too far and shouldn't have been looking in that link
262 to begin with. If we found the preferred serial number,
263 forget that we saw it. */
270 /* we're not interested in the page... just the serialno and granpos. */
271 if(prefoffset>=0)return(prefoffset);
273 *serialno = ret_serialno;
279 /* uses the local ogg_stream storage in vf; this is important for
280 non-streaming input sources */
281 static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
282 long **serialno_list, int *serialno_n,
290 ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
291 if(llret==OV_EREAD)return(OV_EREAD);
292 if(llret<0)return(OV_ENOTVORBIS);
296 vorbis_info_init(vi);
297 vorbis_comment_init(vc);
298 vf->ready_state=OPENED;
300 /* extract the serialnos of all BOS pages + the first set of vorbis
301 headers we see in the link */
303 while(ogg_page_bos(og_ptr)){
305 if(_lookup_page_serialno(og_ptr,*serialno_list,*serialno_n)){
306 /* a dupe serialnumber in an initial header packet set == invalid stream */
307 if(*serialno_list)_ogg_free(*serialno_list);
314 _add_serialno(og_ptr,serialno_list,serialno_n);
317 if(vf->ready_state<STREAMSET){
318 /* we don't have a vorbis stream in this link yet, so begin
319 prospective stream setup. We need a stream to get packets */
320 ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
321 ogg_stream_pagein(&vf->os,og_ptr);
323 if(ogg_stream_packetout(&vf->os,&op) > 0 &&
324 vorbis_synthesis_idheader(&op)){
325 /* vorbis header; continue setup */
326 vf->ready_state=STREAMSET;
327 if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
336 ogg_int64_t llret=_get_next_page(vf,og_ptr,CHUNKSIZE);
346 /* if this page also belongs to our vorbis stream, submit it and break */
347 if(vf->ready_state==STREAMSET &&
348 vf->os.serialno == ogg_page_serialno(og_ptr)){
349 ogg_stream_pagein(&vf->os,og_ptr);
355 if(vf->ready_state!=STREAMSET){
363 while(i<2){ /* get a page loop */
365 while(i<2){ /* get a packet loop */
367 int result=ogg_stream_packetout(&vf->os,&op);
374 if((ret=vorbis_synthesis_headerin(vi,vc,&op)))
381 if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
386 /* if this page belongs to the correct stream, go parse it */
387 if(vf->os.serialno == ogg_page_serialno(og_ptr)){
388 ogg_stream_pagein(&vf->os,og_ptr);
392 /* if we never see the final vorbis headers before the link
394 if(ogg_page_bos(og_ptr)){
402 /* otherwise, keep looking */
410 vorbis_info_clear(vi);
411 vorbis_comment_clear(vc);
412 vf->ready_state=OPENED;
417 /* Starting from current cursor position, get initial PCM offset of
418 next page. Consumes the page in the process without decoding
419 audio, however this is only called during stream parsing upon
421 static ogg_int64_t _initial_pcmoffset(OggVorbis_File *vf, vorbis_info *vi){
423 ogg_int64_t accumulated=0;
426 int serialno = vf->os.serialno;
430 if(_get_next_page(vf,&og,-1)<0)
431 break; /* should not be possible unless the file is truncated/mangled */
433 if(ogg_page_bos(&og)) break;
434 if(ogg_page_serialno(&og)!=serialno) continue;
436 /* count blocksizes of all frames in the page */
437 ogg_stream_pagein(&vf->os,&og);
438 while((result=ogg_stream_packetout(&vf->os,&op))){
439 if(result>0){ /* ignore holes */
440 long thisblock=vorbis_packet_blocksize(vi,&op);
442 accumulated+=(lastblock+thisblock)>>2;
447 if(ogg_page_granulepos(&og)!=-1){
448 /* pcm offset of last packet on the first audio page */
449 accumulated= ogg_page_granulepos(&og)-accumulated;
454 /* less than zero? This is a stream with samples trimmed off
455 the beginning, a normal occurrence; set the offset to zero */
456 if(accumulated<0)accumulated=0;
461 /* finds each bitstream link one at a time using a bisection search
462 (has to begin by knowing the offset of the lb's initial page).
463 Recurses for each link so it can alloc the link storage after
464 finding them all, then unroll and fill the cache at the same time */
465 static int _bisect_forward_serialno(OggVorbis_File *vf,
467 ogg_int64_t searched,
471 long *currentno_list,
474 ogg_int64_t pcmoffset;
475 ogg_int64_t dataoffset=searched;
476 ogg_int64_t endsearched=end;
477 ogg_int64_t next=end;
478 ogg_int64_t searchgran=-1;
480 ogg_int64_t ret,last;
481 int serialno = vf->os.serialno;
484 we have the headers and serialnos for the link beginning at 'begin'
485 we have the offset and granpos of the last page in the file (potentially
486 not a page we care about)
489 /* Is the last page in our list of current serialnumbers? */
490 if(_lookup_serialno(endserial,currentno_list,currentnos)){
492 /* last page is in the starting serialno list, so we've bisected
493 down to (or just started with) a single link. Now we need to
494 find the last vorbis page belonging to the first vorbis stream
497 while(endserial != serialno){
498 endserial = serialno;
499 vf->offset=_get_prev_page_serial(vf,currentno_list,currentnos,&endserial,&endgran);
503 if(vf->offsets)_ogg_free(vf->offsets);
504 if(vf->serialnos)_ogg_free(vf->serialnos);
505 if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
507 vf->offsets=_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
508 vf->vi=_ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
509 vf->vc=_ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
510 vf->serialnos=_ogg_malloc(vf->links*sizeof(*vf->serialnos));
511 vf->dataoffsets=_ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
512 vf->pcmlengths=_ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
514 vf->offsets[m+1]=end;
515 vf->offsets[m]=begin;
516 vf->pcmlengths[m*2+1]=endgran;
520 long *next_serialno_list=NULL;
521 int next_serialnos=0;
525 /* the below guards against garbage seperating the last and
526 first pages of two links. */
527 while(searched<endsearched){
530 if(endsearched-searched<CHUNKSIZE){
533 bisect=(searched+endsearched)/2;
536 if(bisect != vf->offset){
537 ret=_seek_helper(vf,bisect);
541 last=_get_next_page(vf,&og,-1);
542 if(last==OV_EREAD)return(OV_EREAD);
543 if(last<0 || !_lookup_page_serialno(&og,currentno_list,currentnos)){
545 if(last>=0)next=last;
551 /* Bisection point found */
553 /* for the time being, fetch end PCM offset the simple way */
555 int testserial = serialno+1;
557 while(testserial != serialno){
558 testserial = serialno;
559 vf->offset=_get_prev_page_serial(vf,currentno_list,currentnos,&testserial,&searchgran);
563 if(vf->offset!=next){
564 ret=_seek_helper(vf,next);
568 ret=_fetch_headers(vf,&vi,&vc,&next_serialno_list,&next_serialnos,NULL);
570 serialno = vf->os.serialno;
571 dataoffset = vf->offset;
573 /* this will consume a page, however the next bistection always
574 starts with a raw seek */
575 pcmoffset = _initial_pcmoffset(vf,&vi);
577 ret=_bisect_forward_serialno(vf,next,vf->offset,end,endgran,endserial,
578 next_serialno_list,next_serialnos,m+1);
581 if(next_serialno_list)_ogg_free(next_serialno_list);
583 vf->offsets[m+1]=next;
584 vf->serialnos[m+1]=serialno;
585 vf->dataoffsets[m+1]=dataoffset;
590 vf->pcmlengths[m*2+1]=searchgran;
591 vf->pcmlengths[m*2+2]=pcmoffset;
592 vf->pcmlengths[m*2+3]-=pcmoffset;
598 static int _make_decode_ready(OggVorbis_File *vf){
599 if(vf->ready_state>STREAMSET)return 0;
600 if(vf->ready_state<STREAMSET)return OV_EFAULT;
602 if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
605 if(vorbis_synthesis_init(&vf->vd,vf->vi))
608 vorbis_block_init(&vf->vd,&vf->vb);
609 vf->ready_state=INITSET;
615 static int _open_seekable2(OggVorbis_File *vf){
616 ogg_int64_t dataoffset=vf->dataoffsets[0],end,endgran=-1;
617 int endserial=vf->os.serialno;
618 int serialno=vf->os.serialno;
620 /* we're partially open and have a first link header state in
623 /* fetch initial PCM offset */
624 ogg_int64_t pcmoffset = _initial_pcmoffset(vf,vf->vi);
626 /* we can seek, so set out learning all about this file */
627 if(vf->callbacks.seek_func && vf->callbacks.tell_func){
628 (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
629 vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
631 vf->offset=vf->end=-1;
634 /* If seek_func is implemented, tell_func must also be implemented */
635 if(vf->end==-1) return(OV_EINVAL);
637 /* Get the offset of the last page of the physical bitstream, or, if
638 we're lucky the last vorbis page of this link as most OggVorbis
639 files will contain a single logical bitstream */
640 end=_get_prev_page_serial(vf,vf->serialnos+2,vf->serialnos[1],&endserial,&endgran);
641 if(end<0)return(end);
643 /* now determine bitstream structure recursively */
644 if(_bisect_forward_serialno(vf,0,dataoffset,vf->offset,endgran,endserial,
645 vf->serialnos+2,vf->serialnos[1],0)<0)return(OV_EREAD);
648 vf->serialnos[0]=serialno;
649 vf->dataoffsets[0]=dataoffset;
650 vf->pcmlengths[0]=pcmoffset;
651 vf->pcmlengths[1]-=pcmoffset;
653 return(ov_raw_seek(vf,dataoffset));
656 /* clear out the current logical bitstream decoder */
657 static void _decode_clear(OggVorbis_File *vf){
658 vorbis_dsp_clear(&vf->vd);
659 vorbis_block_clear(&vf->vb);
660 vf->ready_state=OPENED;
663 /* fetch and process a packet. Handles the case where we're at a
664 bitstream boundary and dumps the decoding machine. If the decoding
665 machine is unloaded, it loads it. It also keeps pcm_offset up to
666 date (seek and read both use this. seek uses a special hack with
669 return: <0) error, OV_HOLE (lost packet) or OV_EOF
670 0) need more data (only if readp==0)
674 static int _fetch_and_process_packet(OggVorbis_File *vf,
680 /* handle one packet. Try to fetch it from current stream state */
681 /* extract packets from page */
684 if(vf->ready_state==STREAMSET){
685 int ret=_make_decode_ready(vf);
689 /* process a packet if we can. */
691 if(vf->ready_state==INITSET){
694 ogg_packet *op_ptr=(op_in?op_in:&op);
695 int result=ogg_stream_packetout(&vf->os,op_ptr);
696 ogg_int64_t granulepos;
699 if(result==-1)return(OV_HOLE); /* hole in the data. */
701 /* got a packet. process it */
702 granulepos=op_ptr->granulepos;
703 if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
705 header packets aren't
708 vorbis_synthesis will
711 /* suck in the synthesis data and track bitrate */
713 int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
714 /* for proper use of libvorbis within libvorbisfile,
715 oldsamples will always be zero. */
716 if(oldsamples)return(OV_EFAULT);
718 vorbis_synthesis_blockin(&vf->vd,&vf->vb);
719 vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
720 vf->bittrack+=op_ptr->bytes*8;
723 /* update the pcm offset. */
724 if(granulepos!=-1 && !op_ptr->e_o_s){
725 int link=(vf->seekable?vf->current_link:0);
728 /* this packet has a pcm_offset on it (the last packet
729 completed on a page carries the offset) After processing
730 (above), we know the pcm position of the *last* sample
731 ready to be returned. Find the offset of the *first*
733 As an aside, this trick is inaccurate if we begin
734 reading anew right at the last page; the end-of-stream
735 granulepos declares the last frame in the stream, and the
736 last packet of the last page may be a partial frame.
737 So, we need a previous granulepos from an in-sequence page
738 to have a reference point. Thus the !op_ptr->e_o_s clause
741 if(vf->seekable && link>0)
742 granulepos-=vf->pcmlengths[link*2];
743 if(granulepos<0)granulepos=0; /* actually, this
744 shouldn't be possible
745 here unless the stream
748 samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
752 granulepos+=vf->pcmlengths[i*2+1];
753 vf->pcm_offset=granulepos;
763 if(vf->ready_state>=OPENED){
767 /* the loop is not strictly necessary, but there's no sense in
768 doing the extra checks of the larger loop for the common
769 case in a multiplexed bistream where the page is simply
770 part of a different logical bitstream; keep reading until
771 we get one with the correct serialno */
774 if((ret=_get_next_page(vf,&og,-1))<0){
775 return(OV_EOF); /* eof. leave unitialized */
778 /* bitrate tracking; add the header's bytes here, the body bytes
779 are done by packet above */
780 vf->bittrack+=og.header_len*8;
782 if(vf->ready_state==INITSET){
783 if(vf->current_serialno!=ogg_page_serialno(&og)){
785 /* two possibilities:
786 1) our decoding just traversed a bitstream boundary
787 2) another stream is multiplexed into this logical section */
789 if(ogg_page_bos(&og)){
797 vorbis_info_clear(vf->vi);
798 vorbis_comment_clear(vf->vc);
803 continue; /* possibility #2 */
811 /* Do we need to load a new machine before submitting the page? */
812 /* This is different in the seekable and non-seekable cases.
814 In the seekable case, we already have all the header
815 information loaded and cached; we just initialize the machine
816 with it and continue on our merry way.
818 In the non-seekable (streaming) case, we'll only be at a
819 boundary if we just left the previous logical bitstream and
820 we're now nominally at the header of the next bitstream
823 if(vf->ready_state!=INITSET){
826 if(vf->ready_state<STREAMSET){
828 long serialno = ogg_page_serialno(&og);
830 /* match the serialno to bitstream section. We use this rather than
831 offset positions to avoid problems near logical bitstream
834 for(link=0;link<vf->links;link++)
835 if(vf->serialnos[link]==serialno)break;
837 if(link==vf->links) continue; /* not the desired Vorbis
838 bitstream section; keep
841 vf->current_serialno=serialno;
842 vf->current_link=link;
844 ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
845 vf->ready_state=STREAMSET;
848 /* we're streaming */
849 /* fetch the three header packets, build the info struct */
851 int ret=_fetch_headers(vf,vf->vi,vf->vc,NULL,NULL,&og);
853 vf->current_serialno=vf->os.serialno;
860 /* the buffered page is the data we want, and we're ready for it;
861 add it to the stream state */
862 ogg_stream_pagein(&vf->os,&og);
867 /* if, eg, 64 bit stdio is configured by default, this will build with
869 static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
870 if(f==NULL)return(-1);
871 return fseek(f,off,whence);
874 static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
875 long ibytes, ov_callbacks callbacks){
876 int offsettest=((f && callbacks.seek_func)?callbacks.seek_func(f,0,SEEK_CUR):-1);
877 long *serialno_list=NULL;
878 int serialno_list_size=0;
881 memset(vf,0,sizeof(*vf));
883 vf->callbacks = callbacks;
885 /* init the framing state */
886 ogg_sync_init(&vf->oy);
888 /* perhaps some data was previously read into a buffer for testing
889 against other stream types. Allow initialization from this
890 previously read data (especially as we may be reading from a
891 non-seekable stream) */
893 char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
894 memcpy(buffer,initial,ibytes);
895 ogg_sync_wrote(&vf->oy,ibytes);
898 /* can we seek? Stevens suggests the seek test was portable */
899 if(offsettest!=-1)vf->seekable=1;
901 /* No seeking yet; Set up a 'single' (current) logical bitstream
902 entry for partial open */
904 vf->vi=_ogg_calloc(vf->links,sizeof(*vf->vi));
905 vf->vc=_ogg_calloc(vf->links,sizeof(*vf->vc));
906 ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
908 /* Fetch all BOS pages, store the vorbis header and all seen serial
909 numbers, load subsequent vorbis setup headers */
910 if((ret=_fetch_headers(vf,vf->vi,vf->vc,&serialno_list,&serialno_list_size,NULL))<0){
914 /* serial number list for first link needs to be held somewhere
915 for second stage of seekable stream open; this saves having to
916 seek/reread first link's serialnumber data then. */
917 vf->serialnos=_ogg_calloc(serialno_list_size+2,sizeof(*vf->serialnos));
918 vf->serialnos[0]=vf->current_serialno;
919 vf->serialnos[1]=serialno_list_size;
920 memcpy(vf->serialnos+2,serialno_list,serialno_list_size*sizeof(*vf->serialnos));
922 vf->offsets=_ogg_calloc(1,sizeof(*vf->offsets));
923 vf->dataoffsets=_ogg_calloc(1,sizeof(*vf->dataoffsets));
925 vf->dataoffsets[0]=vf->offset;
926 vf->current_serialno=vf->os.serialno;
928 vf->ready_state=PARTOPEN;
930 if(serialno_list)_ogg_free(serialno_list);
934 static int _ov_open2(OggVorbis_File *vf){
935 if(vf->ready_state != PARTOPEN) return OV_EINVAL;
936 vf->ready_state=OPENED;
938 int ret=_open_seekable2(vf);
945 vf->ready_state=STREAMSET;
951 /* clear out the OggVorbis_File struct */
952 int ov_clear(OggVorbis_File *vf){
954 vorbis_block_clear(&vf->vb);
955 vorbis_dsp_clear(&vf->vd);
956 ogg_stream_clear(&vf->os);
958 if(vf->vi && vf->links){
960 for(i=0;i<vf->links;i++){
961 vorbis_info_clear(vf->vi+i);
962 vorbis_comment_clear(vf->vc+i);
967 if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
968 if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
969 if(vf->serialnos)_ogg_free(vf->serialnos);
970 if(vf->offsets)_ogg_free(vf->offsets);
971 ogg_sync_clear(&vf->oy);
972 if(vf->datasource && vf->callbacks.close_func)
973 (vf->callbacks.close_func)(vf->datasource);
974 memset(vf,0,sizeof(*vf));
982 /* inspects the OggVorbis file and finds/documents all the logical
983 bitstreams contained in it. Tries to be tolerant of logical
984 bitstream sections that are truncated/woogie.
990 int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
991 ov_callbacks callbacks){
992 int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
994 return _ov_open2(vf);
997 int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
998 ov_callbacks callbacks = {
999 (size_t (*)(void *, size_t, size_t, void *)) fread,
1000 (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
1001 (int (*)(void *)) fclose,
1002 (long (*)(void *)) ftell
1005 return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
1008 int ov_fopen(char *path,OggVorbis_File *vf){
1010 FILE *f = fopen(path,"rb");
1013 ret = ov_open(f,vf,NULL,0);
1019 /* cheap hack for game usage where downsampling is desirable; there's
1020 no need for SRC as we can just do it cheaply in libvorbis. */
1022 int ov_halfrate(OggVorbis_File *vf,int flag){
1024 if(vf->vi==NULL)return OV_EINVAL;
1025 if(!vf->seekable)return OV_EINVAL;
1026 if(vf->ready_state>=STREAMSET)
1027 _decode_clear(vf); /* clear out stream state; later on libvorbis
1028 will be able to swap this on the fly, but
1029 for now dumping the decode machine is needed
1030 to reinit the MDCT lookups. 1.1 libvorbis
1031 is planned to be able to switch on the fly */
1033 for(i=0;i<vf->links;i++){
1034 if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
1042 int ov_halfrate_p(OggVorbis_File *vf){
1043 if(vf->vi==NULL)return OV_EINVAL;
1044 return vorbis_synthesis_halfrate_p(vf->vi);
1047 /* Only partially open the vorbis file; test for Vorbisness, and load
1048 the headers for the first chain. Do not seek (although test for
1049 seekability). Use ov_test_open to finish opening the file, else
1050 ov_clear to close/free it. Same return codes as open. */
1052 int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
1053 ov_callbacks callbacks)
1055 return _ov_open1(f,vf,initial,ibytes,callbacks);
1058 int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
1059 ov_callbacks callbacks = {
1060 (size_t (*)(void *, size_t, size_t, void *)) fread,
1061 (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
1062 (int (*)(void *)) fclose,
1063 (long (*)(void *)) ftell
1066 return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
1069 int ov_test_open(OggVorbis_File *vf){
1070 if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
1071 return _ov_open2(vf);
1074 /* How many logical bitstreams in this physical bitstream? */
1075 long ov_streams(OggVorbis_File *vf){
1079 /* Is the FILE * associated with vf seekable? */
1080 long ov_seekable(OggVorbis_File *vf){
1081 return vf->seekable;
1084 /* returns the bitrate for a given logical bitstream or the entire
1085 physical bitstream. If the file is open for random access, it will
1086 find the *actual* average bitrate. If the file is streaming, it
1087 returns the nominal bitrate (if set) else the average of the
1088 upper/lower bounds (if set) else -1 (unset).
1090 If you want the actual bitrate field settings, get them from the
1091 vorbis_info structs */
1093 long ov_bitrate(OggVorbis_File *vf,int i){
1094 if(vf->ready_state<OPENED)return(OV_EINVAL);
1095 if(i>=vf->links)return(OV_EINVAL);
1096 if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
1101 for(i=0;i<vf->links;i++)
1102 bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
1103 /* This once read: return(rint(bits/ov_time_total(vf,-1)));
1104 * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
1105 * so this is slightly transformed to make it work.
1107 br = bits/ov_time_total(vf,-1);
1111 /* return the actual bitrate */
1112 return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
1114 /* return nominal if set */
1115 if(vf->vi[i].bitrate_nominal>0){
1116 return vf->vi[i].bitrate_nominal;
1118 if(vf->vi[i].bitrate_upper>0){
1119 if(vf->vi[i].bitrate_lower>0){
1120 return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
1122 return vf->vi[i].bitrate_upper;
1131 /* returns the actual bitrate since last call. returns -1 if no
1132 additional data to offer since last call (or at beginning of stream),
1133 EINVAL if stream is only partially open
1135 long ov_bitrate_instant(OggVorbis_File *vf){
1136 int link=(vf->seekable?vf->current_link:0);
1138 if(vf->ready_state<OPENED)return(OV_EINVAL);
1139 if(vf->samptrack==0)return(OV_FALSE);
1140 ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
1147 long ov_serialnumber(OggVorbis_File *vf,int i){
1148 if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
1149 if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
1151 return(vf->current_serialno);
1153 return(vf->serialnos[i]);
1157 /* returns: total raw (compressed) length of content if i==-1
1158 raw (compressed) length of that logical bitstream for i==0 to n
1159 OV_EINVAL if the stream is not seekable (we can't know the length)
1160 or if stream is only partially open
1162 ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
1163 if(vf->ready_state<OPENED)return(OV_EINVAL);
1164 if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
1168 for(i=0;i<vf->links;i++)
1169 acc+=ov_raw_total(vf,i);
1172 return(vf->offsets[i+1]-vf->offsets[i]);
1176 /* returns: total PCM length (samples) of content if i==-1 PCM length
1177 (samples) of that logical bitstream for i==0 to n
1178 OV_EINVAL if the stream is not seekable (we can't know the
1179 length) or only partially open
1181 ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
1182 if(vf->ready_state<OPENED)return(OV_EINVAL);
1183 if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
1187 for(i=0;i<vf->links;i++)
1188 acc+=ov_pcm_total(vf,i);
1191 return(vf->pcmlengths[i*2+1]);
1195 /* returns: total seconds of content if i==-1
1196 seconds in that logical bitstream for i==0 to n
1197 OV_EINVAL if the stream is not seekable (we can't know the
1198 length) or only partially open
1200 double ov_time_total(OggVorbis_File *vf,int i){
1201 if(vf->ready_state<OPENED)return(OV_EINVAL);
1202 if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
1206 for(i=0;i<vf->links;i++)
1207 acc+=ov_time_total(vf,i);
1210 return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
1214 /* seek to an offset relative to the *compressed* data. This also
1215 scans packets to update the PCM cursor. It will cross a logical
1216 bitstream boundary, but only if it can't get any packets out of the
1217 tail of the bitstream we seek to (so no surprises).
1219 returns zero on success, nonzero on failure */
1221 int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
1222 ogg_stream_state work_os;
1225 if(vf->ready_state<OPENED)return(OV_EINVAL);
1227 return(OV_ENOSEEK); /* don't dump machine if we can't seek */
1229 if(pos<0 || pos>vf->end)return(OV_EINVAL);
1231 /* is the seek position outside our current link [if any]? */
1232 if(vf->ready_state>=STREAMSET){
1233 if(pos<vf->offsets[vf->current_link] || pos>=vf->offsets[vf->current_link+1])
1234 _decode_clear(vf); /* clear out stream state */
1237 /* don't yet clear out decoding machine (if it's initialized), in
1238 the case we're in the same link. Restart the decode lapping, and
1239 let _fetch_and_process_packet deal with a potential bitstream
1242 ogg_stream_reset_serialno(&vf->os,
1243 vf->current_serialno); /* must set serialno */
1244 vorbis_synthesis_restart(&vf->vd);
1246 ret=_seek_helper(vf,pos);
1247 if(ret)goto seek_error;
1249 /* we need to make sure the pcm_offset is set, but we don't want to
1250 advance the raw cursor past good packets just to get to the first
1251 with a granulepos. That's not equivalent behavior to beginning
1252 decoding as immediately after the seek position as possible.
1254 So, a hack. We use two stream states; a local scratch state and
1255 the shared vf->os stream state. We use the local state to
1256 scan, and the shared state as a buffer for later decode.
1258 Unfortuantely, on the last page we still advance to last packet
1259 because the granulepos on the last page is not necessarily on a
1260 packet boundary, and we need to make sure the granpos is
1272 ogg_int64_t pagepos=-1;
1274 ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
1275 ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
1276 return from not necessarily
1277 starting from the beginning */
1280 if(vf->ready_state>=STREAMSET){
1281 /* snarf/scan a packet if we can */
1282 int result=ogg_stream_packetout(&work_os,&op);
1286 if(vf->vi[vf->current_link].codec_setup){
1287 thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
1289 ogg_stream_packetout(&vf->os,NULL);
1293 /* We can't get a guaranteed correct pcm position out of the
1294 last page in a stream because it might have a 'short'
1295 granpos, which can only be detected in the presence of a
1296 preceeding page. However, if the last page is also the first
1297 page, the granpos rules of a first page take precedence. Not
1298 only that, but for first==last, the EOS page must be treated
1299 as if its a normal first page for the stream to open/play. */
1300 if(lastflag && !firstflag)
1301 ogg_stream_packetout(&vf->os,NULL);
1303 if(lastblock)accblock+=(lastblock+thisblock)>>2;
1306 if(op.granulepos!=-1){
1307 int i,link=vf->current_link;
1308 ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
1309 if(granulepos<0)granulepos=0;
1312 granulepos+=vf->pcmlengths[i*2+1];
1313 vf->pcm_offset=granulepos-accblock;
1314 if(vf->pcm_offset<0)vf->pcm_offset=0;
1317 lastblock=thisblock;
1320 ogg_stream_packetout(&vf->os,NULL);
1325 pagepos=_get_next_page(vf,&og,-1);
1327 vf->pcm_offset=ov_pcm_total(vf,-1);
1331 /* huh? Bogus stream with packets but no granulepos */
1336 /* has our decoding just traversed a bitstream boundary? */
1337 if(vf->ready_state>=STREAMSET){
1338 if(vf->current_serialno!=ogg_page_serialno(&og)){
1340 /* two possibilities:
1341 1) our decoding just traversed a bitstream boundary
1342 2) another stream is multiplexed into this logical section? */
1344 if(ogg_page_bos(&og)){
1346 _decode_clear(vf); /* clear out stream state */
1347 ogg_stream_clear(&work_os);
1348 } /* else, do nothing; next loop will scoop another page */
1352 if(vf->ready_state<STREAMSET){
1354 long serialno = ogg_page_serialno(&og);
1356 for(link=0;link<vf->links;link++)
1357 if(vf->serialnos[link]==serialno)break;
1359 if(link==vf->links) continue; /* not the desired Vorbis
1360 bitstream section; keep
1362 vf->current_link=link;
1363 vf->current_serialno=serialno;
1364 ogg_stream_reset_serialno(&vf->os,serialno);
1365 ogg_stream_reset_serialno(&work_os,serialno);
1366 vf->ready_state=STREAMSET;
1367 firstflag=(pagepos<=vf->dataoffsets[link]);
1370 ogg_stream_pagein(&vf->os,&og);
1371 ogg_stream_pagein(&work_os,&og);
1372 lastflag=ogg_page_eos(&og);
1377 ogg_stream_clear(&work_os);
1383 /* dump the machine so we're in a known state */
1385 ogg_stream_clear(&work_os);
1390 /* Page granularity seek (faster than sample granularity because we
1391 don't do the last bit of decode to find a specific sample).
1393 Seek to the last [granule marked] page preceeding the specified pos
1394 location, such that decoding past the returned point will quickly
1395 arrive at the requested position. */
1396 int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
1398 ogg_int64_t result=0;
1399 ogg_int64_t total=ov_pcm_total(vf,-1);
1401 if(vf->ready_state<OPENED)return(OV_EINVAL);
1402 if(!vf->seekable)return(OV_ENOSEEK);
1404 if(pos<0 || pos>total)return(OV_EINVAL);
1406 /* which bitstream section does this pcm offset occur in? */
1407 for(link=vf->links-1;link>=0;link--){
1408 total-=vf->pcmlengths[link*2+1];
1409 if(pos>=total)break;
1412 /* search within the logical bitstream for the page with the highest
1413 pcm_pos preceeding (or equal to) pos. There is a danger here;
1414 missing pages or incorrect frame number information in the
1415 bitstream could make our task impossible. Account for that (it
1416 would be an error condition) */
1418 /* new search algorithm by HB (Nicholas Vinen) */
1420 ogg_int64_t end=vf->offsets[link+1];
1421 ogg_int64_t begin=vf->offsets[link];
1422 ogg_int64_t begintime = vf->pcmlengths[link*2];
1423 ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
1424 ogg_int64_t target=pos-total+begintime;
1425 ogg_int64_t best=begin;
1431 if(end-begin<CHUNKSIZE){
1434 /* take a (pretty decent) guess. */
1436 (ogg_int64_t)((double)(target-begintime)*(end-begin)/(endtime-begintime))
1438 if(bisect<begin+CHUNKSIZE)
1442 if(bisect!=vf->offset){
1443 result=_seek_helper(vf,bisect);
1444 if(result) goto seek_error;
1448 result=_get_next_page(vf,&og,end-vf->offset);
1449 if(result==OV_EREAD) goto seek_error;
1452 end=begin; /* found it */
1454 if(bisect==0) goto seek_error;
1456 if(bisect<=begin)bisect=begin+1;
1457 result=_seek_helper(vf,bisect);
1458 if(result) goto seek_error;
1461 ogg_int64_t granulepos;
1463 if(ogg_page_serialno(&og)!=vf->serialnos[link])
1466 granulepos=ogg_page_granulepos(&og);
1467 if(granulepos==-1)continue;
1469 if(granulepos<target){
1470 best=result; /* raw offset of packet with granulepos */
1471 begin=vf->offset; /* raw offset of next page */
1472 begintime=granulepos;
1474 if(target-begintime>44100)break;
1475 bisect=begin; /* *not* begin + 1 */
1478 end=begin; /* found it */
1480 if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
1482 bisect-=CHUNKSIZE; /* an endless loop otherwise. */
1483 if(bisect<=begin)bisect=begin+1;
1484 result=_seek_helper(vf,bisect);
1485 if(result) goto seek_error;
1497 /* found our page. seek to it, update pcm offset. Easier case than
1498 raw_seek, don't keep packets preceeding granulepos. */
1504 result=_seek_helper(vf,best);
1506 if(result) goto seek_error;
1507 result=_get_next_page(vf,&og,-1);
1508 if(result<0) goto seek_error;
1510 if(link!=vf->current_link){
1511 /* Different link; dump entire decode machine */
1514 vf->current_link=link;
1515 vf->current_serialno=vf->serialnos[link];
1516 vf->ready_state=STREAMSET;
1519 vorbis_synthesis_restart(&vf->vd);
1522 ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
1523 ogg_stream_pagein(&vf->os,&og);
1525 /* pull out all but last packet; the one with granulepos */
1527 result=ogg_stream_packetpeek(&vf->os,&op);
1529 /* !!! the packet finishing this page originated on a
1530 preceeding page. Keep fetching previous pages until we
1531 get one with a granulepos or without the 'continued' flag
1532 set. Then just use raw_seek for simplicity. */
1534 result=_seek_helper(vf,best);
1535 if(result<0) goto seek_error;
1538 result=_get_prev_page(vf,&og);
1539 if(result<0) goto seek_error;
1540 if(ogg_page_serialno(&og)==vf->current_serialno &&
1541 (ogg_page_granulepos(&og)>-1 ||
1542 !ogg_page_continued(&og))){
1543 return ov_raw_seek(vf,result);
1549 result = OV_EBADPACKET;
1552 if(op.granulepos!=-1){
1553 vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
1554 if(vf->pcm_offset<0)vf->pcm_offset=0;
1555 vf->pcm_offset+=total;
1558 result=ogg_stream_packetout(&vf->os,NULL);
1564 if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
1573 /* dump machine so we're in a known state */
1579 /* seek to a sample offset relative to the decompressed pcm stream
1580 returns zero on success, nonzero on failure */
1582 int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
1583 int thisblock,lastblock=0;
1584 int ret=ov_pcm_seek_page(vf,pos);
1585 if(ret<0)return(ret);
1586 if((ret=_make_decode_ready(vf)))return ret;
1588 /* discard leading packets we don't need for the lapping of the
1589 position we want; don't decode them */
1595 int ret=ogg_stream_packetpeek(&vf->os,&op);
1597 thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
1599 ogg_stream_packetout(&vf->os,NULL);
1600 continue; /* non audio packet */
1602 if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
1604 if(vf->pcm_offset+((thisblock+
1605 vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
1607 /* remove the packet from packet queue and track its granulepos */
1608 ogg_stream_packetout(&vf->os,NULL);
1609 vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
1612 vorbis_synthesis_blockin(&vf->vd,&vf->vb);
1614 /* end of logical stream case is hard, especially with exact
1615 length positioning. */
1617 if(op.granulepos>-1){
1619 /* always believe the stream markers */
1620 vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
1621 if(vf->pcm_offset<0)vf->pcm_offset=0;
1622 for(i=0;i<vf->current_link;i++)
1623 vf->pcm_offset+=vf->pcmlengths[i*2+1];
1626 lastblock=thisblock;
1629 if(ret<0 && ret!=OV_HOLE)break;
1631 /* suck in a new page */
1632 if(_get_next_page(vf,&og,-1)<0)break;
1633 if(ogg_page_bos(&og))_decode_clear(vf);
1635 if(vf->ready_state<STREAMSET){
1636 long serialno=ogg_page_serialno(&og);
1639 for(link=0;link<vf->links;link++)
1640 if(vf->serialnos[link]==serialno)break;
1641 if(link==vf->links) continue;
1642 vf->current_link=link;
1644 vf->ready_state=STREAMSET;
1645 vf->current_serialno=ogg_page_serialno(&og);
1646 ogg_stream_reset_serialno(&vf->os,serialno);
1647 ret=_make_decode_ready(vf);
1652 ogg_stream_pagein(&vf->os,&og);
1658 /* discard samples until we reach the desired position. Crossing a
1659 logical bitstream boundary with abandon is OK. */
1660 while(vf->pcm_offset<pos){
1661 ogg_int64_t target=pos-vf->pcm_offset;
1662 long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
1664 if(samples>target)samples=target;
1665 vorbis_synthesis_read(&vf->vd,samples);
1666 vf->pcm_offset+=samples;
1669 if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
1670 vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
1675 /* seek to a playback time relative to the decompressed pcm stream
1676 returns zero on success, nonzero on failure */
1677 int ov_time_seek(OggVorbis_File *vf,double seconds){
1678 /* translate time to PCM position and call ov_pcm_seek */
1681 ogg_int64_t pcm_total=0;
1682 double time_total=0.;
1684 if(vf->ready_state<OPENED)return(OV_EINVAL);
1685 if(!vf->seekable)return(OV_ENOSEEK);
1686 if(seconds<0)return(OV_EINVAL);
1688 /* which bitstream section does this time offset occur in? */
1689 for(link=0;link<vf->links;link++){
1690 double addsec = ov_time_total(vf,link);
1691 if(seconds<time_total+addsec)break;
1693 pcm_total+=vf->pcmlengths[link*2+1];
1696 if(link==vf->links)return(OV_EINVAL);
1698 /* enough information to convert time offset to pcm offset */
1700 ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
1701 return(ov_pcm_seek(vf,target));
1705 /* page-granularity version of ov_time_seek
1706 returns zero on success, nonzero on failure */
1707 int ov_time_seek_page(OggVorbis_File *vf,double seconds){
1708 /* translate time to PCM position and call ov_pcm_seek */
1711 ogg_int64_t pcm_total=0;
1712 double time_total=0.;
1714 if(vf->ready_state<OPENED)return(OV_EINVAL);
1715 if(!vf->seekable)return(OV_ENOSEEK);
1716 if(seconds<0)return(OV_EINVAL);
1718 /* which bitstream section does this time offset occur in? */
1719 for(link=0;link<vf->links;link++){
1720 double addsec = ov_time_total(vf,link);
1721 if(seconds<time_total+addsec)break;
1723 pcm_total+=vf->pcmlengths[link*2+1];
1726 if(link==vf->links)return(OV_EINVAL);
1728 /* enough information to convert time offset to pcm offset */
1730 ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
1731 return(ov_pcm_seek_page(vf,target));
1735 /* tell the current stream offset cursor. Note that seek followed by
1736 tell will likely not give the set offset due to caching */
1737 ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
1738 if(vf->ready_state<OPENED)return(OV_EINVAL);
1742 /* return PCM offset (sample) of next PCM sample to be read */
1743 ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
1744 if(vf->ready_state<OPENED)return(OV_EINVAL);
1745 return(vf->pcm_offset);
1748 /* return time offset (seconds) of next PCM sample to be read */
1749 double ov_time_tell(OggVorbis_File *vf){
1751 ogg_int64_t pcm_total=0;
1752 double time_total=0.f;
1754 if(vf->ready_state<OPENED)return(OV_EINVAL);
1756 pcm_total=ov_pcm_total(vf,-1);
1757 time_total=ov_time_total(vf,-1);
1759 /* which bitstream section does this time offset occur in? */
1760 for(link=vf->links-1;link>=0;link--){
1761 pcm_total-=vf->pcmlengths[link*2+1];
1762 time_total-=ov_time_total(vf,link);
1763 if(vf->pcm_offset>=pcm_total)break;
1767 return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
1770 /* link: -1) return the vorbis_info struct for the bitstream section
1771 currently being decoded
1772 0-n) to request information for a specific bitstream section
1774 In the case of a non-seekable bitstream, any call returns the
1775 current bitstream. NULL in the case that the machine is not
1778 vorbis_info *ov_info(OggVorbis_File *vf,int link){
1781 if(vf->ready_state>=STREAMSET)
1782 return vf->vi+vf->current_link;
1795 /* grr, strong typing, grr, no templates/inheritence, grr */
1796 vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
1799 if(vf->ready_state>=STREAMSET)
1800 return vf->vc+vf->current_link;
1813 static int host_is_big_endian() {
1814 ogg_int32_t pattern = 0xfeedface; /* deadbeef */
1815 unsigned char *bytewise = (unsigned char *)&pattern;
1816 if (bytewise[0] == 0xfe) return 1;
1820 /* up to this point, everything could more or less hide the multiple
1821 logical bitstream nature of chaining from the toplevel application
1822 if the toplevel application didn't particularly care. However, at
1823 the point that we actually read audio back, the multiple-section
1824 nature must surface: Multiple bitstream sections do not necessarily
1825 have to have the same number of channels or sampling rate.
1827 ov_read returns the sequential logical bitstream number currently
1828 being decoded along with the PCM data in order that the toplevel
1829 application can take action on channel/sample rate changes. This
1830 number will be incremented even for streamed (non-seekable) streams
1831 (for seekable streams, it represents the actual logical bitstream
1832 index within the physical bitstream. Note that the accessor
1833 functions above are aware of this dichotomy).
1835 ov_read_filter is exactly the same as ov_read except that it processes
1836 the decoded audio data through a filter before packing it into the
1837 requested format. This gives greater accuracy than applying a filter
1838 after the audio has been converted into integral PCM.
1840 input values: buffer) a buffer to hold packed PCM data for return
1841 length) the byte length requested to be placed into buffer
1842 bigendianp) should the data be packed LSB first (0) or
1844 word) word size for output. currently 1 (byte) or
1847 return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
1849 n) number of bytes of PCM actually returned. The
1850 below works on a packet-by-packet basis, so the
1851 return length is not related to the 'length' passed
1852 in, just guaranteed to fit.
1854 *section) set to the logical bitstream number */
1856 long ov_read_filter(OggVorbis_File *vf,char *buffer,int length,
1857 int bigendianp,int word,int sgned,int *bitstream,
1858 void (*filter)(float **pcm,long channels,long samples,void *filter_param),void *filter_param){
1860 int host_endian = host_is_big_endian();
1865 if(vf->ready_state<OPENED)return(OV_EINVAL);
1868 if(vf->ready_state==INITSET){
1869 samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
1873 /* suck in another packet */
1875 int ret=_fetch_and_process_packet(vf,NULL,1,1);
1886 /* yay! proceed to pack data into the byte buffer */
1888 long channels=ov_info(vf,-1)->channels;
1889 long bytespersample=word * channels;
1890 vorbis_fpu_control fpu;
1891 if(samples>length/bytespersample)samples=length/bytespersample;
1898 filter(pcm,channels,samples,filter_param);
1900 /* a tight loop to pack each size */
1904 int off=(sgned?0:128);
1905 vorbis_fpu_setround(&fpu);
1906 for(j=0;j<samples;j++)
1907 for(i=0;i<channels;i++){
1908 val=vorbis_ftoi(pcm[i][j]*128.f);
1910 else if(val<-128)val=-128;
1913 vorbis_fpu_restore(fpu);
1915 int off=(sgned?0:32768);
1917 if(host_endian==bigendianp){
1920 vorbis_fpu_setround(&fpu);
1921 for(i=0;i<channels;i++) { /* It's faster in this order */
1923 short *dest=((short *)buffer)+i;
1924 for(j=0;j<samples;j++) {
1925 val=vorbis_ftoi(src[j]*32768.f);
1926 if(val>32767)val=32767;
1927 else if(val<-32768)val=-32768;
1932 vorbis_fpu_restore(fpu);
1936 vorbis_fpu_setround(&fpu);
1937 for(i=0;i<channels;i++) {
1939 short *dest=((short *)buffer)+i;
1940 for(j=0;j<samples;j++) {
1941 val=vorbis_ftoi(src[j]*32768.f);
1942 if(val>32767)val=32767;
1943 else if(val<-32768)val=-32768;
1948 vorbis_fpu_restore(fpu);
1951 }else if(bigendianp){
1953 vorbis_fpu_setround(&fpu);
1954 for(j=0;j<samples;j++)
1955 for(i=0;i<channels;i++){
1956 val=vorbis_ftoi(pcm[i][j]*32768.f);
1957 if(val>32767)val=32767;
1958 else if(val<-32768)val=-32768;
1961 *buffer++=(val&0xff);
1963 vorbis_fpu_restore(fpu);
1967 vorbis_fpu_setround(&fpu);
1968 for(j=0;j<samples;j++)
1969 for(i=0;i<channels;i++){
1970 val=vorbis_ftoi(pcm[i][j]*32768.f);
1971 if(val>32767)val=32767;
1972 else if(val<-32768)val=-32768;
1974 *buffer++=(val&0xff);
1977 vorbis_fpu_restore(fpu);
1983 vorbis_synthesis_read(&vf->vd,samples);
1984 vf->pcm_offset+=samples;
1985 if(bitstream)*bitstream=vf->current_link;
1986 return(samples*bytespersample);
1992 long ov_read(OggVorbis_File *vf,char *buffer,int length,
1993 int bigendianp,int word,int sgned,int *bitstream){
1994 return ov_read_filter(vf, buffer, length, bigendianp, word, sgned, bitstream, NULL, NULL);
1997 /* input values: pcm_channels) a float vector per channel of output
1998 length) the sample length being read by the app
2000 return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
2002 n) number of samples of PCM actually returned. The
2003 below works on a packet-by-packet basis, so the
2004 return length is not related to the 'length' passed
2005 in, just guaranteed to fit.
2007 *section) set to the logical bitstream number */
2011 long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
2014 if(vf->ready_state<OPENED)return(OV_EINVAL);
2017 if(vf->ready_state==INITSET){
2019 long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
2021 if(pcm_channels)*pcm_channels=pcm;
2022 if(samples>length)samples=length;
2023 vorbis_synthesis_read(&vf->vd,samples);
2024 vf->pcm_offset+=samples;
2025 if(bitstream)*bitstream=vf->current_link;
2031 /* suck in another packet */
2033 int ret=_fetch_and_process_packet(vf,NULL,1,1);
2034 if(ret==OV_EOF)return(0);
2035 if(ret<=0)return(ret);
2041 extern float *vorbis_window(vorbis_dsp_state *v,int W);
2043 static void _ov_splice(float **pcm,float **lappcm,
2046 float *w1, float *w2){
2057 for(j=0;j<ch1 && j<ch2;j++){
2064 d[i]=d[i]*wd + s[i]*ws;
2067 /* window from zero */
2078 /* make sure vf is INITSET */
2079 static int _ov_initset(OggVorbis_File *vf){
2081 if(vf->ready_state==INITSET)break;
2082 /* suck in another packet */
2084 int ret=_fetch_and_process_packet(vf,NULL,1,0);
2085 if(ret<0 && ret!=OV_HOLE)return(ret);
2091 /* make sure vf is INITSET and that we have a primed buffer; if
2092 we're crosslapping at a stream section boundary, this also makes
2093 sure we're sanity checking against the right stream information */
2094 static int _ov_initprime(OggVorbis_File *vf){
2095 vorbis_dsp_state *vd=&vf->vd;
2097 if(vf->ready_state==INITSET)
2098 if(vorbis_synthesis_pcmout(vd,NULL))break;
2100 /* suck in another packet */
2102 int ret=_fetch_and_process_packet(vf,NULL,1,0);
2103 if(ret<0 && ret!=OV_HOLE)return(ret);
2109 /* grab enough data for lapping from vf; this may be in the form of
2110 unreturned, already-decoded pcm, remaining PCM we will need to
2111 decode, or synthetic postextrapolation from last packets. */
2112 static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
2113 float **lappcm,int lapsize){
2117 /* try first to decode the lapping data */
2118 while(lapcount<lapsize){
2119 int samples=vorbis_synthesis_pcmout(vd,&pcm);
2121 if(samples>lapsize-lapcount)samples=lapsize-lapcount;
2122 for(i=0;i<vi->channels;i++)
2123 memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
2125 vorbis_synthesis_read(vd,samples);
2127 /* suck in another packet */
2128 int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
2129 if(ret==OV_EOF)break;
2132 if(lapcount<lapsize){
2133 /* failed to get lapping data from normal decode; pry it from the
2134 postextrapolation buffering, or the second half of the MDCT
2135 from the last packet */
2136 int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
2138 for(i=0;i<vi->channels;i++)
2139 memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
2142 if(samples>lapsize-lapcount)samples=lapsize-lapcount;
2143 for(i=0;i<vi->channels;i++)
2144 memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
2150 /* this sets up crosslapping of a sample by using trailing data from
2151 sample 1 and lapping it into the windowing buffer of sample 2 */
2152 int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
2153 vorbis_info *vi1,*vi2;
2157 int n1,n2,i,ret,hs1,hs2;
2159 if(vf1==vf2)return(0); /* degenerate case */
2160 if(vf1->ready_state<OPENED)return(OV_EINVAL);
2161 if(vf2->ready_state<OPENED)return(OV_EINVAL);
2163 /* the relevant overlap buffers must be pre-checked and pre-primed
2164 before looking at settings in the event that priming would cross
2165 a bitstream boundary. So, do it now */
2167 ret=_ov_initset(vf1);
2169 ret=_ov_initprime(vf2);
2172 vi1=ov_info(vf1,-1);
2173 vi2=ov_info(vf2,-1);
2174 hs1=ov_halfrate_p(vf1);
2175 hs2=ov_halfrate_p(vf2);
2177 lappcm=alloca(sizeof(*lappcm)*vi1->channels);
2178 n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
2179 n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
2180 w1=vorbis_window(&vf1->vd,0);
2181 w2=vorbis_window(&vf2->vd,0);
2183 for(i=0;i<vi1->channels;i++)
2184 lappcm[i]=alloca(sizeof(**lappcm)*n1);
2186 _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
2188 /* have a lapping buffer from vf1; now to splice it into the lapping
2190 /* consolidate and expose the buffer. */
2191 vorbis_synthesis_lapout(&vf2->vd,&pcm);
2194 _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
2195 _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
2199 _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
2205 static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
2206 int (*localseek)(OggVorbis_File *,ogg_int64_t)){
2211 int n1,n2,ch1,ch2,hs;
2214 if(vf->ready_state<OPENED)return(OV_EINVAL);
2215 ret=_ov_initset(vf);
2218 hs=ov_halfrate_p(vf);
2221 n1=vorbis_info_blocksize(vi,0)>>(1+hs);
2222 w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
2223 persistent; even if the decode state
2224 from this link gets dumped, this
2225 window array continues to exist */
2227 lappcm=alloca(sizeof(*lappcm)*ch1);
2229 lappcm[i]=alloca(sizeof(**lappcm)*n1);
2230 _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
2232 /* have lapping data; seek and prime the buffer */
2233 ret=localseek(vf,pos);
2235 ret=_ov_initprime(vf);
2238 /* Guard against cross-link changes; they're perfectly legal */
2241 n2=vorbis_info_blocksize(vi,0)>>(1+hs);
2242 w2=vorbis_window(&vf->vd,0);
2244 /* consolidate and expose the buffer. */
2245 vorbis_synthesis_lapout(&vf->vd,&pcm);
2248 _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
2254 int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
2255 return _ov_64_seek_lap(vf,pos,ov_raw_seek);
2258 int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
2259 return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
2262 int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
2263 return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
2266 static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
2267 int (*localseek)(OggVorbis_File *,double)){
2272 int n1,n2,ch1,ch2,hs;
2275 if(vf->ready_state<OPENED)return(OV_EINVAL);
2276 ret=_ov_initset(vf);
2279 hs=ov_halfrate_p(vf);
2282 n1=vorbis_info_blocksize(vi,0)>>(1+hs);
2283 w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
2284 persistent; even if the decode state
2285 from this link gets dumped, this
2286 window array continues to exist */
2288 lappcm=alloca(sizeof(*lappcm)*ch1);
2290 lappcm[i]=alloca(sizeof(**lappcm)*n1);
2291 _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
2293 /* have lapping data; seek and prime the buffer */
2294 ret=localseek(vf,pos);
2296 ret=_ov_initprime(vf);
2299 /* Guard against cross-link changes; they're perfectly legal */
2302 n2=vorbis_info_blocksize(vi,0)>>(1+hs);
2303 w2=vorbis_window(&vf->vd,0);
2305 /* consolidate and expose the buffer. */
2306 vorbis_synthesis_lapout(&vf->vd,&pcm);
2309 _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
2315 int ov_time_seek_lap(OggVorbis_File *vf,double pos){
2316 return _ov_d_seek_lap(vf,pos,ov_time_seek);
2319 int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
2320 return _ov_d_seek_lap(vf,pos,ov_time_seek_page);