opusfile_example.c 11 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
/********************************************************************
 *                                                                  *
 * THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. *
 * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
 * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
 * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
 *                                                                  *
 * THE libopusfile SOURCE CODE IS (C) COPYRIGHT 1994-2012           *
 * by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
 *                                                                  *
 ********************************************************************/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
12
13
14
15
16
17
18
19
20
21
22
23
24
/*For fileno()*/
#if !defined(_POSIX_SOURCE)
# define _POSIX_SOURCE 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#if defined(_WIN32)
/*We need the following two to set stdin/stdout to binary.*/
# include <io.h>
# include <fcntl.h>
#endif
Ralph Giles's avatar
Ralph Giles committed
25
#include <opusfile.h>
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
26

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
static void print_duration(FILE *_fp,ogg_int64_t _nsamples,int _frac){
  ogg_int64_t seconds;
  ogg_int64_t minutes;
  ogg_int64_t hours;
  ogg_int64_t days;
  ogg_int64_t weeks;
  _nsamples+=_frac?24:24000;
  seconds=_nsamples/48000;
  _nsamples-=seconds*48000;
  minutes=seconds/60;
  seconds-=minutes*60;
  hours=minutes/60;
  minutes-=hours*60;
  days=hours/24;
  hours-=days*24;
  weeks=days/7;
  days-=weeks*7;
  if(weeks)fprintf(_fp,"%liw",(long)weeks);
  if(weeks||days)fprintf(_fp,"%id",(int)days);
  if(weeks||days||hours){
    if(weeks||days)fprintf(_fp,"%02ih",(int)hours);
    else fprintf(_fp,"%ih",(int)hours);
  }
  if(weeks||days||hours||minutes){
    if(weeks||days||hours)fprintf(_fp,"%02im",(int)minutes);
    else fprintf(_fp,"%im",(int)minutes);
    fprintf(_fp,"%02i",(int)seconds);
  }
  else fprintf(_fp,"%i",(int)seconds);
  if(_frac)fprintf(_fp,".%03i",(int)(_nsamples/48));
  fprintf(_fp,"s");
}

static void print_size(FILE *_fp,opus_int64 _nbytes,int _metric,
 const char *_spacer){
  static const char SUFFIXES[7]={' ','k','M','G','T','P','E'};
  opus_int64 val;
  opus_int64 den;
  opus_int64 round;
  int        base;
  int        shift;
  base=_metric?1000:1024;
  round=0;
  den=1;
  for(shift=0;shift<6;shift++){
    if(_nbytes<den*base-round)break;
    den*=base;
    round=den>>1;
  }
  val=(_nbytes+round)/den;
  if(den>1&&val<10){
    if(den>=1000000000)val=(_nbytes+(round/100))/(den/100);
    else val=(_nbytes*100+round)/den;
    fprintf(_fp,"%li.%02i%s%c",(long)(val/100),(int)(val%100),
     _spacer,SUFFIXES[shift]);
  }
  else if(den>1&&val<100){
    if(den>=1000000000)val=(_nbytes+(round/10))/(den/10);
    else val=(_nbytes*10+round)/den;
    fprintf(_fp,"%li.%i%s%c",(long)(val/10),(int)(val%10),
     _spacer,SUFFIXES[shift]);
  }
  else fprintf(_fp,"%li%s%c",(long)val,_spacer,SUFFIXES[shift]);
}

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
static void put_le32(unsigned char *_dst,opus_uint32 _x){
  _dst[0]=(unsigned char)(_x&0xFF);
  _dst[1]=(unsigned char)(_x>>8&0xFF);
  _dst[2]=(unsigned char)(_x>>16&0xFF);
  _dst[3]=(unsigned char)(_x>>24&0xFF);
}

