Correct two more corner case problems with #1486:
[platform/upstream/libvorbis.git] / lib / vorbisfile.c
1 /********************************************************************
2  *                                                                  *
3  * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE.   *
4  * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
5  * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
6  * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
7  *                                                                  *
8  * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2014             *
9  * by the Xiph.Org Foundation http://www.xiph.org/                  *
10  *                                                                  *
11  ********************************************************************
12
13  function: stdio-based convenience library for opening/seeking/decoding
14  last mod: $Id$
15
16  ********************************************************************/
17
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <errno.h>
21 #include <string.h>
22 #include <math.h>
23
24 #include "vorbis/codec.h"
25
26 /* we don't need or want the static callback symbols here */
27 #define OV_EXCLUDE_STATIC_CALLBACKS
28 #include "vorbis/vorbisfile.h"
29
30 #include "os.h"
31 #include "misc.h"
32
33 /* A 'chained bitstream' is a Vorbis bitstream that contains more than
34    one logical bitstream arranged end to end (the only form of Ogg
35    multiplexing allowed in a Vorbis bitstream; grouping [parallel
36    multiplexing] is not allowed in Vorbis) */
37
38 /* A Vorbis file can be played beginning to end (streamed) without
39    worrying ahead of time about chaining (see decoder_example.c).  If
40    we have the whole file, however, and want random access
41    (seeking/scrubbing) or desire to know the total length/time of a
42    file, we need to account for the possibility of chaining. */
43
44 /* We can handle things a number of ways; we can determine the entire
45    bitstream structure right off the bat, or find pieces on demand.
46    This example determines and caches structure for the entire
47    bitstream, but builds a virtual decoder on the fly when moving
48    between links in the chain. */
49
50 /* There are also different ways to implement seeking.  Enough
51    information exists in an Ogg bitstream to seek to
52    sample-granularity positions in the output.  Or, one can seek by
53    picking some portion of the stream roughly in the desired area if
54    we only want coarse navigation through the stream. */
55
56 /*************************************************************************
57  * Many, many internal helpers.  The intention is not to be confusing;
58  * rampant duplication and monolithic function implementation would be
59  * harder to understand anyway.  The high level functions are last.  Begin
60  * grokking near the end of the file */
61
62 /* read a little more data from the file/pipe into the ogg_sync framer
63 */
64 #define CHUNKSIZE 65536 /* greater-than-page-size granularity seeking */
65 #define READSIZE 2048 /* a smaller read size is needed for low-rate streaming. */
66
67 static long _get_data(OggVorbis_File *vf){
68   errno=0;
69   if(!(vf->callbacks.read_func))return(-1);
70   if(vf->datasource){
71     char *buffer=ogg_sync_buffer(&vf->oy,READSIZE);
72     long bytes=(vf->callbacks.read_func)(buffer,1,READSIZE,vf->datasource);
73     if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
74     if(bytes==0 && errno)return(-1);
75     return(bytes);
76   }else
77     return(0);
78 }
79
80 /* save a tiny smidge of verbosity to make the code more readable */
81 static int _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
82   if(vf->datasource){
83     /* only seek if the file position isn't already there */
84     if(vf->offset != offset){
85       if(!(vf->callbacks.seek_func)||
86          (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET) == -1)
87         return OV_EREAD;
88       vf->offset=offset;
89       ogg_sync_reset(&vf->oy);
90     }
91   }else{
92     /* shouldn't happen unless someone writes a broken callback */
93     return OV_EFAULT;
94   }
95   return 0;
96 }
97
98 /* The read/seek functions track absolute position within the stream */
99
100 /* from the head of the stream, get the next page.  boundary specifies
101    if the function is allowed to fetch more data from the stream (and
102    how much) or only use internally buffered data.
103
104    boundary: -1) unbounded search
105               0) read no additional data; use cached only
106               n) search for a new page beginning for n bytes
107
108    return:   <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
109               n) found a page at absolute offset n */
110
111 static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
112                                   ogg_int64_t boundary){
113   if(boundary>0)boundary+=vf->offset;
114   while(1){
115     long more;
116
117     if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
118     more=ogg_sync_pageseek(&vf->oy,og);
119
120     if(more<0){
121       /* skipped n bytes */
122       vf->offset-=more;
123     }else{
124       if(more==0){
125         /* send more paramedics */
126         if(!boundary)return(OV_FALSE);
127         {
128           long ret=_get_data(vf);
129           if(ret==0)return(OV_EOF);
130           if(ret<0)return(OV_EREAD);
131         }
132       }else{
133         /* got a page.  Return the offset at the page beginning,
134            advance the internal offset past the page end */
135         ogg_int64_t ret=vf->offset;
136         vf->offset+=more;
137         return(ret);
138
139       }
140     }
141   }
142 }
143
144 /* find the latest page beginning before the passed in position. Much
145    dirtier than the above as Ogg doesn't have any backward search
146    linkage.  no 'readp' as it will certainly have to read. */
147 /* returns offset or OV_EREAD, OV_FAULT */
148 static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_int64_t begin,ogg_page *og){
149   ogg_int64_t end = begin;
150   ogg_int64_t ret;
151   ogg_int64_t offset=-1;
152
153   while(offset==-1){
154     begin-=CHUNKSIZE;
155     if(begin<0)
156       begin=0;
157
158     ret=_seek_helper(vf,begin);
159     if(ret)return(ret);
160
161     while(vf->offset<end){
162       memset(og,0,sizeof(*og));
163       ret=_get_next_page(vf,og,end-vf->offset);
164       if(ret==OV_EREAD)return(OV_EREAD);
165       if(ret<0){
166         break;
167       }else{
168         offset=ret;
169       }
170     }
171   }
172
173   /* In a fully compliant, non-multiplexed stream, we'll still be
174      holding the last page.  In multiplexed (or noncompliant streams),
175      we will probably have to re-read the last page we saw */
176   if(og->header_len==0){
177     ret=_seek_helper(vf,offset);
178     if(ret)return(ret);
179
180     ret=_get_next_page(vf,og,CHUNKSIZE);
181     if(ret<0)
182       /* this shouldn't be possible */
183       return(OV_EFAULT);
184   }
185
186   return(offset);
187 }
188
189 static void _add_serialno(ogg_page *og,long **serialno_list, int *n){
190   long s = ogg_page_serialno(og);
191   (*n)++;
192
193   if(*serialno_list){
194     *serialno_list = _ogg_realloc(*serialno_list, sizeof(**serialno_list)*(*n));
195   }else{
196     *serialno_list = _ogg_malloc(sizeof(**serialno_list));
197   }
198
199   (*serialno_list)[(*n)-1] = s;
200 }
201
202 /* returns nonzero if found */
203 static int _lookup_serialno(long s, long *serialno_list, int n){
204   if(serialno_list){
205     while(n--){
206       if(*serialno_list == s) return 1;
207       serialno_list++;
208     }
209   }
210   return 0;
211 }
212
213 static int _lookup_page_serialno(ogg_page *og, long *serialno_list, int n){
214   long s = ogg_page_serialno(og);
215   return _lookup_serialno(s,serialno_list,n);
216 }
217
218 /* performs the same search as _get_prev_page, but prefers pages of
219    the specified serial number. If a page of the specified serialno is
220    spotted during the seek-back-and-read-forward, it will return the
221    info of last page of the matching serial number instead of the very
222    last page.  If no page of the specified serialno is seen, it will
223    return the info of last page and alter *serialno.  */
224 static ogg_int64_t _get_prev_page_serial(OggVorbis_File *vf, ogg_int64_t begin,
225                                          long *serial_list, int serial_n,
226                                          int *serialno, ogg_int64_t *granpos){
227   ogg_page og;
228   ogg_int64_t end=begin;
229   ogg_int64_t ret;
230
231   ogg_int64_t prefoffset=-1;
232   ogg_int64_t offset=-1;
233   ogg_int64_t ret_serialno=-1;
234   ogg_int64_t ret_gran=-1;
235
236   while(offset==-1){
237     begin-=CHUNKSIZE;
238     if(begin<0)
239       begin=0;
240
241     ret=_seek_helper(vf,begin);
242     if(ret)return(ret);
243
244     while(vf->offset<end){
245       ret=_get_next_page(vf,&og,end-vf->offset);
246       if(ret==OV_EREAD)return(OV_EREAD);
247       if(ret<0){
248         break;
249       }else{
250         ret_serialno=ogg_page_serialno(&og);
251         ret_gran=ogg_page_granulepos(&og);
252         offset=ret;
253
254         if(ret_serialno == *serialno){
255           prefoffset=ret;
256           *granpos=ret_gran;
257         }
258
259         if(!_lookup_serialno(ret_serialno,serial_list,serial_n)){
260           /* we fell off the end of the link, which means we seeked
261              back too far and shouldn't have been looking in that link
262              to begin with.  If we found the preferred serial number,
263              forget that we saw it. */
264           prefoffset=-1;
265         }
266       }
267     }
268   }
269
270   /* we're not interested in the page... just the serialno and granpos. */
271   if(prefoffset>=0)return(prefoffset);
272
273   *serialno = ret_serialno;
274   *granpos = ret_gran;
275   return(offset);
276
277 }
278
279 /* uses the local ogg_stream storage in vf; this is important for
280    non-streaming input sources */
281 static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
282                           long **serialno_list, int *serialno_n,
283                           ogg_page *og_ptr){
284   ogg_page og;
285   ogg_packet op;
286   int i,ret;
287   int allbos=0;
288
289   if(!og_ptr){
290     ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
291     if(llret==OV_EREAD)return(OV_EREAD);
292     if(llret<0)return(OV_ENOTVORBIS);
293     og_ptr=&og;
294   }
295
296   vorbis_info_init(vi);
297   vorbis_comment_init(vc);
298   vf->ready_state=OPENED;
299
300   /* extract the serialnos of all BOS pages + the first set of vorbis
301      headers we see in the link */
302
303   while(ogg_page_bos(og_ptr)){
304     if(serialno_list){
305       if(_lookup_page_serialno(og_ptr,*serialno_list,*serialno_n)){
306         /* a dupe serialnumber in an initial header packet set == invalid stream */
307         if(*serialno_list)_ogg_free(*serialno_list);
308         *serialno_list=0;
309         *serialno_n=0;
310         ret=OV_EBADHEADER;
311         goto bail_header;
312       }
313
314       _add_serialno(og_ptr,serialno_list,serialno_n);
315     }
316
317     if(vf->ready_state<STREAMSET){
318       /* we don't have a vorbis stream in this link yet, so begin
319          prospective stream setup. We need a stream to get packets */
320       ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
321       ogg_stream_pagein(&vf->os,og_ptr);
322
323       if(ogg_stream_packetout(&vf->os,&op) > 0 &&
324          vorbis_synthesis_idheader(&op)){
325         /* vorbis header; continue setup */
326         vf->ready_state=STREAMSET;
327         if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
328           ret=OV_EBADHEADER;
329           goto bail_header;
330         }
331       }
332     }
333
334     /* get next page */
335     {
336       ogg_int64_t llret=_get_next_page(vf,og_ptr,CHUNKSIZE);
337       if(llret==OV_EREAD){
338         ret=OV_EREAD;
339         goto bail_header;
340       }
341       if(llret<0){
342         ret=OV_ENOTVORBIS;
343         goto bail_header;
344       }
345
346       /* if this page also belongs to our vorbis stream, submit it and break */
347       if(vf->ready_state==STREAMSET &&
348          vf->os.serialno == ogg_page_serialno(og_ptr)){
349         ogg_stream_pagein(&vf->os,og_ptr);
350         break;
351       }
352     }
353   }
354
355   if(vf->ready_state!=STREAMSET){
356     ret = OV_ENOTVORBIS;
357     goto bail_header;
358   }
359
360   while(1){
361
362     i=0;
363     while(i<2){ /* get a page loop */
364
365       while(i<2){ /* get a packet loop */
366
367         int result=ogg_stream_packetout(&vf->os,&op);
368         if(result==0)break;
369         if(result==-1){
370           ret=OV_EBADHEADER;
371           goto bail_header;
372         }
373
374         if((ret=vorbis_synthesis_headerin(vi,vc,&op)))
375           goto bail_header;
376
377         i++;
378       }
379
380       while(i<2){
381         if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
382           ret=OV_EBADHEADER;
383           goto bail_header;
384         }
385
386         /* if this page belongs to the correct stream, go parse it */
387         if(vf->os.serialno == ogg_page_serialno(og_ptr)){
388           ogg_stream_pagein(&vf->os,og_ptr);
389           break;
390         }
391
392         /* if we never see the final vorbis headers before the link
393            ends, abort */
394         if(ogg_page_bos(og_ptr)){
395           if(allbos){
396             ret = OV_EBADHEADER;
397             goto bail_header;
398           }else
399             allbos=1;
400         }
401
402         /* otherwise, keep looking */
403       }
404     }
405
406     return 0;
407   }
408
409  bail_header:
410   vorbis_info_clear(vi);
411   vorbis_comment_clear(vc);
412   vf->ready_state=OPENED;
413
414   return ret;
415 }
416
417 /* Starting from current cursor position, get initial PCM offset of
418    next page.  Consumes the page in the process without decoding
419    audio, however this is only called during stream parsing upon
420    seekable open. */
421 static ogg_int64_t _initial_pcmoffset(OggVorbis_File *vf, vorbis_info *vi){
422   ogg_page    og;
423   ogg_int64_t accumulated=0;
424   long        lastblock=-1;
425   int         result;
426   int         serialno = vf->os.serialno;
427
428   while(1){
429     ogg_packet op;
430     if(_get_next_page(vf,&og,-1)<0)
431       break; /* should not be possible unless the file is truncated/mangled */
432
433     if(ogg_page_bos(&og)) break;
434     if(ogg_page_serialno(&og)!=serialno) continue;
435
436     /* count blocksizes of all frames in the page */
437     ogg_stream_pagein(&vf->os,&og);
438     while((result=ogg_stream_packetout(&vf->os,&op))){
439       if(result>0){ /* ignore holes */
440         long thisblock=vorbis_packet_blocksize(vi,&op);
441         if(lastblock!=-1)
442           accumulated+=(lastblock+thisblock)>>2;
443         lastblock=thisblock;
444       }
445     }
446
447     if(ogg_page_granulepos(&og)!=-1){
448       /* pcm offset of last packet on the first audio page */
449       accumulated= ogg_page_granulepos(&og)-accumulated;
450       break;
451     }
452   }
453
454   /* less than zero?  Either a corrupt file or a stream with samples
455      trimmed off the beginning, a normal occurrence; in both cases set
456      the offset to zero */
457   if(accumulated<0)accumulated=0;
458
459   return accumulated;
460 }
461
462 /* finds each bitstream link one at a time using a bisection search
463    (has to begin by knowing the offset of the lb's initial page).
464    Recurses for each link so it can alloc the link storage after
465    finding them all, then unroll and fill the cache at the same time */
466 static int _bisect_forward_serialno(OggVorbis_File *vf,
467                                     ogg_int64_t begin,
468                                     ogg_int64_t searched,
469                                     ogg_int64_t end,
470                                     ogg_int64_t endgran,
471                                     int endserial,
472                                     long *currentno_list,
473                                     int  currentnos,
474                                     long m){
475   ogg_int64_t pcmoffset;
476   ogg_int64_t dataoffset=searched;
477   ogg_int64_t endsearched=end;
478   ogg_int64_t next=end;
479   ogg_int64_t searchgran=-1;
480   ogg_page og;
481   ogg_int64_t ret,last;
482   int serialno = vf->os.serialno;
483
484   /* invariants:
485      we have the headers and serialnos for the link beginning at 'begin'
486      we have the offset and granpos of the last page in the file (potentially
487        not a page we care about)
488   */
489
490   /* Is the last page in our list of current serialnumbers? */
491   if(_lookup_serialno(endserial,currentno_list,currentnos)){
492
493     /* last page is in the starting serialno list, so we've bisected
494        down to (or just started with) a single link.  Now we need to
495        find the last vorbis page belonging to the first vorbis stream
496        for this link. */
497     searched = end;
498     while(endserial != serialno){
499       endserial = serialno;
500       searched=_get_prev_page_serial(vf,searched,currentno_list,currentnos,&endserial,&endgran);
501     }
502
503     vf->links=m+1;
504     if(vf->offsets)_ogg_free(vf->offsets);
505     if(vf->serialnos)_ogg_free(vf->serialnos);
506     if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
507
508     vf->offsets=_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
509     vf->vi=_ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
510     vf->vc=_ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
511     vf->serialnos=_ogg_malloc(vf->links*sizeof(*vf->serialnos));
512     vf->dataoffsets=_ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
513     vf->pcmlengths=_ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
514
515     vf->offsets[m+1]=end;
516     vf->offsets[m]=begin;
517     vf->pcmlengths[m*2+1]=(endgran<0?0:endgran);
518
519   }else{
520
521     /* last page is not in the starting stream's serial number list,
522        so we have multiple links.  Find where the stream that begins
523        our bisection ends. */
524
525     long *next_serialno_list=NULL;
526     int next_serialnos=0;
527     vorbis_info vi;
528     vorbis_comment vc;
529     int testserial = serialno+1;
530
531     /* the below guards against garbage seperating the last and
532        first pages of two links. */
533     while(searched<endsearched){
534       ogg_int64_t bisect;
535
536       if(endsearched-searched<CHUNKSIZE){
537         bisect=searched;
538       }else{
539         bisect=(searched+endsearched)/2;
540       }
541
542       ret=_seek_helper(vf,bisect);
543       if(ret)return(ret);
544
545       last=_get_next_page(vf,&og,-1);
546       if(last==OV_EREAD)return(OV_EREAD);
547       if(last<0 || !_lookup_page_serialno(&og,currentno_list,currentnos)){
548         endsearched=bisect;
549         if(last>=0)next=last;
550       }else{
551         searched=vf->offset;
552       }
553     }
554
555     /* Bisection point found */
556     /* for the time being, fetch end PCM offset the simple way */
557     searched = next;
558     while(testserial != serialno){
559       testserial = serialno;
560       searched = _get_prev_page_serial(vf,searched,currentno_list,currentnos,&testserial,&searchgran);
561     }
562
563     ret=_seek_helper(vf,next);
564     if(ret)return(ret);
565
566     ret=_fetch_headers(vf,&vi,&vc,&next_serialno_list,&next_serialnos,NULL);
567     if(ret)return(ret);
568     serialno = vf->os.serialno;
569     dataoffset = vf->offset;
570
571     /* this will consume a page, however the next bisection always
572        starts with a raw seek */
573     pcmoffset = _initial_pcmoffset(vf,&vi);
574
575     ret=_bisect_forward_serialno(vf,next,vf->offset,end,endgran,endserial,
576                                  next_serialno_list,next_serialnos,m+1);
577     if(ret)return(ret);
578
579     if(next_serialno_list)_ogg_free(next_serialno_list);
580
581     vf->offsets[m+1]=next;
582     vf->serialnos[m+1]=serialno;
583     vf->dataoffsets[m+1]=dataoffset;
584
585     vf->vi[m+1]=vi;
586     vf->vc[m+1]=vc;
587
588     vf->pcmlengths[m*2+1]=searchgran;
589     vf->pcmlengths[m*2+2]=pcmoffset;
590     vf->pcmlengths[m*2+3]-=pcmoffset;
591     if(vf->pcmlengths[m*2+3]<0)vf->pcmlengths[m*2+3]=0;
592   }
593   return(0);
594 }
595
596 static int _make_decode_ready(OggVorbis_File *vf){
597   if(vf->ready_state>STREAMSET)return 0;
598   if(vf->ready_state<STREAMSET)return OV_EFAULT;
599   if(vf->seekable){
600     if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
601       return OV_EBADLINK;
602   }else{
603     if(vorbis_synthesis_init(&vf->vd,vf->vi))
604       return OV_EBADLINK;
605   }
606   vorbis_block_init(&vf->vd,&vf->vb);
607   vf->ready_state=INITSET;
608   vf->bittrack=0.f;
609   vf->samptrack=0.f;
610   return 0;
611 }
612
613 static int _open_seekable2(OggVorbis_File *vf){
614   ogg_int64_t dataoffset=vf->dataoffsets[0],end,endgran=-1;
615   int endserial=vf->os.serialno;
616   int serialno=vf->os.serialno;
617
618   /* we're partially open and have a first link header state in
619      storage in vf */
620
621   /* fetch initial PCM offset */
622   ogg_int64_t pcmoffset = _initial_pcmoffset(vf,vf->vi);
623
624   /* we can seek, so set out learning all about this file */
625   if(vf->callbacks.seek_func && vf->callbacks.tell_func){
626     (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
627     vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
628   }else{
629     vf->offset=vf->end=-1;
630   }
631
632   /* If seek_func is implemented, tell_func must also be implemented */
633   if(vf->end==-1) return(OV_EINVAL);
634
635   /* Get the offset of the last page of the physical bitstream, or, if
636      we're lucky the last vorbis page of this link as most OggVorbis
637      files will contain a single logical bitstream */
638   end=_get_prev_page_serial(vf,vf->end,vf->serialnos+2,vf->serialnos[1],&endserial,&endgran);
639   if(end<0)return(end);
640
641   /* now determine bitstream structure recursively */
642   if(_bisect_forward_serialno(vf,0,dataoffset,end,endgran,endserial,
643                               vf->serialnos+2,vf->serialnos[1],0)<0)return(OV_EREAD);
644
645   vf->offsets[0]=0;
646   vf->serialnos[0]=serialno;
647   vf->dataoffsets[0]=dataoffset;
648   vf->pcmlengths[0]=pcmoffset;
649   vf->pcmlengths[1]-=pcmoffset;
650   if(vf->pcmlengths[1]<0)vf->pcmlengths[1]=0;
651
652   return(ov_raw_seek(vf,dataoffset));
653 }
654
655 /* clear out the current logical bitstream decoder */
656 static void _decode_clear(OggVorbis_File *vf){
657   vorbis_dsp_clear(&vf->vd);
658   vorbis_block_clear(&vf->vb);
659   vf->ready_state=OPENED;
660 }
661
662 /* fetch and process a packet.  Handles the case where we're at a
663    bitstream boundary and dumps the decoding machine.  If the decoding
664    machine is unloaded, it loads it.  It also keeps pcm_offset up to
665    date (seek and read both use this.  seek uses a special hack with
666    readp).
667
668    return: <0) error, OV_HOLE (lost packet) or OV_EOF
669             0) need more data (only if readp==0)
670             1) got a packet
671 */
672
673 static int _fetch_and_process_packet(OggVorbis_File *vf,
674                                      ogg_packet *op_in,
675                                      int readp,
676                                      int spanp){
677   ogg_page og;
678
679   /* handle one packet.  Try to fetch it from current stream state */
680   /* extract packets from page */
681   while(1){
682
683     if(vf->ready_state==STREAMSET){
684       int ret=_make_decode_ready(vf);
685       if(ret<0)return ret;
686     }
687
688     /* process a packet if we can. */
689
690     if(vf->ready_state==INITSET){
691       int hs=vorbis_synthesis_halfrate_p(vf->vi);
692
693       while(1) {
694               ogg_packet op;
695               ogg_packet *op_ptr=(op_in?op_in:&op);
696         int result=ogg_stream_packetout(&vf->os,op_ptr);
697         ogg_int64_t granulepos;
698
699         op_in=NULL;
700         if(result==-1)return(OV_HOLE); /* hole in the data. */
701         if(result>0){
702           /* got a packet.  process it */
703           granulepos=op_ptr->granulepos;
704           if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
705                                                     header handling.  The
706                                                     header packets aren't
707                                                     audio, so if/when we
708                                                     submit them,
709                                                     vorbis_synthesis will
710                                                     reject them */
711
712             /* suck in the synthesis data and track bitrate */
713             {
714               int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
715               /* for proper use of libvorbis within libvorbisfile,
716                  oldsamples will always be zero. */
717               if(oldsamples)return(OV_EFAULT);
718
719               vorbis_synthesis_blockin(&vf->vd,&vf->vb);
720               vf->samptrack+=(vorbis_synthesis_pcmout(&vf->vd,NULL)<<hs);
721               vf->bittrack+=op_ptr->bytes*8;
722             }
723
724             /* update the pcm offset. */
725             if(granulepos!=-1 && !op_ptr->e_o_s){
726               int link=(vf->seekable?vf->current_link:0);
727               int i,samples;
728
729               /* this packet has a pcm_offset on it (the last packet
730                  completed on a page carries the offset) After processing
731                  (above), we know the pcm position of the *last* sample
732                  ready to be returned. Find the offset of the *first*
733
734                  As an aside, this trick is inaccurate if we begin
735                  reading anew right at the last page; the end-of-stream
736                  granulepos declares the last frame in the stream, and the
737                  last packet of the last page may be a partial frame.
738                  So, we need a previous granulepos from an in-sequence page
739                  to have a reference point.  Thus the !op_ptr->e_o_s clause
740                  above */
741
742               if(vf->seekable && link>0)
743                 granulepos-=vf->pcmlengths[link*2];
744               if(granulepos<0)granulepos=0; /* actually, this
745                                                shouldn't be possible
746                                                here unless the stream
747                                                is very broken */
748
749               samples=(vorbis_synthesis_pcmout(&vf->vd,NULL)<<hs);
750
751               granulepos-=samples;
752               for(i=0;i<link;i++)
753                 granulepos+=vf->pcmlengths[i*2+1];
754               vf->pcm_offset=granulepos;
755             }
756             return(1);
757           }
758         }
759         else
760           break;
761       }
762     }
763
764     if(vf->ready_state>=OPENED){
765       ogg_int64_t ret;
766
767       while(1){
768         /* the loop is not strictly necessary, but there's no sense in
769            doing the extra checks of the larger loop for the common
770            case in a multiplexed bistream where the page is simply
771            part of a different logical bitstream; keep reading until
772            we get one with the correct serialno */
773
774         if(!readp)return(0);
775         if((ret=_get_next_page(vf,&og,-1))<0){
776           return(OV_EOF); /* eof. leave unitialized */
777         }
778
779         /* bitrate tracking; add the header's bytes here, the body bytes
780            are done by packet above */
781         vf->bittrack+=og.header_len*8;
782
783         if(vf->ready_state==INITSET){
784           if(vf->current_serialno!=ogg_page_serialno(&og)){
785
786             /* two possibilities:
787                1) our decoding just traversed a bitstream boundary
788                2) another stream is multiplexed into this logical section */
789
790             if(ogg_page_bos(&og)){
791               /* boundary case */
792               if(!spanp)
793                 return(OV_EOF);
794
795               _decode_clear(vf);
796
797               if(!vf->seekable){
798                 vorbis_info_clear(vf->vi);
799                 vorbis_comment_clear(vf->vc);
800               }
801               break;
802
803             }else
804               continue; /* possibility #2 */
805           }
806         }
807
808         break;
809       }
810     }
811
812     /* Do we need to load a new machine before submitting the page? */
813     /* This is different in the seekable and non-seekable cases.
814
815        In the seekable case, we already have all the header
816        information loaded and cached; we just initialize the machine
817        with it and continue on our merry way.
818
819        In the non-seekable (streaming) case, we'll only be at a
820        boundary if we just left the previous logical bitstream and
821        we're now nominally at the header of the next bitstream
822     */
823
824     if(vf->ready_state!=INITSET){
825       int link;
826
827       if(vf->ready_state<STREAMSET){
828         if(vf->seekable){
829           long serialno = ogg_page_serialno(&og);
830
831           /* match the serialno to bitstream section.  We use this rather than
832              offset positions to avoid problems near logical bitstream
833              boundaries */
834
835           for(link=0;link<vf->links;link++)
836             if(vf->serialnos[link]==serialno)break;
837
838           if(link==vf->links) continue; /* not the desired Vorbis
839                                            bitstream section; keep
840                                            trying */
841
842           vf->current_serialno=serialno;
843           vf->current_link=link;
844
845           ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
846           vf->ready_state=STREAMSET;
847
848         }else{
849           /* we're streaming */
850           /* fetch the three header packets, build the info struct */
851
852           int ret=_fetch_headers(vf,vf->vi,vf->vc,NULL,NULL,&og);
853           if(ret)return(ret);
854           vf->current_serialno=vf->os.serialno;
855           vf->current_link++;
856           link=0;
857         }
858       }
859     }
860
861     /* the buffered page is the data we want, and we're ready for it;
862        add it to the stream state */
863     ogg_stream_pagein(&vf->os,&og);
864
865   }
866 }
867
868 /* if, eg, 64 bit stdio is configured by default, this will build with
869    fseek64 */
870 static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
871   if(f==NULL)return(-1);
872   return fseek(f,off,whence);
873 }
874
875 static int _ov_open1(void *f,OggVorbis_File *vf,const char *initial,
876                      long ibytes, ov_callbacks callbacks){
877   int offsettest=((f && callbacks.seek_func)?callbacks.seek_func(f,0,SEEK_CUR):-1);
878   long *serialno_list=NULL;
879   int serialno_list_size=0;
880   int ret;
881
882   memset(vf,0,sizeof(*vf));
883   vf->datasource=f;
884   vf->callbacks = callbacks;
885
886   /* init the framing state */
887   ogg_sync_init(&vf->oy);
888
889   /* perhaps some data was previously read into a buffer for testing
890      against other stream types.  Allow initialization from this
891      previously read data (especially as we may be reading from a
892      non-seekable stream) */
893   if(initial){
894     char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
895     memcpy(buffer,initial,ibytes);
896     ogg_sync_wrote(&vf->oy,ibytes);
897   }
898
899   /* can we seek? Stevens suggests the seek test was portable */
900   if(offsettest!=-1)vf->seekable=1;
901
902   /* No seeking yet; Set up a 'single' (current) logical bitstream
903      entry for partial open */
904   vf->links=1;
905   vf->vi=_ogg_calloc(vf->links,sizeof(*vf->vi));
906   vf->vc=_ogg_calloc(vf->links,sizeof(*vf->vc));
907   ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
908
909   /* Fetch all BOS pages, store the vorbis header and all seen serial
910      numbers, load subsequent vorbis setup headers */
911   if((ret=_fetch_headers(vf,vf->vi,vf->vc,&serialno_list,&serialno_list_size,NULL))<0){
912     vf->datasource=NULL;
913     ov_clear(vf);
914   }else{
915     /* serial number list for first link needs to be held somewhere
916        for second stage of seekable stream open; this saves having to
917        seek/reread first link's serialnumber data then. */
918     vf->serialnos=_ogg_calloc(serialno_list_size+2,sizeof(*vf->serialnos));
919     vf->serialnos[0]=vf->current_serialno=vf->os.serialno;
920     vf->serialnos[1]=serialno_list_size;
921     memcpy(vf->serialnos+2,serialno_list,serialno_list_size*sizeof(*vf->serialnos));
922
923     vf->offsets=_ogg_calloc(1,sizeof(*vf->offsets));
924     vf->dataoffsets=_ogg_calloc(1,sizeof(*vf->dataoffsets));
925     vf->offsets[0]=0;
926     vf->dataoffsets[0]=vf->offset;
927
928     vf->ready_state=PARTOPEN;
929   }
930   if(serialno_list)_ogg_free(serialno_list);
931   return(ret);
932 }
933
934 static int _ov_open2(OggVorbis_File *vf){
935   if(vf->ready_state != PARTOPEN) return OV_EINVAL;
936   vf->ready_state=OPENED;
937   if(vf->seekable){
938     int ret=_open_seekable2(vf);
939     if(ret){
940       vf->datasource=NULL;
941       ov_clear(vf);
942     }
943     return(ret);
944   }else
945     vf->ready_state=STREAMSET;
946
947   return 0;
948 }
949
950
951 /* clear out the OggVorbis_File struct */
952 int ov_clear(OggVorbis_File *vf){
953   if(vf){
954     vorbis_block_clear(&vf->vb);
955     vorbis_dsp_clear(&vf->vd);
956     ogg_stream_clear(&vf->os);
957
958     if(vf->vi && vf->links){
959       int i;
960       for(i=0;i<vf->links;i++){
961         vorbis_info_clear(vf->vi+i);
962         vorbis_comment_clear(vf->vc+i);
963       }
964       _ogg_free(vf->vi);
965       _ogg_free(vf->vc);
966     }
967     if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
968     if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
969     if(vf->serialnos)_ogg_free(vf->serialnos);
970     if(vf->offsets)_ogg_free(vf->offsets);
971     ogg_sync_clear(&vf->oy);
972     if(vf->datasource && vf->callbacks.close_func)
973       (vf->callbacks.close_func)(vf->datasource);
974     memset(vf,0,sizeof(*vf));
975   }
976 #ifdef DEBUG_LEAKS
977   _VDBG_dump();
978 #endif
979   return(0);
980 }
981
982 /* inspects the OggVorbis file and finds/documents all the logical
983    bitstreams contained in it.  Tries to be tolerant of logical
984    bitstream sections that are truncated/woogie.
985
986    return: -1) error
987             0) OK
988 */
989
990 int ov_open_callbacks(void *f,OggVorbis_File *vf,
991     const char *initial,long ibytes,ov_callbacks callbacks){
992   int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
993   if(ret)return ret;
994   return _ov_open2(vf);
995 }
996
997 int ov_open(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes){
998   ov_callbacks callbacks = {
999     (size_t (*)(void *, size_t, size_t, void *))  fread,
1000     (int (*)(void *, ogg_int64_t, int))              _fseek64_wrap,
1001     (int (*)(void *))                             fclose,
1002     (long (*)(void *))                            ftell
1003   };
1004
1005   return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
1006 }
1007
1008 int ov_fopen(const char *path,OggVorbis_File *vf){
1009   int ret;
1010   FILE *f = fopen(path,"rb");
1011   if(!f) return -1;
1012
1013   ret = ov_open(f,vf,NULL,0);
1014   if(ret) fclose(f);
1015   return ret;
1016 }
1017
1018
1019 /* cheap hack for game usage where downsampling is desirable; there's
1020    no need for SRC as we can just do it cheaply in libvorbis. */
1021
1022 int ov_halfrate(OggVorbis_File *vf,int flag){
1023   int i;
1024   if(vf->vi==NULL)return OV_EINVAL;
1025   if(vf->ready_state>STREAMSET){
1026     /* clear out stream state; dumping the decode machine is needed to
1027        reinit the MDCT lookups. */
1028     vorbis_dsp_clear(&vf->vd);
1029     vorbis_block_clear(&vf->vb);
1030     vf->ready_state=STREAMSET;
1031     if(vf->pcm_offset>=0){
1032       ogg_int64_t pos=vf->pcm_offset;
1033       vf->pcm_offset=-1; /* make sure the pos is dumped if unseekable */
1034       ov_pcm_seek(vf,pos);
1035     }
1036   }
1037
1038   for(i=0;i<vf->links;i++){
1039     if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
1040       if(flag) ov_halfrate(vf,0);
1041       return OV_EINVAL;
1042     }
1043   }
1044   return 0;
1045 }
1046
1047 int ov_halfrate_p(OggVorbis_File *vf){
1048   if(vf->vi==NULL)return OV_EINVAL;
1049   return vorbis_synthesis_halfrate_p(vf->vi);
1050 }
1051
1052 /* Only partially open the vorbis file; test for Vorbisness, and load
1053    the headers for the first chain.  Do not seek (although test for
1054    seekability).  Use ov_test_open to finish opening the file, else
1055    ov_clear to close/free it. Same return codes as open.
1056
1057    Note that vorbisfile does _not_ take ownership of the file if the
1058    call fails; the calling applicaiton is responsible for closing the file
1059    if this call returns an error. */
1060
1061 int ov_test_callbacks(void *f,OggVorbis_File *vf,
1062     const char *initial,long ibytes,ov_callbacks callbacks)
1063 {
1064   return _ov_open1(f,vf,initial,ibytes,callbacks);
1065 }
1066
1067 int ov_test(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes){
1068   ov_callbacks callbacks = {
1069     (size_t (*)(void *, size_t, size_t, void *))  fread,
1070     (int (*)(void *, ogg_int64_t, int))              _fseek64_wrap,
1071     (int (*)(void *))                             fclose,
1072     (long (*)(void *))                            ftell
1073   };
1074
1075   return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
1076 }
1077
1078 int ov_test_open(OggVorbis_File *vf){
1079   if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
1080   return _ov_open2(vf);
1081 }
1082
1083 /* How many logical bitstreams in this physical bitstream? */
1084 long ov_streams(OggVorbis_File *vf){
1085   return vf->links;
1086 }
1087
1088 /* Is the FILE * associated with vf seekable? */
1089 long ov_seekable(OggVorbis_File *vf){
1090   return vf->seekable;
1091 }
1092
1093 /* returns the bitrate for a given logical bitstream or the entire
1094    physical bitstream.  If the file is open for random access, it will
1095    find the *actual* average bitrate.  If the file is streaming, it
1096    returns the nominal bitrate (if set) else the average of the
1097    upper/lower bounds (if set) else -1 (unset).
1098
1099    If you want the actual bitrate field settings, get them from the
1100    vorbis_info structs */
1101
1102 long ov_bitrate(OggVorbis_File *vf,int i){
1103   if(vf->ready_state<OPENED)return(OV_EINVAL);
1104   if(i>=vf->links)return(OV_EINVAL);
1105   if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
1106   if(i<0){
1107     ogg_int64_t bits=0;
1108     int i;
1109     float br;
1110     for(i=0;i<vf->links;i++)
1111       bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
1112     /* This once read: return(rint(bits/ov_time_total(vf,-1)));
1113      * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
1114      * so this is slightly transformed to make it work.
1115      */
1116     br = bits/ov_time_total(vf,-1);
1117     return(rint(br));
1118   }else{
1119     if(vf->seekable){
1120       /* return the actual bitrate */
1121       return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
1122     }else{
1123       /* return nominal if set */
1124       if(vf->vi[i].bitrate_nominal>0){
1125         return vf->vi[i].bitrate_nominal;
1126       }else{
1127         if(vf->vi[i].bitrate_upper>0){
1128           if(vf->vi[i].bitrate_lower>0){
1129             return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
1130           }else{
1131             return vf->vi[i].bitrate_upper;
1132           }
1133         }
1134         return(OV_FALSE);
1135       }
1136     }
1137   }
1138 }
1139
1140 /* returns the actual bitrate since last call.  returns -1 if no
1141    additional data to offer since last call (or at beginning of stream),
1142    EINVAL if stream is only partially open
1143 */
1144 long ov_bitrate_instant(OggVorbis_File *vf){
1145   int link=(vf->seekable?vf->current_link:0);
1146   long ret;
1147   if(vf->ready_state<OPENED)return(OV_EINVAL);
1148   if(vf->samptrack==0)return(OV_FALSE);
1149   ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
1150   vf->bittrack=0.f;
1151   vf->samptrack=0.f;
1152   return(ret);
1153 }
1154
1155 /* Guess */
1156 long ov_serialnumber(OggVorbis_File *vf,int i){
1157   if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
1158   if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
1159   if(i<0){
1160     return(vf->current_serialno);
1161   }else{
1162     return(vf->serialnos[i]);
1163   }
1164 }
1165
1166 /* returns: total raw (compressed) length of content if i==-1
1167             raw (compressed) length of that logical bitstream for i==0 to n
1168             OV_EINVAL if the stream is not seekable (we can't know the length)
1169             or if stream is only partially open
1170 */
1171 ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
1172   if(vf->ready_state<OPENED)return(OV_EINVAL);
1173   if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
1174   if(i<0){
1175     ogg_int64_t acc=0;
1176     int i;
1177     for(i=0;i<vf->links;i++)
1178       acc+=ov_raw_total(vf,i);
1179     return(acc);
1180   }else{
1181     return(vf->offsets[i+1]-vf->offsets[i]);
1182   }
1183 }
1184
1185 /* returns: total PCM length (samples) of content if i==-1 PCM length
1186             (samples) of that logical bitstream for i==0 to n
1187             OV_EINVAL if the stream is not seekable (we can't know the
1188             length) or only partially open
1189 */
1190 ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
1191   if(vf->ready_state<OPENED)return(OV_EINVAL);
1192   if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
1193   if(i<0){
1194     ogg_int64_t acc=0;
1195     int i;
1196     for(i=0;i<vf->links;i++)
1197       acc+=ov_pcm_total(vf,i);
1198     return(acc);
1199   }else{
1200     return(vf->pcmlengths[i*2+1]);
1201   }
1202 }
1203
1204 /* returns: total seconds of content if i==-1
1205             seconds in that logical bitstream for i==0 to n
1206             OV_EINVAL if the stream is not seekable (we can't know the
1207             length) or only partially open
1208 */
1209 double ov_time_total(OggVorbis_File *vf,int i){
1210   if(vf->ready_state<OPENED)return(OV_EINVAL);
1211   if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
1212   if(i<0){
1213     double acc=0;
1214     int i;
1215     for(i=0;i<vf->links;i++)
1216       acc+=ov_time_total(vf,i);
1217     return(acc);
1218   }else{
1219     return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
1220   }
1221 }
1222
1223 /* seek to an offset relative to the *compressed* data. This also
1224    scans packets to update the PCM cursor. It will cross a logical
1225    bitstream boundary, but only if it can't get any packets out of the
1226    tail of the bitstream we seek to (so no surprises).
1227
1228    returns zero on success, nonzero on failure */
1229
1230 int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
1231   ogg_stream_state work_os;
1232   int ret;
1233
1234   if(vf->ready_state<OPENED)return(OV_EINVAL);
1235   if(!vf->seekable)
1236     return(OV_ENOSEEK); /* don't dump machine if we can't seek */
1237
1238   if(pos<0 || pos>vf->end)return(OV_EINVAL);
1239
1240   /* is the seek position outside our current link [if any]? */
1241   if(vf->ready_state>=STREAMSET){
1242     if(pos<vf->offsets[vf->current_link] || pos>=vf->offsets[vf->current_link+1])
1243       _decode_clear(vf); /* clear out stream state */
1244   }
1245
1246   /* don't yet clear out decoding machine (if it's initialized), in
1247      the case we're in the same link.  Restart the decode lapping, and
1248      let _fetch_and_process_packet deal with a potential bitstream
1249      boundary */
1250   vf->pcm_offset=-1;
1251   ogg_stream_reset_serialno(&vf->os,
1252                             vf->current_serialno); /* must set serialno */
1253   vorbis_synthesis_restart(&vf->vd);
1254
1255   ret=_seek_helper(vf,pos);
1256   if(ret)goto seek_error;
1257
1258   /* we need to make sure the pcm_offset is set, but we don't want to
1259      advance the raw cursor past good packets just to get to the first
1260      with a granulepos.  That's not equivalent behavior to beginning
1261      decoding as immediately after the seek position as possible.
1262
1263      So, a hack.  We use two stream states; a local scratch state and
1264      the shared vf->os stream state.  We use the local state to
1265      scan, and the shared state as a buffer for later decode.
1266
1267      Unfortuantely, on the last page we still advance to last packet
1268      because the granulepos on the last page is not necessarily on a
1269      packet boundary, and we need to make sure the granpos is
1270      correct.
1271   */
1272
1273   {
1274     ogg_page og;
1275     ogg_packet op;
1276     int lastblock=0;
1277     int accblock=0;
1278     int thisblock=0;
1279     int lastflag=0;
1280     int firstflag=0;
1281     ogg_int64_t pagepos=-1;
1282
1283     ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
1284     ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
1285                                    return from not necessarily
1286                                    starting from the beginning */
1287
1288     while(1){
1289       if(vf->ready_state>=STREAMSET){
1290         /* snarf/scan a packet if we can */
1291         int result=ogg_stream_packetout(&work_os,&op);
1292
1293         if(result>0){
1294
1295           if(vf->vi[vf->current_link].codec_setup){
1296             thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
1297             if(thisblock<0){
1298               ogg_stream_packetout(&vf->os,NULL);
1299               thisblock=0;
1300             }else{
1301
1302               /* We can't get a guaranteed correct pcm position out of the
1303                  last page in a stream because it might have a 'short'
1304                  granpos, which can only be detected in the presence of a
1305                  preceding page.  However, if the last page is also the first
1306                  page, the granpos rules of a first page take precedence.  Not
1307                  only that, but for first==last, the EOS page must be treated
1308                  as if its a normal first page for the stream to open/play. */
1309               if(lastflag && !firstflag)
1310                 ogg_stream_packetout(&vf->os,NULL);
1311               else
1312                 if(lastblock)accblock+=(lastblock+thisblock)>>2;
1313             }
1314
1315             if(op.granulepos!=-1){
1316               int i,link=vf->current_link;
1317               ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
1318               if(granulepos<0)granulepos=0;
1319
1320               for(i=0;i<link;i++)
1321                 granulepos+=vf->pcmlengths[i*2+1];
1322               vf->pcm_offset=granulepos-accblock;
1323               if(vf->pcm_offset<0)vf->pcm_offset=0;
1324               break;
1325             }
1326             lastblock=thisblock;
1327             continue;
1328           }else
1329             ogg_stream_packetout(&vf->os,NULL);
1330         }
1331       }
1332
1333       if(!lastblock){
1334         pagepos=_get_next_page(vf,&og,-1);
1335         if(pagepos<0){
1336           vf->pcm_offset=ov_pcm_total(vf,-1);
1337           break;
1338         }
1339       }else{
1340         /* huh?  Bogus stream with packets but no granulepos */
1341         vf->pcm_offset=-1;
1342         break;
1343       }
1344
1345       /* has our decoding just traversed a bitstream boundary? */
1346       if(vf->ready_state>=STREAMSET){
1347         if(vf->current_serialno!=ogg_page_serialno(&og)){
1348
1349           /* two possibilities:
1350              1) our decoding just traversed a bitstream boundary
1351              2) another stream is multiplexed into this logical section? */
1352
1353           if(ogg_page_bos(&og)){
1354             /* we traversed */
1355             _decode_clear(vf); /* clear out stream state */
1356             ogg_stream_clear(&work_os);
1357           } /* else, do nothing; next loop will scoop another page */
1358         }
1359       }
1360
1361       if(vf->ready_state<STREAMSET){
1362         int link;
1363         long serialno = ogg_page_serialno(&og);
1364
1365         for(link=0;link<vf->links;link++)
1366           if(vf->serialnos[link]==serialno)break;
1367
1368         if(link==vf->links) continue; /* not the desired Vorbis
1369                                          bitstream section; keep
1370                                          trying */
1371         vf->current_link=link;
1372         vf->current_serialno=serialno;
1373         ogg_stream_reset_serialno(&vf->os,serialno);
1374         ogg_stream_reset_serialno(&work_os,serialno);
1375         vf->ready_state=STREAMSET;
1376         firstflag=(pagepos<=vf->dataoffsets[link]);
1377       }
1378
1379       ogg_stream_pagein(&vf->os,&og);
1380       ogg_stream_pagein(&work_os,&og);
1381       lastflag=ogg_page_eos(&og);
1382
1383     }
1384   }
1385
1386   ogg_stream_clear(&work_os);
1387   vf->bittrack=0.f;
1388   vf->samptrack=0.f;
1389   return(0);
1390
1391  seek_error:
1392   /* dump the machine so we're in a known state */
1393   vf->pcm_offset=-1;
1394   ogg_stream_clear(&work_os);
1395   _decode_clear(vf);
1396   return OV_EBADLINK;
1397 }
1398
1399 /* Page granularity seek (faster than sample granularity because we
1400    don't do the last bit of decode to find a specific sample).
1401
1402    Seek to the last [granule marked] page preceding the specified pos
1403    location, such that decoding past the returned point will quickly
1404    arrive at the requested position. */
1405 int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
1406   int link=-1;
1407   ogg_int64_t result=0;
1408   ogg_int64_t total=ov_pcm_total(vf,-1);
1409
1410   if(vf->ready_state<OPENED)return(OV_EINVAL);
1411   if(!vf->seekable)return(OV_ENOSEEK);
1412
1413   if(pos<0 || pos>total)return(OV_EINVAL);
1414
1415   /* which bitstream section does this pcm offset occur in? */
1416   for(link=vf->links-1;link>=0;link--){
1417     total-=vf->pcmlengths[link*2+1];
1418     if(pos>=total)break;
1419   }
1420
1421   /* Search within the logical bitstream for the page with the highest
1422      pcm_pos preceding pos.  If we're looking for a position on the
1423      first page, bisection will halt without finding our position as
1424      it's before the first explicit granulepos fencepost. That case is
1425      handled separately below.
1426
1427      There is a danger here; missing pages or incorrect frame number
1428      information in the bitstream could make our task impossible.
1429      Account for that (it would be an error condition) */
1430
1431   /* new search algorithm originally by HB (Nicholas Vinen) */
1432
1433   {
1434     ogg_int64_t end=vf->offsets[link+1];
1435     ogg_int64_t begin=vf->dataoffsets[link];
1436     ogg_int64_t begintime = vf->pcmlengths[link*2];
1437     ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
1438     ogg_int64_t target=pos-total+begintime;
1439     ogg_int64_t best=-1;
1440     int         got_page=0;
1441
1442     ogg_page og;
1443
1444     /* if we have only one page, there will be no bisection.  Grab the page here */
1445     if(begin==end){
1446       result=_seek_helper(vf,begin);
1447       if(result) goto seek_error;
1448
1449       result=_get_next_page(vf,&og,1);
1450       if(result<0) goto seek_error;
1451
1452       got_page=1;
1453     }
1454
1455     /* bisection loop */
1456     while(begin<end){
1457       ogg_int64_t bisect;
1458
1459       if(end-begin<CHUNKSIZE){
1460         bisect=begin;
1461       }else{
1462         /* take a (pretty decent) guess. */
1463         bisect=begin +
1464           (ogg_int64_t)((double)(target-begintime)*(end-begin)/(endtime-begintime))
1465           - CHUNKSIZE;
1466         if(bisect<begin+CHUNKSIZE)
1467           bisect=begin;
1468       }
1469
1470       result=_seek_helper(vf,bisect);
1471       if(result) goto seek_error;
1472
1473       /* read loop within the bisection loop */
1474       while(begin<end){
1475         result=_get_next_page(vf,&og,end-vf->offset);
1476         if(result==OV_EREAD) goto seek_error;
1477         if(result<0){
1478           /* there is no next page! */
1479           if(bisect<=begin+1)
1480               /* No bisection left to perform.  We've either found the
1481                  best candidate already or failed. Exit loop. */
1482             end=begin;
1483           else{
1484             /* We tried to load a fraction of the last page; back up a
1485                bit and try to get the whole last page */
1486             if(bisect==0) goto seek_error;
1487             bisect-=CHUNKSIZE;
1488
1489             /* don't repeat/loop on a read we've already performed */
1490             if(bisect<=begin)bisect=begin+1;
1491
1492             /* seek and cntinue bisection */
1493             result=_seek_helper(vf,bisect);
1494             if(result) goto seek_error;
1495           }
1496         }else{
1497           ogg_int64_t granulepos;
1498           got_page=1;
1499
1500           /* got a page. analyze it */
1501           /* only consider pages from primary vorbis stream */
1502           if(ogg_page_serialno(&og)!=vf->serialnos[link])
1503             continue;
1504
1505           /* only consider pages with the granulepos set */
1506           granulepos=ogg_page_granulepos(&og);
1507           if(granulepos==-1)continue;
1508
1509           if(granulepos<target){
1510             /* this page is a successful candidate! Set state */
1511
1512             best=result;  /* raw offset of packet with granulepos */
1513             begin=vf->offset; /* raw offset of next page */
1514             begintime=granulepos;
1515
1516             /* if we're before our target but within a short distance,
1517                don't bisect; read forward */
1518             if(target-begintime>44100)break;
1519
1520             bisect=begin; /* *not* begin + 1 as above */
1521           }else{
1522
1523             /* This is one of our pages, but the granpos is
1524                post-target; it is not a bisection return
1525                candidate. (The only way we'd use it is if it's the
1526                first page in the stream; we handle that case later
1527                outside the bisection) */
1528             if(bisect<=begin+1){
1529               /* No bisection left to perform.  We've either found the
1530                  best candidate already or failed. Exit loop. */
1531               end=begin;
1532             }else{
1533               if(end==vf->offset){
1534                 /* bisection read to the end; use the known page
1535                    boundary (result) to update bisection, back up a
1536                    little bit, and try again */
1537                 end=result;
1538                 bisect-=CHUNKSIZE;
1539                 if(bisect<=begin)bisect=begin+1;
1540                 result=_seek_helper(vf,bisect);
1541                 if(result) goto seek_error;
1542               }else{
1543                 /* Normal bisection */
1544                 end=bisect;
1545                 endtime=granulepos;
1546                 break;
1547               }
1548             }
1549           }
1550         }
1551       }
1552     }
1553
1554     /* Out of bisection: did it 'fail?' */
1555     if(best == -1){
1556
1557       /* Check the 'looking for data in first page' special case;
1558          bisection would 'fail' because our search target was before the
1559          first PCM granule position fencepost. */
1560
1561       if(got_page &&
1562          begin == vf->dataoffsets[link] &&
1563          ogg_page_serialno(&og)==vf->serialnos[link]){
1564
1565         /* Yes, this is the beginning-of-stream case. We already have
1566            our page, right at the beginning of PCM data.  Set state
1567            and return. */
1568
1569         vf->pcm_offset=total;
1570
1571         if(link!=vf->current_link){
1572           /* Different link; dump entire decode machine */
1573           _decode_clear(vf);
1574
1575           vf->current_link=link;
1576           vf->current_serialno=vf->serialnos[link];
1577           vf->ready_state=STREAMSET;
1578
1579         }else{
1580           vorbis_synthesis_restart(&vf->vd);
1581         }
1582
1583         ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
1584         ogg_stream_pagein(&vf->os,&og);
1585
1586       }else
1587         goto seek_error;
1588
1589     }else{
1590
1591       /* Bisection found our page. seek to it, update pcm offset. Easier case than
1592          raw_seek, don't keep packets preceding granulepos. */
1593
1594       ogg_page og;
1595       ogg_packet op;
1596
1597       /* seek */
1598       result=_seek_helper(vf,best);
1599       vf->pcm_offset=-1;
1600       if(result) goto seek_error;
1601       result=_get_next_page(vf,&og,-1);
1602       if(result<0) goto seek_error;
1603
1604       if(link!=vf->current_link){
1605         /* Different link; dump entire decode machine */
1606         _decode_clear(vf);
1607
1608         vf->current_link=link;
1609         vf->current_serialno=vf->serialnos[link];
1610         vf->ready_state=STREAMSET;
1611
1612       }else{
1613         vorbis_synthesis_restart(&vf->vd);
1614       }
1615
1616       ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
1617       ogg_stream_pagein(&vf->os,&og);
1618
1619       /* pull out all but last packet; the one with granulepos */
1620       while(1){
1621         result=ogg_stream_packetpeek(&vf->os,&op);
1622         if(result==0){
1623           /* No packet returned; we exited the bisection with 'best'
1624              pointing to a page with a granule position, so the packet
1625              finishing this page ('best') originated on a preceding
1626              page. Keep fetching previous pages until we get one with
1627              a granulepos or without the 'continued' flag set.  Then
1628              just use raw_seek for simplicity. */
1629           /* Do not rewind past the beginning of link data; if we do,
1630              it's either a bug or a broken stream */
1631           result=best;
1632           while(result>vf->dataoffsets[link]){
1633             result=_get_prev_page(vf,result,&og);
1634             if(result<0) goto seek_error;
1635             if(ogg_page_serialno(&og)==vf->current_serialno &&
1636                (ogg_page_granulepos(&og)>-1 ||
1637                 !ogg_page_continued(&og))){
1638               return ov_raw_seek(vf,result);
1639             }
1640           }
1641         }
1642         if(result<0){
1643           result = OV_EBADPACKET;
1644           goto seek_error;
1645         }
1646         if(op.granulepos!=-1){
1647           vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
1648           if(vf->pcm_offset<0)vf->pcm_offset=0;
1649           vf->pcm_offset+=total;
1650           break;
1651         }else
1652           result=ogg_stream_packetout(&vf->os,NULL);
1653       }
1654     }
1655   }
1656
1657   /* verify result */
1658   if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
1659     result=OV_EFAULT;
1660     goto seek_error;
1661   }
1662   vf->bittrack=0.f;
1663   vf->samptrack=0.f;
1664   return(0);
1665
1666  seek_error:
1667   /* dump machine so we're in a known state */
1668   vf->pcm_offset=-1;
1669   _decode_clear(vf);
1670   return (int)result;
1671 }
1672
1673 /* seek to a sample offset relative to the decompressed pcm stream
1674    returns zero on success, nonzero on failure */
1675
1676 int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
1677   int thisblock,lastblock=0;
1678   int ret=ov_pcm_seek_page(vf,pos);
1679   if(ret<0)return(ret);
1680   if((ret=_make_decode_ready(vf)))return ret;
1681
1682   /* discard leading packets we don't need for the lapping of the
1683      position we want; don't decode them */
1684
1685   while(1){
1686     ogg_packet op;
1687     ogg_page og;
1688
1689     int ret=ogg_stream_packetpeek(&vf->os,&op);
1690     if(ret>0){
1691       thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
1692       if(thisblock<0){
1693         ogg_stream_packetout(&vf->os,NULL);
1694         continue; /* non audio packet */
1695       }
1696       if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
1697
1698       if(vf->pcm_offset+((thisblock+
1699                           vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
1700
1701       /* remove the packet from packet queue and track its granulepos */
1702       ogg_stream_packetout(&vf->os,NULL);
1703       vorbis_synthesis_trackonly(&vf->vb,&op);  /* set up a vb with
1704                                                    only tracking, no
1705                                                    pcm_decode */
1706       vorbis_synthesis_blockin(&vf->vd,&vf->vb);
1707
1708       /* end of logical stream case is hard, especially with exact
1709          length positioning. */
1710
1711       if(op.granulepos>-1){
1712         int i;
1713         /* always believe the stream markers */
1714         vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
1715         if(vf->pcm_offset<0)vf->pcm_offset=0;
1716         for(i=0;i<vf->current_link;i++)
1717           vf->pcm_offset+=vf->pcmlengths[i*2+1];
1718       }
1719
1720       lastblock=thisblock;
1721
1722     }else{
1723       if(ret<0 && ret!=OV_HOLE)break;
1724
1725       /* suck in a new page */
1726       if(_get_next_page(vf,&og,-1)<0)break;
1727       if(ogg_page_bos(&og))_decode_clear(vf);
1728
1729       if(vf->ready_state<STREAMSET){
1730         long serialno=ogg_page_serialno(&og);
1731         int link;
1732
1733         for(link=0;link<vf->links;link++)
1734           if(vf->serialnos[link]==serialno)break;
1735         if(link==vf->links) continue;
1736         vf->current_link=link;
1737
1738         vf->ready_state=STREAMSET;
1739         vf->current_serialno=ogg_page_serialno(&og);
1740         ogg_stream_reset_serialno(&vf->os,serialno);
1741         ret=_make_decode_ready(vf);
1742         if(ret)return ret;
1743         lastblock=0;
1744       }
1745
1746       ogg_stream_pagein(&vf->os,&og);
1747     }
1748   }
1749
1750   vf->bittrack=0.f;
1751   vf->samptrack=0.f;
1752   /* discard samples until we reach the desired position. Crossing a
1753      logical bitstream boundary with abandon is OK. */
1754   {
1755     /* note that halfrate could be set differently in each link, but
1756        vorbisfile encoforces all links are set or unset */
1757     int hs=vorbis_synthesis_halfrate_p(vf->vi);
1758     while(vf->pcm_offset<((pos>>hs)<<hs)){
1759       ogg_int64_t target=(pos-vf->pcm_offset)>>hs;
1760       long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
1761
1762       if(samples>target)samples=target;
1763       vorbis_synthesis_read(&vf->vd,samples);
1764       vf->pcm_offset+=samples<<hs;
1765
1766       if(samples<target)
1767         if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
1768           vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
1769     }
1770   }
1771   return 0;
1772 }
1773
1774 /* seek to a playback time relative to the decompressed pcm stream
1775    returns zero on success, nonzero on failure */
1776 int ov_time_seek(OggVorbis_File *vf,double seconds){
1777   /* translate time to PCM position and call ov_pcm_seek */
1778
1779   int link=-1;
1780   ogg_int64_t pcm_total=0;
1781   double time_total=0.;
1782
1783   if(vf->ready_state<OPENED)return(OV_EINVAL);
1784   if(!vf->seekable)return(OV_ENOSEEK);
1785   if(seconds<0)return(OV_EINVAL);
1786
1787   /* which bitstream section does this time offset occur in? */
1788   for(link=0;link<vf->links;link++){
1789     double addsec = ov_time_total(vf,link);
1790     if(seconds<time_total+addsec)break;
1791     time_total+=addsec;
1792     pcm_total+=vf->pcmlengths[link*2+1];
1793   }
1794
1795   if(link==vf->links)return(OV_EINVAL);
1796
1797   /* enough information to convert time offset to pcm offset */
1798   {
1799     ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
1800     return(ov_pcm_seek(vf,target));
1801   }
1802 }
1803
1804 /* page-granularity version of ov_time_seek
1805    returns zero on success, nonzero on failure */
1806 int ov_time_seek_page(OggVorbis_File *vf,double seconds){
1807   /* translate time to PCM position and call ov_pcm_seek */
1808
1809   int link=-1;
1810   ogg_int64_t pcm_total=0;
1811   double time_total=0.;
1812
1813   if(vf->ready_state<OPENED)return(OV_EINVAL);
1814   if(!vf->seekable)return(OV_ENOSEEK);
1815   if(seconds<0)return(OV_EINVAL);
1816
1817   /* which bitstream section does this time offset occur in? */
1818   for(link=0;link<vf->links;link++){
1819     double addsec = ov_time_total(vf,link);
1820     if(seconds<time_total+addsec)break;
1821     time_total+=addsec;
1822     pcm_total+=vf->pcmlengths[link*2+1];
1823   }
1824
1825   if(link==vf->links)return(OV_EINVAL);
1826
1827   /* enough information to convert time offset to pcm offset */
1828   {
1829     ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
1830     return(ov_pcm_seek_page(vf,target));
1831   }
1832 }
1833
1834 /* tell the current stream offset cursor.  Note that seek followed by
1835    tell will likely not give the set offset due to caching */
1836 ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
1837   if(vf->ready_state<OPENED)return(OV_EINVAL);
1838   return(vf->offset);
1839 }
1840
1841 /* return PCM offset (sample) of next PCM sample to be read */
1842 ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
1843   if(vf->ready_state<OPENED)return(OV_EINVAL);
1844   return(vf->pcm_offset);
1845 }
1846
1847 /* return time offset (seconds) of next PCM sample to be read */
1848 double ov_time_tell(OggVorbis_File *vf){
1849   int link=0;
1850   ogg_int64_t pcm_total=0;
1851   double time_total=0.f;
1852
1853   if(vf->ready_state<OPENED)return(OV_EINVAL);
1854   if(vf->seekable){
1855     pcm_total=ov_pcm_total(vf,-1);
1856     time_total=ov_time_total(vf,-1);
1857
1858     /* which bitstream section does this time offset occur in? */
1859     for(link=vf->links-1;link>=0;link--){
1860       pcm_total-=vf->pcmlengths[link*2+1];
1861       time_total-=ov_time_total(vf,link);
1862       if(vf->pcm_offset>=pcm_total)break;
1863     }
1864   }
1865
1866   return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
1867 }
1868
1869 /*  link:   -1) return the vorbis_info struct for the bitstream section
1870                 currently being decoded
1871            0-n) to request information for a specific bitstream section
1872
1873     In the case of a non-seekable bitstream, any call returns the
1874     current bitstream.  NULL in the case that the machine is not
1875     initialized */
1876
1877 vorbis_info *ov_info(OggVorbis_File *vf,int link){
1878   if(vf->seekable){
1879     if(link<0)
1880       if(vf->ready_state>=STREAMSET)
1881         return vf->vi+vf->current_link;
1882       else
1883       return vf->vi;
1884     else
1885       if(link>=vf->links)
1886         return NULL;
1887       else
1888         return vf->vi+link;
1889   }else{
1890     return vf->vi;
1891   }
1892 }
1893
1894 /* grr, strong typing, grr, no templates/inheritence, grr */
1895 vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
1896   if(vf->seekable){
1897     if(link<0)
1898       if(vf->ready_state>=STREAMSET)
1899         return vf->vc+vf->current_link;
1900       else
1901         return vf->vc;
1902     else
1903       if(link>=vf->links)
1904         return NULL;
1905       else
1906         return vf->vc+link;
1907   }else{
1908     return vf->vc;
1909   }
1910 }
1911
1912 static int host_is_big_endian() {
1913   ogg_int32_t pattern = 0xfeedface; /* deadbeef */
1914   unsigned char *bytewise = (unsigned char *)&pattern;
1915   if (bytewise[0] == 0xfe) return 1;
1916   return 0;
1917 }
1918
1919 /* up to this point, everything could more or less hide the multiple
1920    logical bitstream nature of chaining from the toplevel application
1921    if the toplevel application didn't particularly care.  However, at
1922    the point that we actually read audio back, the multiple-section
1923    nature must surface: Multiple bitstream sections do not necessarily
1924    have to have the same number of channels or sampling rate.
1925
1926    ov_read returns the sequential logical bitstream number currently
1927    being decoded along with the PCM data in order that the toplevel
1928    application can take action on channel/sample rate changes.  This
1929    number will be incremented even for streamed (non-seekable) streams
1930    (for seekable streams, it represents the actual logical bitstream
1931    index within the physical bitstream.  Note that the accessor
1932    functions above are aware of this dichotomy).
1933
1934    ov_read_filter is exactly the same as ov_read except that it processes
1935    the decoded audio data through a filter before packing it into the
1936    requested format. This gives greater accuracy than applying a filter
1937    after the audio has been converted into integral PCM.
1938
1939    input values: buffer) a buffer to hold packed PCM data for return
1940                  length) the byte length requested to be placed into buffer
1941                  bigendianp) should the data be packed LSB first (0) or
1942                              MSB first (1)
1943                  word) word size for output.  currently 1 (byte) or
1944                        2 (16 bit short)
1945
1946    return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
1947                    0) EOF
1948                    n) number of bytes of PCM actually returned.  The
1949                    below works on a packet-by-packet basis, so the
1950                    return length is not related to the 'length' passed
1951                    in, just guaranteed to fit.
1952
1953             *section) set to the logical bitstream number */
1954
1955 long ov_read_filter(OggVorbis_File *vf,char *buffer,int length,
1956                     int bigendianp,int word,int sgned,int *bitstream,
1957                     void (*filter)(float **pcm,long channels,long samples,void *filter_param),void *filter_param){
1958   int i,j;
1959   int host_endian = host_is_big_endian();
1960   int hs;
1961
1962   float **pcm;
1963   long samples;
1964
1965   if(vf->ready_state<OPENED)return(OV_EINVAL);
1966
1967   while(1){
1968     if(vf->ready_state==INITSET){
1969       samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
1970       if(samples)break;
1971     }
1972
1973     /* suck in another packet */
1974     {
1975       int ret=_fetch_and_process_packet(vf,NULL,1,1);
1976       if(ret==OV_EOF)
1977         return(0);
1978       if(ret<=0)
1979         return(ret);
1980     }
1981
1982   }
1983
1984   if(samples>0){
1985
1986     /* yay! proceed to pack data into the byte buffer */
1987
1988     long channels=ov_info(vf,-1)->channels;
1989     long bytespersample=word * channels;
1990     vorbis_fpu_control fpu;
1991     if(samples>length/bytespersample)samples=length/bytespersample;
1992
1993     if(samples <= 0)
1994       return OV_EINVAL;
1995
1996     /* Here. */
1997     if(filter)
1998       filter(pcm,channels,samples,filter_param);
1999
2000     /* a tight loop to pack each size */
2001     {
2002       int val;
2003       if(word==1){
2004         int off=(sgned?0:128);
2005         vorbis_fpu_setround(&fpu);
2006         for(j=0;j<samples;j++)
2007           for(i=0;i<channels;i++){
2008             val=vorbis_ftoi(pcm[i][j]*128.f);
2009             if(val>127)val=127;
2010             else if(val<-128)val=-128;
2011             *buffer++=val+off;
2012           }
2013         vorbis_fpu_restore(fpu);
2014       }else{
2015         int off=(sgned?0:32768);
2016
2017         if(host_endian==bigendianp){
2018           if(sgned){
2019
2020             vorbis_fpu_setround(&fpu);
2021             for(i=0;i<channels;i++) { /* It's faster in this order */
2022               float *src=pcm[i];
2023               short *dest=((short *)buffer)+i;
2024               for(j=0;j<samples;j++) {
2025                 val=vorbis_ftoi(src[j]*32768.f);
2026                 if(val>32767)val=32767;
2027                 else if(val<-32768)val=-32768;
2028                 *dest=val;
2029                 dest+=channels;
2030               }
2031             }
2032             vorbis_fpu_restore(fpu);
2033
2034           }else{
2035
2036             vorbis_fpu_setround(&fpu);
2037             for(i=0;i<channels;i++) {
2038               float *src=pcm[i];
2039               short *dest=((short *)buffer)+i;
2040               for(j=0;j<samples;j++) {
2041                 val=vorbis_ftoi(src[j]*32768.f);
2042                 if(val>32767)val=32767;
2043                 else if(val<-32768)val=-32768;
2044                 *dest=val+off;
2045                 dest+=channels;
2046               }
2047             }
2048             vorbis_fpu_restore(fpu);
2049
2050           }
2051         }else if(bigendianp){
2052
2053           vorbis_fpu_setround(&fpu);
2054           for(j=0;j<samples;j++)
2055             for(i=0;i<channels;i++){
2056               val=vorbis_ftoi(pcm[i][j]*32768.f);
2057               if(val>32767)val=32767;
2058               else if(val<-32768)val=-32768;
2059               val+=off;
2060               *buffer++=(val>>8);
2061               *buffer++=(val&0xff);
2062             }
2063           vorbis_fpu_restore(fpu);
2064
2065         }else{
2066           int val;
2067           vorbis_fpu_setround(&fpu);
2068           for(j=0;j<samples;j++)
2069             for(i=0;i<channels;i++){
2070               val=vorbis_ftoi(pcm[i][j]*32768.f);
2071               if(val>32767)val=32767;
2072               else if(val<-32768)val=-32768;
2073               val+=off;
2074               *buffer++=(val&0xff);
2075               *buffer++=(val>>8);
2076                   }
2077           vorbis_fpu_restore(fpu);
2078
2079         }
2080       }
2081     }
2082
2083     vorbis_synthesis_read(&vf->vd,samples);
2084     hs=vorbis_synthesis_halfrate_p(vf->vi);
2085     vf->pcm_offset+=(samples<<hs);
2086     if(bitstream)*bitstream=vf->current_link;
2087     return(samples*bytespersample);
2088   }else{
2089     return(samples);
2090   }
2091 }
2092
2093 long ov_read(OggVorbis_File *vf,char *buffer,int length,
2094              int bigendianp,int word,int sgned,int *bitstream){
2095   return ov_read_filter(vf, buffer, length, bigendianp, word, sgned, bitstream, NULL, NULL);
2096 }
2097
2098 /* input values: pcm_channels) a float vector per channel of output
2099                  length) the sample length being read by the app
2100
2101    return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
2102                    0) EOF
2103                    n) number of samples of PCM actually returned.  The
2104                    below works on a packet-by-packet basis, so the
2105                    return length is not related to the 'length' passed
2106                    in, just guaranteed to fit.
2107
2108             *section) set to the logical bitstream number */
2109
2110
2111
2112 long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
2113                    int *bitstream){
2114
2115   if(vf->ready_state<OPENED)return(OV_EINVAL);
2116
2117   while(1){
2118     if(vf->ready_state==INITSET){
2119       float **pcm;
2120       long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
2121       if(samples){
2122         int hs=vorbis_synthesis_halfrate_p(vf->vi);
2123         if(pcm_channels)*pcm_channels=pcm;
2124         if(samples>length)samples=length;
2125         vorbis_synthesis_read(&vf->vd,samples);
2126         vf->pcm_offset+=samples<<hs;
2127         if(bitstream)*bitstream=vf->current_link;
2128         return samples;
2129
2130       }
2131     }
2132
2133     /* suck in another packet */
2134     {
2135       int ret=_fetch_and_process_packet(vf,NULL,1,1);
2136       if(ret==OV_EOF)return(0);
2137       if(ret<=0)return(ret);
2138     }
2139
2140   }
2141 }
2142
2143 extern const float *vorbis_window(vorbis_dsp_state *v,int W);
2144
2145 static void _ov_splice(float **pcm,float **lappcm,
2146                        int n1, int n2,
2147                        int ch1, int ch2,
2148                        const float *w1, const float *w2){
2149   int i,j;
2150   const float *w=w1;
2151   int n=n1;
2152
2153   if(n1>n2){
2154     n=n2;
2155     w=w2;
2156   }
2157
2158   /* splice */
2159   for(j=0;j<ch1 && j<ch2;j++){
2160     float *s=lappcm[j];
2161     float *d=pcm[j];
2162
2163     for(i=0;i<n;i++){
2164       float wd=w[i]*w[i];
2165       float ws=1.-wd;
2166       d[i]=d[i]*wd + s[i]*ws;
2167     }
2168   }
2169   /* window from zero */
2170   for(;j<ch2;j++){
2171     float *d=pcm[j];
2172     for(i=0;i<n;i++){
2173       float wd=w[i]*w[i];
2174       d[i]=d[i]*wd;
2175     }
2176   }
2177
2178 }
2179
2180 /* make sure vf is INITSET */
2181 static int _ov_initset(OggVorbis_File *vf){
2182   while(1){
2183     if(vf->ready_state==INITSET)break;
2184     /* suck in another packet */
2185     {
2186       int ret=_fetch_and_process_packet(vf,NULL,1,0);
2187       if(ret<0 && ret!=OV_HOLE)return(ret);
2188     }
2189   }
2190   return 0;
2191 }
2192
2193 /* make sure vf is INITSET and that we have a primed buffer; if
2194    we're crosslapping at a stream section boundary, this also makes
2195    sure we're sanity checking against the right stream information */
2196 static int _ov_initprime(OggVorbis_File *vf){
2197   vorbis_dsp_state *vd=&vf->vd;
2198   while(1){
2199     if(vf->ready_state==INITSET)
2200       if(vorbis_synthesis_pcmout(vd,NULL))break;
2201
2202     /* suck in another packet */
2203     {
2204       int ret=_fetch_and_process_packet(vf,NULL,1,0);
2205       if(ret<0 && ret!=OV_HOLE)return(ret);
2206     }
2207   }
2208   return 0;
2209 }
2210
2211 /* grab enough data for lapping from vf; this may be in the form of
2212    unreturned, already-decoded pcm, remaining PCM we will need to
2213    decode, or synthetic postextrapolation from last packets. */
2214 static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
2215                        float **lappcm,int lapsize){
2216   int lapcount=0,i;
2217   float **pcm;
2218
2219   /* try first to decode the lapping data */
2220   while(lapcount<lapsize){
2221     int samples=vorbis_synthesis_pcmout(vd,&pcm);
2222     if(samples){
2223       if(samples>lapsize-lapcount)samples=lapsize-lapcount;
2224       for(i=0;i<vi->channels;i++)
2225         memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
2226       lapcount+=samples;
2227       vorbis_synthesis_read(vd,samples);
2228     }else{
2229     /* suck in another packet */
2230       int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
2231       if(ret==OV_EOF)break;
2232     }
2233   }
2234   if(lapcount<lapsize){
2235     /* failed to get lapping data from normal decode; pry it from the
2236        postextrapolation buffering, or the second half of the MDCT
2237        from the last packet */
2238     int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
2239     if(samples==0){
2240       for(i=0;i<vi->channels;i++)
2241         memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
2242       lapcount=lapsize;
2243     }else{
2244       if(samples>lapsize-lapcount)samples=lapsize-lapcount;
2245       for(i=0;i<vi->channels;i++)
2246         memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
2247       lapcount+=samples;
2248     }
2249   }
2250 }
2251
2252 /* this sets up crosslapping of a sample by using trailing data from
2253    sample 1 and lapping it into the windowing buffer of sample 2 */
2254 int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
2255   vorbis_info *vi1,*vi2;
2256   float **lappcm;
2257   float **pcm;
2258   const float *w1,*w2;
2259   int n1,n2,i,ret,hs1,hs2;
2260
2261   if(vf1==vf2)return(0); /* degenerate case */
2262   if(vf1->ready_state<OPENED)return(OV_EINVAL);
2263   if(vf2->ready_state<OPENED)return(OV_EINVAL);
2264
2265   /* the relevant overlap buffers must be pre-checked and pre-primed
2266      before looking at settings in the event that priming would cross
2267      a bitstream boundary.  So, do it now */
2268
2269   ret=_ov_initset(vf1);
2270   if(ret)return(ret);
2271   ret=_ov_initprime(vf2);
2272   if(ret)return(ret);
2273
2274   vi1=ov_info(vf1,-1);
2275   vi2=ov_info(vf2,-1);
2276   hs1=ov_halfrate_p(vf1);
2277   hs2=ov_halfrate_p(vf2);
2278
2279   lappcm=alloca(sizeof(*lappcm)*vi1->channels);
2280   n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
2281   n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
2282   w1=vorbis_window(&vf1->vd,0);
2283   w2=vorbis_window(&vf2->vd,0);
2284
2285   for(i=0;i<vi1->channels;i++)
2286     lappcm[i]=alloca(sizeof(**lappcm)*n1);
2287
2288   _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
2289
2290   /* have a lapping buffer from vf1; now to splice it into the lapping
2291      buffer of vf2 */
2292   /* consolidate and expose the buffer. */
2293   vorbis_synthesis_lapout(&vf2->vd,&pcm);
2294
2295 #if 0
2296   _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
2297   _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
2298 #endif
2299
2300   /* splice */
2301   _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
2302
2303   /* done */
2304   return(0);
2305 }
2306
2307 static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
2308                            int (*localseek)(OggVorbis_File *,ogg_int64_t)){
2309   vorbis_info *vi;
2310   float **lappcm;
2311   float **pcm;
2312   const float *w1,*w2;
2313   int n1,n2,ch1,ch2,hs;
2314   int i,ret;
2315
2316   if(vf->ready_state<OPENED)return(OV_EINVAL);
2317   ret=_ov_initset(vf);
2318   if(ret)return(ret);
2319   vi=ov_info(vf,-1);
2320   hs=ov_halfrate_p(vf);
2321
2322   ch1=vi->channels;
2323   n1=vorbis_info_blocksize(vi,0)>>(1+hs);
2324   w1=vorbis_window(&vf->vd,0);  /* window arrays from libvorbis are
2325                                    persistent; even if the decode state
2326                                    from this link gets dumped, this
2327                                    window array continues to exist */
2328
2329   lappcm=alloca(sizeof(*lappcm)*ch1);
2330   for(i=0;i<ch1;i++)
2331     lappcm[i]=alloca(sizeof(**lappcm)*n1);
2332   _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
2333
2334   /* have lapping data; seek and prime the buffer */
2335   ret=localseek(vf,pos);
2336   if(ret)return ret;
2337   ret=_ov_initprime(vf);
2338   if(ret)return(ret);
2339
2340  /* Guard against cross-link changes; they're perfectly legal */
2341   vi=ov_info(vf,-1);
2342   ch2=vi->channels;
2343   n2=vorbis_info_blocksize(vi,0)>>(1+hs);
2344   w2=vorbis_window(&vf->vd,0);
2345
2346   /* consolidate and expose the buffer. */
2347   vorbis_synthesis_lapout(&vf->vd,&pcm);
2348
2349   /* splice */
2350   _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
2351
2352   /* done */
2353   return(0);
2354 }
2355
2356 int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
2357   return _ov_64_seek_lap(vf,pos,ov_raw_seek);
2358 }
2359
2360 int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
2361   return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
2362 }
2363
2364 int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
2365   return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
2366 }
2367
2368 static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
2369                            int (*localseek)(OggVorbis_File *,double)){
2370   vorbis_info *vi;
2371   float **lappcm;
2372   float **pcm;
2373   const float *w1,*w2;
2374   int n1,n2,ch1,ch2,hs;
2375   int i,ret;
2376
2377   if(vf->ready_state<OPENED)return(OV_EINVAL);
2378   ret=_ov_initset(vf);
2379   if(ret)return(ret);
2380   vi=ov_info(vf,-1);
2381   hs=ov_halfrate_p(vf);
2382
2383   ch1=vi->channels;
2384   n1=vorbis_info_blocksize(vi,0)>>(1+hs);
2385   w1=vorbis_window(&vf->vd,0);  /* window arrays from libvorbis are
2386                                    persistent; even if the decode state
2387                                    from this link gets dumped, this
2388                                    window array continues to exist */
2389
2390   lappcm=alloca(sizeof(*lappcm)*ch1);
2391   for(i=0;i<ch1;i++)
2392     lappcm[i]=alloca(sizeof(**lappcm)*n1);
2393   _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
2394
2395   /* have lapping data; seek and prime the buffer */
2396   ret=localseek(vf,pos);
2397   if(ret)return ret;
2398   ret=_ov_initprime(vf);
2399   if(ret)return(ret);
2400
2401  /* Guard against cross-link changes; they're perfectly legal */
2402   vi=ov_info(vf,-1);
2403   ch2=vi->channels;
2404   n2=vorbis_info_blocksize(vi,0)>>(1+hs);
2405   w2=vorbis_window(&vf->vd,0);
2406
2407   /* consolidate and expose the buffer. */
2408   vorbis_synthesis_lapout(&vf->vd,&pcm);
2409
2410   /* splice */
2411   _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
2412
2413   /* done */
2414   return(0);
2415 }
2416
2417 int ov_time_seek_lap(OggVorbis_File *vf,double pos){
2418   return _ov_d_seek_lap(vf,pos,ov_time_seek);
2419 }
2420
2421 int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
2422   return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
2423 }