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