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