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