/*Make a header for a 48 kHz, stereo, signed, 16-bit little-endian PCM WAV.*/
static void make_wav_header(unsigned char _dst[44],ogg_int64_t _duration){
  /*The chunk sizes are set to 0x7FFFFFFF by default.
    Many, though not all, programs will interpret this to mean the duration is
     "undefined", and continue to read from the file so long as there is actual
     data.*/
  static const unsigned char WAV_HEADER_TEMPLATE[44]={
    'R','I','F','F',0xFF,0xFF,0xFF,0x7F,
    'W','A','V','E','f','m','t',' ',
    0x10,0x00,0x00,0x00,0x01,0x00,0x02,0x00,
    0x80,0xBB,0x00,0x00,0x00,0xEE,0x02,0x00,
    0x04,0x00,0x10,0x00,'d','a','t','a',
    0xFF,0xFF,0xFF,0x7F
  };
  memcpy(_dst,WAV_HEADER_TEMPLATE,sizeof(WAV_HEADER_TEMPLATE));
  if(_duration>0){
    if(_duration>0x1FFFFFF6){
      fprintf(stderr,"WARNING: WAV output would be larger than 2 GB.\n");
      fprintf(stderr,
       "Writing non-standard WAV header with invalid chunk sizes.\n");
    }
    else{
      opus_uint32 audio_size;
      audio_size=(opus_uint32)(_duration*4);
      put_le32(_dst+4,audio_size+36);
      put_le32(_dst+40,audio_size);
    }
  }
}

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
129
int main(int _argc,const char **_argv){
130
131
132
133
134
135
  OggOpusFile  *of;
  ogg_int64_t   duration;
  unsigned char wav_header[44];
  int           ret;
  int           is_ssl;
  int           output_seekable;
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#if defined(_WIN32)
# undef fileno
# define fileno _fileno
  /*We need to set stdin/stdout to binary mode. Damn windows.*/
  /*Beware the evil ifdef. We avoid these where we can, but this one we
     cannot.
    Don't add any more.
    You'll probably go to hell if you do.*/
  _setmode(fileno(stdin),_O_BINARY);
  _setmode(fileno(stdout),_O_BINARY);
#endif
  if(_argc!=2){
    fprintf(stderr,"Usage: %s <file.opus>\n",_argv[0]);
    return EXIT_FAILURE;
  }
151
  is_ssl=0;
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
152
153
  if(strcmp(_argv[1],"-")==0){
    OpusFileCallbacks cb={NULL,NULL,NULL,NULL};
154
    of=op_open_callbacks(op_fdopen(&cb,fileno(stdin),"rb"),&cb,NULL,0,&ret);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
155
156
  }
  else{
157
    /*Try to treat the argument as a URL.*/
158
    of=op_open_url(_argv[1],&ret,NULL);
159
160
#if 0
    if(of==NULL){
161
162
163
164
165
166
167
168
      OpusFileCallbacks  cb={NULL,NULL,NULL,NULL};
      void              *fp;
      /*For debugging: force a file to not be seekable.*/
      fp=op_fopen(&cb,_argv[1],"rb");
      cb.seek=NULL;
      cb.tell=NULL;
      of=op_open_callbacks(fp,&cb,NULL,0,NULL);
    }
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
169
#else
170
    if(of==NULL)of=op_open_file(_argv[1],&ret);
171
172
173
    /*This is not a very good check, but at least it won't give false
       positives.*/
    else is_ssl=strncmp(_argv[1],"https:",6)==0;
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
174
#endif
175
  }
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
176
  if(of==NULL){
177
    fprintf(stderr,"Failed to open file '%s': %i\n",_argv[1],ret);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
178
179
    return EXIT_FAILURE;
  }
180
181
  duration=0;
  output_seekable=fseek(stdout,0,SEEK_CUR)!=-1;
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
182
  if(op_seekable(of)){
183
    opus_int64  size;
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
184
185
    fprintf(stderr,"Total number of links: %i\n",op_link_count(of));
    duration=op_pcm_total(of,-1);
186
187
188
189
190
191
192
    fprintf(stderr,"Total duration: ");
    print_duration(stderr,duration,3);
    fprintf(stderr," (%li samples @ 48 kHz)\n",(long)duration);
    size=op_raw_total(of,-1);
    fprintf(stderr,"Total size: ");
    print_size(stderr,size,0,"");
    fprintf(stderr,"\n");
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
193
  }
194
195
196
197
198
199
200
201
202
  else if(!output_seekable){
    fprintf(stderr,"WARNING: Neither input nor output are seekable.\n");
    fprintf(stderr,
     "Writing non-standard WAV header with invalid chunk sizes.\n");
  }
  make_wav_header(wav_header,duration);
  if(!fwrite(wav_header,sizeof(wav_header),1,stdout)){
    fprintf(stderr,"Error writing WAV header: %s\n",strerror(errno));
    ret=EXIT_FAILURE;
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
203
  }
204
205
206
207
208
209
210
211
212
213
214
  else{
    ogg_int64_t pcm_offset;
    ogg_int64_t pcm_print_offset;
    ogg_int64_t nsamples;
    opus_int32  bitrate;
    int         prev_li;
    prev_li=-1;
    nsamples=0;
    pcm_offset=op_pcm_tell(of);
    if(pcm_offset!=0){
      fprintf(stderr,"Non-zero starting PCM offset: %li\n",(long)pcm_offset);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
215
    }
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
    pcm_print_offset=pcm_offset-48000;
    bitrate=0;
    for(;;){
      ogg_int64_t   next_pcm_offset;
      opus_int16    pcm[120*48*2];
      unsigned char out[120*48*2*2];
      int           li;
      int           si;
      /*Although we would generally prefer to use the float interface, WAV
         files with signed, 16-bit little-endian samples are far more
         universally supported, so that's what we output.*/
      ret=op_read_stereo(of,pcm,sizeof(pcm)/sizeof(*pcm));
      if(ret<0){
        fprintf(stderr,"\nError decoding '%s': %i\n",_argv[1],ret);
        if(is_ssl)fprintf(stderr,"Possible truncation attack?\n");
        ret=EXIT_FAILURE;
        break;
      }
      li=op_current_link(of);
      if(li!=prev_li){
        const OpusHead *head;
        const OpusTags *tags;
        int             ci;
        /*We found a new link.
          Print out some information.*/
        fprintf(stderr,"Decoding link %i:                          \n",li);
        head=op_head(of,li);
        fprintf(stderr,"  Channels: %i\n",head->channel_count);
        if(op_seekable(of)){
          ogg_int64_t duration;
          opus_int64  size;
          duration=op_pcm_total(of,li);
          fprintf(stderr,"  Duration: ");
          print_duration(stderr,duration,3);
          fprintf(stderr," (%li samples @ 48 kHz)\n",(long)duration);
          size=op_raw_total(of,li);
          fprintf(stderr,"  Size: ");
          print_size(stderr,size,0,"");
          fprintf(stderr,"\n");
        }
        if(head->input_sample_rate){
          fprintf(stderr,"  Original sampling rate: %lu Hz\n",
           (unsigned long)head->input_sample_rate);
        }
        tags=op_tags(of,li);
        fprintf(stderr,"  Encoded by: %s\n",tags->vendor);
        for(ci=0;ci<tags->comments;ci++){
          fprintf(stderr,"  %s\n",tags->user_comments[ci]);
        }
265
        fprintf(stderr,"\n");
266
267
268
269
270
271
272
        if(!op_seekable(of)){
          pcm_offset=op_pcm_tell(of)-ret;
          if(pcm_offset!=0){
            fprintf(stderr,"Non-zero starting PCM offset in link %i: %li\n",
             li,(long)pcm_offset);
          }
        }
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
273
      }
274
275
276
277
278
279
280
281
282
283
284
285
286
287
      if(li!=prev_li||pcm_offset>=pcm_print_offset+48000){
        opus_int32 next_bitrate;
        opus_int64 raw_offset;
        next_bitrate=op_bitrate_instant(of);
        if(next_bitrate>=0)bitrate=next_bitrate;
        raw_offset=op_raw_tell(of);
        fprintf(stderr,"\r ");
        print_size(stderr,raw_offset,0,"");
        fprintf(stderr,"  ");
        print_duration(stderr,pcm_offset,0);
        fprintf(stderr,"  (");
        print_size(stderr,bitrate,1," ");
        fprintf(stderr,"bps)                    \r");
        pcm_print_offset=pcm_offset;
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
288
      }
289
290
291
292
      next_pcm_offset=op_pcm_tell(of);
      if(pcm_offset+ret!=next_pcm_offset){
        fprintf(stderr,"\nPCM offset gap! %li+%i!=%li\n",
         (long)pcm_offset,ret,(long)next_pcm_offset);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
293
      }
294
295
296
297
      pcm_offset=next_pcm_offset;
      if(ret<=0){
        ret=EXIT_SUCCESS;
        break;
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
298
      }
299
300
301
302
303
      /*Ensure the data is little-endian before writing it out.*/
      for(si=0;si<2*ret;si++){
        out[2*si+0]=(unsigned char)(pcm[si]&0xFF);
        out[2*si+1]=(unsigned char)(pcm[si]>>8&0xFF);
      }
304
      if(!fwrite(out,sizeof(*out)*4*ret,1,stdout)){
305
306
307
308
309
310
311
        fprintf(stderr,"\nError writing decoded audio data: %s\n",
         strerror(errno));
        ret=EXIT_FAILURE;
        break;
      }
      nsamples+=ret;
      prev_li=li;
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
312
    }
313
314
315
316
    if(ret==EXIT_SUCCESS){
      fprintf(stderr,"\nDone: played ");
      print_duration(stderr,nsamples,3);
      fprintf(stderr," (%li samples @ 48 kHz).\n",(long)nsamples);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
317
    }
318
319
320
321
    if(op_seekable(of)&&nsamples!=duration){
      fprintf(stderr,"\nWARNING: "
       "Number of output samples does not match declared file duration.\n");
      if(!output_seekable)fprintf(stderr,"Output WAV file will be corrupt.\n");
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
322
    }
323
324
325
326
327
328
329
    if(output_seekable&&nsamples!=duration){
      make_wav_header(wav_header,nsamples);
      if(fseek(stdout,0,SEEK_SET)||
       !fwrite(wav_header,sizeof(wav_header),1,stdout)){
        fprintf(stderr,"Error rewriting WAV header: %s\n",strerror(errno));
        ret=EXIT_FAILURE;
      }
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
330
331
332
333
334
    }
  }
  op_free(of);
  return ret;
}