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