Cleaned up memory leaks in vorbisfile and libvorbis.
[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_clear(vi);
218   vorbis_info_init(vi);
219   
220   i=0;
221   while(i<3){
222     ogg_stream_pagein(&vf->os,&og);
223     while(i<3){
224       int result=ogg_stream_packetout(&vf->os,&op);
225       if(result==0)break;
226       if(result==-1){
227         fprintf(stderr,"Corrupt header in logical bitstream.\n");
228         goto bail_header;
229       }
230       if(vorbis_info_headerin(vi,&op)){
231         fprintf(stderr,"Illegal header in logical bitstream.\n");
232         goto bail_header;
233       }
234       i++;
235     }
236     if(i<3)
237       if(_get_next_page(vf,&og,1)<0){
238         fprintf(stderr,"Missing header in logical bitstream.\n");
239         goto bail_header;
240       }
241   }
242   ogg_stream_clear(&vf->os);
243   return 0; 
244
245  bail_header:
246   vorbis_info_clear(vi);
247   ogg_stream_clear(&vf->os);
248   return -1;
249 }
250
251 /* last step of the OggVorbis_File initialization; get all the
252    vorbis_info structs and PCM positions.  Only called by the seekable
253    initialization (local stream storage is hacked slightly; pay
254    attention to how that's done) */
255 static void _prefetch_all_headers(OggVorbis_File *vf,vorbis_info *first,
256                                   long dataoffset){
257   ogg_page og;
258   int i,ret;
259   
260   vf->vi=calloc(vf->links,sizeof(vorbis_info));
261   vf->dataoffsets=malloc(vf->links*sizeof(long));
262   vf->pcmlengths=malloc(vf->links*sizeof(size64));
263   vf->serialnos=malloc(vf->links*sizeof(long));
264   
265   for(i=0;i<vf->links;i++){
266     if(first && i==0){
267       /* we already grabbed the initial header earlier.  This just
268          saves the waste of grabbing it again */
269       memcpy(vf->vi+i,first,sizeof(vorbis_info));
270       memset(first,0,sizeof(vorbis_info));
271       vf->dataoffsets[i]=dataoffset;
272     }else{
273
274       /* seek to the location of the initial header */
275
276       _seek_helper(vf,vf->offsets[i]);
277       if(_fetch_headers(vf,vf->vi+i,NULL)==-1){
278         vorbis_info_clear(vf->vi+i);
279         fprintf(stderr,"Error opening logical bitstream #%d.\n\n",i+1);
280     
281         ogg_stream_clear(&vf->os); /* clear local storage.  This is not
282                                       done in _fetch_headers, as that may
283                                       be called in a non-seekable stream
284                                       (in which case, we need to preserve
285                                       the stream local storage) */
286         vf->dataoffsets[i]=-1;
287       }else
288         vf->dataoffsets[i]=vf->offset;
289     }
290
291     /* get the serial number and PCM length of this link. To do this,
292        get the last page of the stream */
293     {
294       long end=vf->offsets[i+1];
295       _seek_helper(vf,end);
296
297       while(1){
298         ret=_get_prev_page(vf,&og);
299         if(ret==-1){
300           /* this should not be possible */
301           fprintf(stderr,"Could not find last page of logical "
302                   "bitstream #%d\n\n",i);
303           vorbis_info_clear(vf->vi+i);
304           break;
305         }
306         if(ogg_page_frameno(&og)!=-1){
307           vf->serialnos[i]=ogg_page_serialno(&og);
308           vf->pcmlengths[i]=ogg_page_frameno(&og);
309           break;
310         }
311       }
312     }
313   }
314 }
315
316 static int _open_seekable(OggVorbis_File *vf){
317   vorbis_info initial;
318   long serialno,end;
319   int ret;
320   long dataoffset;
321   ogg_page og;
322   
323   /* is this even vorbis...? */
324   memset(&initial,0,sizeof(vorbis_info));
325   ret=_fetch_headers(vf,&initial,&serialno);
326   dataoffset=vf->offset;
327   ogg_stream_clear(&vf->os);
328   if(ret==-1)return(-1);
329   
330   /* we can seek, so set out learning all about this file */
331   vf->seekable=1;
332   fseek(vf->f,0,SEEK_END);
333   vf->offset=vf->end=ftell(vf->f);
334   
335   /* We get the offset for the last page of the physical bitstream.
336      Most OggVorbis files will contain a single logical bitstream */
337   end=_get_prev_page(vf,&og);
338
339   /* moer than one logical bitstream? */
340   if(ogg_page_serialno(&og)!=serialno){
341
342     /* Chained bitstream. Bisect-search each logical bitstream
343        section.  Do so based on serial number only */
344     _bisect_forward_serialno(vf,0,0,end+1,serialno,0);
345
346   }else{
347
348     /* Only one logical bitstream */
349     _bisect_forward_serialno(vf,0,end,end+1,serialno,0);
350
351   }
352
353   _prefetch_all_headers(vf,&initial,dataoffset);
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       size64 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         vorbis_synthesis(&vf->vb,&op);
408         vorbis_synthesis_blockin(&vf->vd,&vf->vb);
409         
410         /* update the pcm offset. */
411         if(frameno!=-1){
412           int link=(vf->seekable?vf->current_link:0);
413           double **dummy;
414           int i,samples;
415           
416           /* this packet has a pcm_offset on it (the last packet
417              completed on a page carries the offset) After processing
418              (above), we know the pcm position of the *last* sample
419              ready to be returned. Find the offset of the *first* */
420           
421           samples=vorbis_synthesis_pcmout(&vf->vd,&dummy);
422           
423           frameno-=samples;
424           for(i=0;i<link;i++)
425             frameno+=vf->pcmlengths[i];
426           vf->pcm_offset=frameno;
427         }
428         return(1);
429       }
430     }
431
432     if(!readp)return(0);
433     if(_get_next_page(vf,&og,-1)<0)return(0); /* eof. leave unitialized */
434
435     /* has our decoding just traversed a bitstream boundary? */
436     if(vf->decode_ready){
437       if(vf->current_serialno!=ogg_page_serialno(&og)){
438         _decode_clear(vf);
439       }
440     }
441
442     /* Do we need to load a new machine before submitting the page? */
443     /* This is different in the seekable and non-seekable cases.  
444
445        In the seekable case, we already have all the header
446        information loaded and cached; we just initialize the machine
447        with it and continue on our merry way.
448
449        In the non-seekable (streaming) case, we'll only be at a
450        boundary if we just left the previous logical bitstream and
451        we're now nominally at the header of the next bitstream
452     */
453
454     if(!vf->decode_ready){
455       int link;
456       if(vf->seekable){
457         vf->current_serialno=ogg_page_serialno(&og);
458         
459         /* match the serialno to bitstream section.  We use this rather than
460            offset positions to avoid problems near logical bitstream
461            boundaries */
462         for(link=0;link<vf->links;link++)
463           if(vf->serialnos[link]==vf->current_serialno)break;
464         if(link==vf->links)return(-1); /* sign of a bogus stream.  error out,
465                                           leave machine uninitialized */
466         
467         vf->current_link=link;
468       }else{
469         /* we're streaming */
470         /* fetch the three header packets, build the info struct */
471         
472         _fetch_headers(vf,vf->vi,&vf->current_serialno);
473         vf->current_link++;
474         link=0;
475       }
476       
477       /* reload */
478       ogg_stream_init(&vf->os,vf->current_serialno);
479       ogg_stream_reset(&vf->os,ogg_page_pageno(&og));
480       vorbis_synthesis_init(&vf->vd,vf->vi+link);
481       vorbis_block_init(&vf->vd,&vf->vb);
482       vf->decode_ready=1;
483     }
484     ogg_stream_pagein(&vf->os,&og);
485   }
486 }
487
488 /**********************************************************************
489  * The helpers are over; it's all toplevel interface from here on out */
490  
491 /* clear out the OggVorbis_File struct */
492 int ov_clear(OggVorbis_File *vf){
493   if(vf){
494     vorbis_block_clear(&vf->vb);
495     vorbis_dsp_clear(&vf->vd);
496     ogg_stream_clear(&vf->os);
497     
498     if(vf->vi && vf->links){
499       int i;
500       for(i=0;i<vf->links;i++)
501         vorbis_info_clear(vf->vi+i);
502       free(vf->vi);
503     }
504     if(vf->dataoffsets)free(vf->dataoffsets);
505     if(vf->pcmlengths)free(vf->pcmlengths);
506     if(vf->serialnos)free(vf->serialnos);
507     if(vf->offsets)free(vf->offsets);
508     ogg_sync_clear(&vf->oy);
509     if(vf->f)fclose(vf->f);
510     memset(vf,0,sizeof(OggVorbis_File));
511   }
512   return(0);
513 }
514
515 /* inspects the OggVorbis file and finds/documents all the logical
516    bitstreams contained in it.  Tries to be tolerant of logical
517    bitstream sections that are truncated/woogie. 
518
519    return: -1) error
520             0) OK
521 */
522
523 int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
524   long offset=fseek(f,0,SEEK_CUR);
525   int ret;
526
527   memset(vf,0,sizeof(OggVorbis_File));
528   vf->f=f;
529
530   /* init the framing state */
531   ogg_sync_init(&vf->oy);
532
533   /* perhaps some data was previously read into a buffer for testing
534      against other stream types.  Allow initialization from this
535      previously read data (as we may be reading from a non-seekable
536      stream) */
537   if(initial){
538     char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
539     memcpy(buffer,initial,ibytes);
540     ogg_sync_wrote(&vf->oy,ibytes);
541   }
542
543   /* can we seek? Stevens suggests the seek test was portable */
544   if(offset!=-1){
545     ret=_open_seekable(vf);
546   }else{
547     ret=_open_nonseekable(vf);
548   }
549   if(ret){
550     vf->f=NULL;
551     ov_clear(vf);
552   }else{
553     ogg_stream_init(&vf->os,vf->current_serialno);
554     vorbis_synthesis_init(&vf->vd,vf->vi);
555     vorbis_block_init(&vf->vd,&vf->vb);
556     vf->decode_ready=1;
557   }
558   return(ret);
559 }
560
561 /* How many logical bitstreams in this physical bitstream? */
562 long ov_streams(OggVorbis_File *vf){
563   return vf->links;
564 }
565
566 /* Is the FILE * associated with vf seekable? */
567 long ov_seekable(OggVorbis_File *vf){
568   return vf->seekable;
569 }
570
571 /* returns the bitrate for a given logical bitstream or the entire
572    physical bitstream.  If the file is open for random access, it will
573    find the *actual* average bitrate.  If the file is streaming, it
574    returns the nominal bitrate (if set) else the average of the
575    upper/lower bounds (if set) else -1 (unset).
576
577    If you want the actual bitrate field settings, get them from the
578    vorbis_info structs */
579
580 long ov_bitrate(OggVorbis_File *vf,int i){
581   if(i>=vf->links)return(-1);
582   if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
583   if(i<0){
584     size64 bits;
585     int i;
586     for(i=0;i<vf->links;i++)
587       bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
588     return(rint(bits/ov_time_total(vf,-1)));
589   }else{
590     if(vf->seekable){
591       /* return the actual bitrate */
592       return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
593     }else{
594       /* return nominal if set */
595       if(vf->vi[i].bitrate_nominal>0){
596         return vf->vi[i].bitrate_nominal;
597       }else{
598         if(vf->vi[i].bitrate_upper>0){
599           if(vf->vi[i].bitrate_lower>0){
600             return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
601           }else{
602             return vf->vi[i].bitrate_upper;
603           }
604         }
605         return(-1);
606       }
607     }
608   }
609 }
610
611 /* Guess */
612 long ov_serialnumber(OggVorbis_File *vf,int i){
613   if(i>=vf->links)return(-1);
614   if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
615   if(i<0){
616     return(vf->current_serialno);
617   }else{
618     return(vf->serialnos[i]);
619   }
620 }
621
622 /* returns: total raw (compressed) length of content if i==-1
623             raw (compressed) length of that logical bitstream for i==0 to n
624             -1 if the stream is not seekable (we can't know the length)
625 */
626 long ov_raw_total(OggVorbis_File *vf,int i){
627   if(!vf->seekable || i>=vf->links)return(-1);
628   if(i<0){
629     long acc=0;
630     int i;
631     for(i=0;i<vf->links;i++)
632       acc+=ov_raw_total(vf,i);
633     return(acc);
634   }else{
635     return(vf->offsets[i+1]-vf->offsets[i]);
636   }
637 }
638
639 /* returns: total PCM length (samples) of content if i==-1
640             PCM length (samples) of that logical bitstream for i==0 to n
641             -1 if the stream is not seekable (we can't know the length)
642 */
643 size64 ov_pcm_total(OggVorbis_File *vf,int i){
644   if(!vf->seekable || i>=vf->links)return(-1);
645   if(i<0){
646     size64 acc=0;
647     int i;
648     for(i=0;i<vf->links;i++)
649       acc+=ov_pcm_total(vf,i);
650     return(acc);
651   }else{
652     return(vf->pcmlengths[i]);
653   }
654 }
655
656 /* returns: total seconds of content if i==-1
657             seconds in that logical bitstream for i==0 to n
658             -1 if the stream is not seekable (we can't know the length)
659 */
660 double ov_time_total(OggVorbis_File *vf,int i){
661   if(!vf->seekable || i>=vf->links)return(-1);
662   if(i<0){
663     double acc=0;
664     int i;
665     for(i=0;i<vf->links;i++)
666       acc+=ov_time_total(vf,i);
667     return(acc);
668   }else{
669     return((float)(vf->pcmlengths[i])/vf->vi[i].rate);
670   }
671 }
672
673 /* seek to an offset relative to the *compressed* data. This also
674    immediately sucks in and decodes pages to update the PCM cursor. It
675    will cross a logical bitstream boundary, but only if it can't get
676    any packets out of the tail of the bitstream we seek to (so no
677    surprises). 
678
679    returns zero on success, nonzero on failure */
680
681 int ov_raw_seek(OggVorbis_File *vf,long pos){
682
683   if(!vf->seekable)return(-1); /* don't dump machine if we can't seek */
684   if(pos<0 || pos>vf->offsets[vf->links])goto seek_error;
685
686   /* clear out decoding machine state */
687   _decode_clear(vf);
688
689   /* seek */
690   _seek_helper(vf,pos);
691
692   /* we need to make sure the pcm_offset is set.  We use the
693      _fetch_packet helper to process one packet with readp set, then
694      call it until it returns '0' with readp not set (the last packet
695      from a page has the 'frameno' field set, and that's how the
696      helper updates the offset */
697
698   switch(_process_packet(vf,1)){
699   case 0:
700     /* oh, eof. There are no packets remaining.  Set the pcm offset to
701        the end of file */
702     vf->pcm_offset=ov_pcm_total(vf,-1);
703     return(0);
704   case -1:
705     /* error! missing data or invalid bitstream structure */
706     goto seek_error;
707   default:
708     /* all OK */
709     break;
710   }
711
712   while(1){
713     switch(_process_packet(vf,0)){
714     case 0:
715       /* the offset is set.  If it's a bogus bitstream with no offset
716          information, it's not but that's not our fault.  We still run
717          gracefully, we're just missing the offset */
718       return(0);
719     case -1:
720       /* error! missing data or invalid bitstream structure */
721       goto seek_error;
722     default:
723       /* continue processing packets */
724       break;
725     }
726   }
727   
728  seek_error:
729   /* dump the machine so we're in a known state */
730   _decode_clear(vf);
731   return -1;
732 }
733
734 /* seek to a sample offset relative to the decompressed pcm stream 
735
736    returns zero on success, nonzero on failure */
737
738 int ov_pcm_seek(OggVorbis_File *vf,size64 pos){
739   int link=-1;
740   size64 total=ov_pcm_total(vf,-1);
741
742   if(!vf->seekable)return(-1); /* don't dump machine if we can't seek */  
743   if(pos<0 || pos>total)goto seek_error;
744
745   /* which bitstream section does this pcm offset occur in? */
746   for(link=vf->links-1;link>=0;link--){
747     total-=vf->pcmlengths[link];
748     if(pos>=total)break;
749   }
750
751   /* search within the logical bitstream for the page with the highest
752      pcm_pos preceeding (or equal to) pos.  There is a danger here;
753      missing pages or incorrect frame number information in the
754      bitstream could make our task impossible.  Account for that (it
755      would be an error condition) */
756   {
757     size64 target=pos-total;
758     long end=vf->offsets[link+1];
759     long begin=vf->offsets[link];
760     long best=begin;
761
762     ogg_page og;
763     while(begin<end){
764       long bisect;
765       long ret;
766     
767       if(end-begin<CHUNKSIZE){
768         bisect=begin;
769       }else{
770         bisect=(end+begin)/2;
771       }
772     
773       _seek_helper(vf,bisect);
774       ret=_get_next_page(vf,&og,end-bisect);
775       
776       if(ret==-1){
777         end=bisect;
778       }else{
779         size64 frameno=ogg_page_frameno(&og);
780         if(frameno<target){
781           best=ret;  /* raw offset of packet with frameno */ 
782           begin=vf->offset; /* raw offset of next packet */
783         }else{
784           end=bisect;
785         }
786       }
787     }
788
789     /* found our page. seek to it (call raw_seek). */
790     
791     if(ov_raw_seek(vf,best))goto seek_error;
792   }
793
794   /* verify result */
795   if(vf->pcm_offset>=pos)goto seek_error;
796   if(pos>ov_pcm_total(vf,-1))goto seek_error;
797
798   /* discard samples until we reach the desired position. Crossing a
799      logical bitstream boundary with abandon is OK. */
800   while(vf->pcm_offset<pos){
801     double **pcm;
802     long target=pos-vf->pcm_offset;
803     long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
804
805     if(samples>target)samples=target;
806     vorbis_synthesis_read(&vf->vd,samples);
807     vf->pcm_offset+=samples;
808     
809     if(samples<target)
810       if(_process_packet(vf,1)==0)
811         vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
812   }
813   return 0;
814   
815  seek_error:
816   /* dump machine so we're in a known state */
817   _decode_clear(vf);
818   return -1;
819 }
820
821 /* seek to a playback time relative to the decompressed pcm stream 
822    returns zero on success, nonzero on failure */
823 int ov_time_seek(OggVorbis_File *vf,double seconds){
824   /* translate time to PCM position and call ov_pcm_seek */
825
826   int link=-1;
827   size64 pcm_total=ov_pcm_total(vf,-1);
828   double time_total=ov_time_total(vf,-1);
829
830   if(!vf->seekable)return(-1); /* don't dump machine if we can't seek */  
831   if(seconds<0 || seconds>time_total)goto seek_error;
832   
833   /* which bitstream section does this time offset occur in? */
834   for(link=vf->links-1;link>=0;link--){
835     pcm_total-=vf->pcmlengths[link];
836     time_total-=ov_time_total(vf,link);
837     if(seconds>=time_total)break;
838   }
839
840   /* enough information to convert time offset to pcm offset */
841   {
842     size64 target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
843     return(ov_pcm_seek(vf,target));
844   }
845
846  seek_error:
847   /* dump machine so we're in a known state */
848   _decode_clear(vf);
849   return -1;
850 }
851
852 /* tell the current stream offset cursor.  Note that seek followed by
853    tell will likely not give the set offset due to caching */
854 long ov_raw_tell(OggVorbis_File *vf){
855   return(vf->offset);
856 }
857
858 /* return PCM offset (sample) of next PCM sample to be read */
859 size64 ov_pcm_tell(OggVorbis_File *vf){
860   return(vf->pcm_offset);
861 }
862
863 /* return time offset (seconds) of next PCM sample to be read */
864 double ov_time_tell(OggVorbis_File *vf){
865   /* translate time to PCM position and call ov_pcm_seek */
866
867   int link=-1;
868   size64 pcm_total=0;
869   double time_total=0.;
870   
871   if(vf->seekable){
872     pcm_total=ov_pcm_total(vf,-1);
873     time_total=ov_time_total(vf,-1);
874   
875     /* which bitstream section does this time offset occur in? */
876     for(link=vf->links-1;link>=0;link--){
877       pcm_total-=vf->pcmlengths[link];
878       time_total-=ov_time_total(vf,link);
879       if(vf->pcm_offset>pcm_total)break;
880     }
881   }
882
883   return(time_total+(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
884 }
885
886 /*  link:   -1) return the vorbis_info struct for the bitstream section
887                 currently being decoded
888            0-n) to request information for a specific bitstream section
889     
890     In the case of a non-seekable bitstream, any call returns the
891     current bitstream.  NULL in the case that the machine is not
892     initialized */
893
894 vorbis_info *ov_info(OggVorbis_File *vf,int link){
895   if(vf->seekable){
896     if(link<0)
897       if(vf->decode_ready)
898         return vf->vi+vf->current_link;
899       else
900         return NULL;
901     else
902       if(link>=vf->links)
903         return NULL;
904       else
905         return vf->vi+link;
906   }else{
907     if(vf->decode_ready)
908       return vf->vi;
909     else
910       return NULL;
911   }
912 }
913
914 /* up to this point, everything could more or less hide the multiple
915    logical bitstream nature of chaining from the toplevel application
916    if the toplevel application didn't particularly care.  However, at
917    the point that we actually read audio back, the multiple-section
918    nature must surface: Multiple bitstream sections do not necessarily
919    have to have the same number of channels or sampling rate.
920
921    ov_read returns the sequential logical bitstream number currently
922    being decoded along with the PCM data in order that the toplevel
923    application can take action on channel/sample rate changes.  This
924    number will be incremented even for streamed (non-seekable) streams
925    (for seekable streams, it represents the actual logical bitstream
926    index within the physical bitstream.  Note that the accessor
927    functions above are aware of this dichotomy).
928
929    input values: buffer) a buffer to hold packed PCM data for return
930                  length) the byte length requested to be placed into buffer
931                  bigendianp) should the data be packed LSB first (0) or
932                              MSB first (1)
933                  word) word size for output.  currently 1 (byte) or 
934                        2 (16 bit short)
935
936    return values: -1) error/hole in data
937                    0) EOF
938                    n) number of bytes of PCM actually returned.  The
939                    below works on a packet-by-packet basis, so the
940                    return length is not related to the 'length' passed
941                    in, just guaranteed to fit.
942
943             *section) set to the logical bitstream number */
944
945 long ov_read(OggVorbis_File *vf,char *buffer,int length,
946                     int bigendianp,int word,int sgned,int *bitstream){
947   int i,j;
948
949   while(1){
950     if(vf->decode_ready){
951       double **pcm;
952       long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
953       if(samples){
954         /* yay! proceed to pack data into the byte buffer */
955
956         long channels=ov_info(vf,-1)->channels;
957         long bytespersample=word * channels;
958         if(samples>length/bytespersample)samples=length/bytespersample;
959         
960         /* a tight loop to pack each size */
961         {
962           if(word==1){
963             int off=(sgned?0:128);
964             for(j=0;j<samples;j++)
965               for(i=0;i<channels;i++){
966                 int val=rint(pcm[i][j]*128.);
967                 if(val>127)val=127;
968                 if(val<-128)val=-128;
969                 *buffer++=val+off;
970               }
971           }else{
972             int off=(sgned?0:32768);
973
974             if(bigendianp){
975               for(j=0;j<samples;j++)
976                 for(i=0;i<channels;i++){
977                   int val=rint(pcm[i][j]*32768.);
978                   if(val>32767)val=32767;
979                   if(val<-32768)val=-32768;
980                   val+=off;
981                   *buffer++=(val>>8);
982                   *buffer++=(val&0xff);
983                 }
984             }else{
985               for(j=0;j<samples;j++)
986                 for(i=0;i<channels;i++){
987                   int val=rint(pcm[i][j]*32768.);
988                   if(val>32767)val=32767;
989                   if(val<-32768)val=-32768;
990                   val+=off;
991                   *buffer++=(val&0xff);
992                   *buffer++=(val>>8);
993                 }
994
995             }
996           }
997         }
998         
999         vorbis_synthesis_read(&vf->vd,samples);
1000         vf->pcm_offset+=samples;
1001         *bitstream=vf->current_link;
1002         return(samples*bytespersample);
1003       }
1004     }
1005
1006     /* suck in another packet */
1007     switch(_process_packet(vf,1)){
1008     case 0:
1009       return(0);
1010     case -1:
1011       return -1;
1012     default:
1013       break;
1014     }
1015   }
1016 }
1017
1018
1019
1020