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