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