We never called vorbis_comment_clear() in either of these examples. That's bad.
[platform/upstream/libvorbis.git] / examples / decoder_example.c
1 /********************************************************************
2  *                                                                  *
3  * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE.   *
4  * USE, DISTRIBUTION AND REPRODUCTION OF THIS SOURCE IS GOVERNED BY *
5  * THE GNU LESSER/LIBRARY PUBLIC LICENSE, WHICH IS INCLUDED WITH    *
6  * THIS SOURCE. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.        *
7  *                                                                  *
8  * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2000             *
9  * by Monty <monty@xiph.org> and the XIPHOPHORUS Company            *
10  * http://www.xiph.org/                                             *
11  *                                                                  *
12  ********************************************************************
13
14  function: simple example decoder
15  last mod: $Id: decoder_example.c,v 1.16 2001/01/20 14:06:28 msmith Exp $
16
17  ********************************************************************/
18
19 /* Takes a vorbis bitstream from stdin and writes raw stereo PCM to
20    stdout.  Decodes simple and chained OggVorbis files from beginning
21    to end.  Vorbisfile.a is somewhat more complex than the code below.  */
22
23 /* Note that this is POSIX, not ANSI code */
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <math.h>
28 #include <vorbis/codec.h>
29
30 #ifdef _WIN32 /* We need the following two to set stdin/stdout to binary */
31 #include <io.h>
32 #include <fcntl.h>
33 #endif
34
35 #if defined(macintosh) && defined(__MWERKS__)
36 #include <console.h>      /* CodeWarrior's Mac "command-line" support */
37 #endif
38
39 ogg_int16_t convbuffer[4096]; /* take 8k out of the data segment, not the stack */
40 int convsize=4096;
41
42 int main(int argc, char **argv){
43   ogg_sync_state   oy; /* sync and verify incoming physical bitstream */
44   ogg_stream_state os; /* take physical pages, weld into a logical
45                           stream of packets */
46   ogg_page         og; /* one Ogg bitstream page.  Vorbis packets are inside */
47   ogg_packet       op; /* one raw packet of data for decode */
48   
49   vorbis_info      vi; /* struct that stores all the static vorbis bitstream
50                           settings */
51   vorbis_comment   vc; /* struct that stores all the bitstream user comments */
52   vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
53   vorbis_block     vb; /* local working space for packet->PCM decode */
54   
55   char *buffer;
56   int  bytes;
57
58 #ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */
59   /* Beware the evil ifdef. We avoid these where we can, but this one we 
60      cannot. Don't add any more, you'll probably go to hell if you do. */
61   _setmode( _fileno( stdin ), _O_BINARY );
62   _setmode( _fileno( stdout ), _O_BINARY );
63 #endif
64
65 #if defined(macintosh) && defined(__MWERKS__)
66
67   argc = ccommand(&argv); /* get a "command line" from the Mac user */
68                           /* this also lets the user set stdin and stdout */
69 #endif
70
71   /********** Decode setup ************/
72
73   ogg_sync_init(&oy); /* Now we can read pages */
74   
75   while(1){ /* we repeat if the bitstream is chained */
76     int eos=0;
77     int i;
78
79     /* grab some data at the head of the stream.  We want the first page
80        (which is guaranteed to be small and only contain the Vorbis
81        stream initial header) We need the first page to get the stream
82        serialno. */
83
84     /* submit a 4k block to libvorbis' Ogg layer */
85     buffer=ogg_sync_buffer(&oy,4096);
86     bytes=fread(buffer,1,4096,stdin);
87     ogg_sync_wrote(&oy,bytes);
88     
89     /* Get the first page. */
90     if(ogg_sync_pageout(&oy,&og)!=1){
91       /* have we simply run out of data?  If so, we're done. */
92       if(bytes<4096)break;
93       
94       /* error case.  Must not be Vorbis data */
95       fprintf(stderr,"Input does not appear to be an Ogg bitstream.\n");
96       exit(1);
97     }
98   
99     /* Get the serial number and set up the rest of decode. */
100     /* serialno first; use it to set up a logical stream */
101     ogg_stream_init(&os,ogg_page_serialno(&og));
102     
103     /* extract the initial header from the first page and verify that the
104        Ogg bitstream is in fact Vorbis data */
105     
106     /* I handle the initial header first instead of just having the code
107        read all three Vorbis headers at once because reading the initial
108        header is an easy way to identify a Vorbis bitstream and it's
109        useful to see that functionality seperated out. */
110     
111     vorbis_info_init(&vi);
112     vorbis_comment_init(&vc);
113     if(ogg_stream_pagein(&os,&og)<0){ 
114       /* error; stream version mismatch perhaps */
115       fprintf(stderr,"Error reading first page of Ogg bitstream data.\n");
116       exit(1);
117     }
118     
119     if(ogg_stream_packetout(&os,&op)!=1){ 
120       /* no page? must not be vorbis */
121       fprintf(stderr,"Error reading initial header packet.\n");
122       exit(1);
123     }
124     
125     if(vorbis_synthesis_headerin(&vi,&vc,&op)<0){ 
126       /* error case; not a vorbis header */
127       fprintf(stderr,"This Ogg bitstream does not contain Vorbis "
128               "audio data.\n");
129       exit(1);
130     }
131     
132     /* At this point, we're sure we're Vorbis.  We've set up the logical
133        (Ogg) bitstream decoder.  Get the comment and codebook headers and
134        set up the Vorbis decoder */
135     
136     /* The next two packets in order are the comment and codebook headers.
137        They're likely large and may span multiple pages.  Thus we reead
138        and submit data until we get our two pacakets, watching that no
139        pages are missing.  If a page is missing, error out; losing a
140        header page is the only place where missing data is fatal. */
141     
142     i=0;
143     while(i<2){
144       while(i<2){
145         int result=ogg_sync_pageout(&oy,&og);
146         if(result==0)break; /* Need more data */
147         /* Don't complain about missing or corrupt data yet.  We'll
148            catch it at the packet output phase */
149         if(result==1){
150           ogg_stream_pagein(&os,&og); /* we can ignore any errors here
151                                          as they'll also become apparent
152                                          at packetout */
153           while(i<2){
154             result=ogg_stream_packetout(&os,&op);
155             if(result==0)break;
156             if(result<0){
157               /* Uh oh; data at some point was corrupted or missing!
158                  We can't tolerate that in a header.  Die. */
159               fprintf(stderr,"Corrupt secondary header.  Exiting.\n");
160               exit(1);
161             }
162             vorbis_synthesis_headerin(&vi,&vc,&op);
163             i++;
164           }
165         }
166       }
167       /* no harm in not checking before adding more */
168       buffer=ogg_sync_buffer(&oy,4096);
169       bytes=fread(buffer,1,4096,stdin);
170       if(bytes==0 && i<2){
171         fprintf(stderr,"End of file before finding all Vorbis headers!\n");
172         exit(1);
173       }
174       ogg_sync_wrote(&oy,bytes);
175     }
176     
177     /* Throw the comments plus a few lines about the bitstream we're
178        decoding */
179     {
180       char **ptr=vc.user_comments;
181       while(*ptr){
182         fprintf(stderr,"%s\n",*ptr);
183         ++ptr;
184       }
185       fprintf(stderr,"\nBitstream is %d channel, %ldHz\n",vi.channels,vi.rate);
186       fprintf(stderr,"Encoded by: %s\n\n",vc.vendor);
187     }
188     
189     convsize=4096/vi.channels;
190
191     /* OK, got and parsed all three headers. Initialize the Vorbis
192        packet->PCM decoder. */
193     vorbis_synthesis_init(&vd,&vi); /* central decode state */
194     vorbis_block_init(&vd,&vb);     /* local state for most of the decode
195                                        so multiple block decodes can
196                                        proceed in parallel.  We could init
197                                        multiple vorbis_block structures
198                                        for vd here */
199     
200     /* The rest is just a straight decode loop until end of stream */
201     while(!eos){
202       while(!eos){
203         int result=ogg_sync_pageout(&oy,&og);
204         if(result==0)break; /* need more data */
205         if(result<0){ /* missing or corrupt data at this page position */
206           fprintf(stderr,"Corrupt or missing data in bitstream; "
207                   "continuing...\n");
208         }else{
209           ogg_stream_pagein(&os,&og); /* can safely ignore errors at
210                                          this point */
211           while(1){
212             result=ogg_stream_packetout(&os,&op);
213
214             if(result==0)break; /* need more data */
215             if(result<0){ /* missing or corrupt data at this page position */
216               /* no reason to complain; already complained above */
217             }else{
218               /* we have a packet.  Decode it */
219               float **pcm;
220               int samples;
221               
222               if(vorbis_synthesis(&vb,&op)==0) /* test for success! */
223                 vorbis_synthesis_blockin(&vd,&vb);
224               /* 
225                  
226               **pcm is a multichannel float vector.  In stereo, for
227               example, pcm[0] is left, and pcm[1] is right.  samples is
228               the size of each channel.  Convert the float values
229               (-1.<=range<=1.) to whatever PCM format and write it out */
230               
231               while((samples=vorbis_synthesis_pcmout(&vd,&pcm))>0){
232                 int j;
233                 int clipflag=0;
234                 int bout=(samples<convsize?samples:convsize);
235                 
236                 /* convert floats to 16 bit signed ints (host order) and
237                    interleave */
238                 for(i=0;i<vi.channels;i++){
239                   ogg_int16_t *ptr=convbuffer+i;
240                   float  *mono=pcm[i];
241                   for(j=0;j<bout;j++){
242 #if 1
243                     int val=mono[j]*32767.f;
244 #else /* optional dither */
245                     int val=mono[j]*32767.f+drand48()-0.5f;
246 #endif
247                     /* might as well guard against clipping */
248                     if(val>32767){
249                       val=32767;
250                       clipflag=1;
251                     }
252                     if(val<-32768){
253                       val=-32768;
254                       clipflag=1;
255                     }
256                     *ptr=val;
257                     ptr+=2;
258                   }
259                 }
260                 
261                 if(clipflag)
262                   fprintf(stderr,"Clipping in frame %ld\n",(long)(vd.sequence));
263                 
264                 
265                 fwrite(convbuffer,2*vi.channels,bout,stdout);
266                 
267                 vorbis_synthesis_read(&vd,bout); /* tell libvorbis how
268                                                    many samples we
269                                                    actually consumed */
270               }     
271             }
272           }
273           if(ogg_page_eos(&og))eos=1;
274         }
275       }
276       if(!eos){
277         buffer=ogg_sync_buffer(&oy,4096);
278         bytes=fread(buffer,1,4096,stdin);
279         ogg_sync_wrote(&oy,bytes);
280         if(bytes==0)eos=1;
281       }
282     }
283     
284     /* clean up this logical bitstream; before exit we see if we're
285        followed by another [chained] */
286
287     ogg_stream_clear(&os);
288   
289     /* ogg_page and ogg_packet structs always point to storage in
290        libvorbis.  They're never freed or manipulated directly */
291     
292     vorbis_block_clear(&vb);
293     vorbis_dsp_clear(&vd);
294         vorbis_comment_clear(&vc);
295     vorbis_info_clear(&vi);  /* must be called last */
296   }
297
298   /* OK, clean up the framer */
299   ogg_sync_clear(&oy);
300   
301   fprintf(stderr,"Done.\n");
302   return(0);
303 }
304