• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2007-2008 CSIRO
2    Copyright (c) 2007-2009 Xiph.Org Foundation
3    Written by Jean-Marc Valin */
4 /*
5    Redistribution and use in source and binary forms, with or without
6    modification, are permitted provided that the following conditions
7    are met:
8 
9    - Redistributions of source code must retain the above copyright
10    notice, this list of conditions and the following disclaimer.
11 
12    - Redistributions in binary form must reproduce the above copyright
13    notice, this list of conditions and the following disclaimer in the
14    documentation and/or other materials provided with the distribution.
15 
16    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17    ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20    OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28 
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
32 
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <math.h>
36 #include <string.h>
37 #include "opus.h"
38 #include "debug.h"
39 #include "opus_types.h"
40 #include "opus_private.h"
41 #include "opus_multistream.h"
42 
43 #define MAX_PACKET 1500
44 
print_usage(char * argv[])45 void print_usage( char* argv[] )
46 {
47     fprintf(stderr, "Usage: %s [-e] <application> <sampling rate (Hz)> <channels (1/2)> "
48         "<bits per second>  [options] <input> <output>\n", argv[0]);
49     fprintf(stderr, "       %s -d <sampling rate (Hz)> <channels (1/2)> "
50         "[options] <input> <output>\n\n", argv[0]);
51     fprintf(stderr, "application: voip | audio | restricted-lowdelay\n" );
52     fprintf(stderr, "options:\n" );
53     fprintf(stderr, "-e                   : only runs the encoder (output the bit-stream)\n" );
54     fprintf(stderr, "-d                   : only runs the decoder (reads the bit-stream as input)\n" );
55     fprintf(stderr, "-cbr                 : enable constant bitrate; default: variable bitrate\n" );
56     fprintf(stderr, "-cvbr                : enable constrained variable bitrate; default: unconstrained\n" );
57     fprintf(stderr, "-delayed-decision    : use look-ahead for speech/music detection (experts only); default: disabled\n" );
58     fprintf(stderr, "-bandwidth <NB|MB|WB|SWB|FB> : audio bandwidth (from narrowband to fullband); default: sampling rate\n" );
59     fprintf(stderr, "-framesize <2.5|5|10|20|40|60|80|100|120> : frame size in ms; default: 20 \n" );
60     fprintf(stderr, "-max_payload <bytes> : maximum payload size in bytes, default: 1024\n" );
61     fprintf(stderr, "-complexity <comp>   : complexity, 0 (lowest) ... 10 (highest); default: 10\n" );
62     fprintf(stderr, "-inbandfec           : enable SILK inband FEC\n" );
63     fprintf(stderr, "-forcemono           : force mono encoding, even for stereo input\n" );
64     fprintf(stderr, "-dtx                 : enable SILK DTX\n" );
65     fprintf(stderr, "-loss <perc>         : simulate packet loss, in percent (0-100); default: 0\n" );
66 }
67 
int_to_char(opus_uint32 i,unsigned char ch[4])68 static void int_to_char(opus_uint32 i, unsigned char ch[4])
69 {
70     ch[0] = i>>24;
71     ch[1] = (i>>16)&0xFF;
72     ch[2] = (i>>8)&0xFF;
73     ch[3] = i&0xFF;
74 }
75 
char_to_int(unsigned char ch[4])76 static opus_uint32 char_to_int(unsigned char ch[4])
77 {
78     return ((opus_uint32)ch[0]<<24) | ((opus_uint32)ch[1]<<16)
79          | ((opus_uint32)ch[2]<< 8) |  (opus_uint32)ch[3];
80 }
81 
check_encoder_option(int decode_only,const char * opt)82 static void check_encoder_option(int decode_only, const char *opt)
83 {
84    if (decode_only)
85    {
86       fprintf(stderr, "option %s is only for encoding\n", opt);
87       exit(EXIT_FAILURE);
88    }
89 }
90 
91 static const int silk8_test[][4] = {
92       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*3, 1},
93       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*2, 1},
94       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960,   1},
95       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 480,   1},
96       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*3, 2},
97       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*2, 2},
98       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960,   2},
99       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 480,   2}
100 };
101 
102 static const int silk12_test[][4] = {
103       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*3, 1},
104       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*2, 1},
105       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960,   1},
106       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 480,   1},
107       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*3, 2},
108       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*2, 2},
109       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960,   2},
110       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 480,   2}
111 };
112 
113 static const int silk16_test[][4] = {
114       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*3, 1},
115       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*2, 1},
116       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960,   1},
117       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 480,   1},
118       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*3, 2},
119       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*2, 2},
120       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960,   2},
121       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 480,   2}
122 };
123 
124 static const int hybrid24_test[][4] = {
125       {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 1},
126       {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 1},
127       {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 2},
128       {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 2}
129 };
130 
131 static const int hybrid48_test[][4] = {
132       {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 1},
133       {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 1},
134       {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 2},
135       {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 2}
136 };
137 
138 static const int celt_test[][4] = {
139       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      960, 1},
140       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 1},
141       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      960, 1},
142       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    960, 1},
143 
144       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      480, 1},
145       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 1},
146       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      480, 1},
147       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    480, 1},
148 
149       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      240, 1},
150       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 240, 1},
151       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      240, 1},
152       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    240, 1},
153 
154       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      120, 1},
155       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 120, 1},
156       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      120, 1},
157       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    120, 1},
158 
159       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      960, 2},
160       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 2},
161       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      960, 2},
162       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    960, 2},
163 
164       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      480, 2},
165       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 2},
166       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      480, 2},
167       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    480, 2},
168 
169       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      240, 2},
170       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 240, 2},
171       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      240, 2},
172       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    240, 2},
173 
174       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      120, 2},
175       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 120, 2},
176       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      120, 2},
177       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    120, 2},
178 
179 };
180 
181 static const int celt_hq_test[][4] = {
182       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      960, 2},
183       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      480, 2},
184       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      240, 2},
185       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      120, 2},
186 };
187 
188 #if 0 /* This is a hack that replaces the normal encoder/decoder with the multistream version */
189 #define OpusEncoder OpusMSEncoder
190 #define OpusDecoder OpusMSDecoder
191 #define opus_encode opus_multistream_encode
192 #define opus_decode opus_multistream_decode
193 #define opus_encoder_ctl opus_multistream_encoder_ctl
194 #define opus_decoder_ctl opus_multistream_decoder_ctl
195 #define opus_encoder_create ms_opus_encoder_create
196 #define opus_decoder_create ms_opus_decoder_create
197 #define opus_encoder_destroy opus_multistream_encoder_destroy
198 #define opus_decoder_destroy opus_multistream_decoder_destroy
199 
200 static OpusEncoder *ms_opus_encoder_create(opus_int32 Fs, int channels, int application, int *error)
201 {
202    int streams, coupled_streams;
203    unsigned char mapping[256];
204    return (OpusEncoder *)opus_multistream_surround_encoder_create(Fs, channels, 1, &streams, &coupled_streams, mapping, application, error);
205 }
206 static OpusDecoder *ms_opus_decoder_create(opus_int32 Fs, int channels, int *error)
207 {
208    int streams;
209    int coupled_streams;
210    unsigned char mapping[256]={0,1};
211    streams = 1;
212    coupled_streams = channels==2;
213    return (OpusDecoder *)opus_multistream_decoder_create(Fs, channels, streams, coupled_streams, mapping, error);
214 }
215 #endif
216 
main(int argc,char * argv[])217 int main(int argc, char *argv[])
218 {
219     int err;
220     char *inFile, *outFile;
221     FILE *fin, *fout;
222     OpusEncoder *enc=NULL;
223     OpusDecoder *dec=NULL;
224     int args;
225     int len[2];
226     int frame_size, channels;
227     opus_int32 bitrate_bps=0;
228     unsigned char *data[2];
229     unsigned char *fbytes;
230     opus_int32 sampling_rate;
231     int use_vbr;
232     int max_payload_bytes;
233     int complexity;
234     int use_inbandfec;
235     int use_dtx;
236     int forcechannels;
237     int cvbr = 0;
238     int packet_loss_perc;
239     opus_int32 count=0, count_act=0;
240     int k;
241     opus_int32 skip=0;
242     int stop=0;
243     short *in, *out;
244     int application=OPUS_APPLICATION_AUDIO;
245     double bits=0.0, bits_max=0.0, bits_act=0.0, bits2=0.0, nrg;
246     double tot_samples=0;
247     opus_uint64 tot_in, tot_out;
248     int bandwidth=OPUS_AUTO;
249     const char *bandwidth_string;
250     int lost = 0, lost_prev = 1;
251     int toggle = 0;
252     opus_uint32 enc_final_range[2];
253     opus_uint32 dec_final_range;
254     int encode_only=0, decode_only=0;
255     int max_frame_size = 48000*2;
256     size_t num_read;
257     int curr_read=0;
258     int sweep_bps = 0;
259     int random_framesize=0, newsize=0, delayed_celt=0;
260     int sweep_max=0, sweep_min=0;
261     int random_fec=0;
262     const int (*mode_list)[4]=NULL;
263     int nb_modes_in_list=0;
264     int curr_mode=0;
265     int curr_mode_count=0;
266     int mode_switch_time = 48000;
267     int nb_encoded=0;
268     int remaining=0;
269     int variable_duration=OPUS_FRAMESIZE_ARG;
270     int delayed_decision=0;
271 
272     if (argc < 5 )
273     {
274        print_usage( argv );
275        return EXIT_FAILURE;
276     }
277 
278     tot_in=tot_out=0;
279     fprintf(stderr, "%s\n", opus_get_version_string());
280 
281     args = 1;
282     if (strcmp(argv[args], "-e")==0)
283     {
284         encode_only = 1;
285         args++;
286     } else if (strcmp(argv[args], "-d")==0)
287     {
288         decode_only = 1;
289         args++;
290     }
291     if (!decode_only && argc < 7 )
292     {
293        print_usage( argv );
294        return EXIT_FAILURE;
295     }
296 
297     if (!decode_only)
298     {
299        if (strcmp(argv[args], "voip")==0)
300           application = OPUS_APPLICATION_VOIP;
301        else if (strcmp(argv[args], "restricted-lowdelay")==0)
302           application = OPUS_APPLICATION_RESTRICTED_LOWDELAY;
303        else if (strcmp(argv[args], "audio")!=0) {
304           fprintf(stderr, "unknown application: %s\n", argv[args]);
305           print_usage(argv);
306           return EXIT_FAILURE;
307        }
308        args++;
309     }
310     sampling_rate = (opus_int32)atol(argv[args]);
311     args++;
312 
313     if (sampling_rate != 8000 && sampling_rate != 12000
314      && sampling_rate != 16000 && sampling_rate != 24000
315      && sampling_rate != 48000)
316     {
317         fprintf(stderr, "Supported sampling rates are 8000, 12000, "
318                 "16000, 24000 and 48000.\n");
319         return EXIT_FAILURE;
320     }
321     frame_size = sampling_rate/50;
322 
323     channels = atoi(argv[args]);
324     args++;
325 
326     if (channels < 1 || channels > 2)
327     {
328         fprintf(stderr, "Opus_demo supports only 1 or 2 channels.\n");
329         return EXIT_FAILURE;
330     }
331 
332     if (!decode_only)
333     {
334        bitrate_bps = (opus_int32)atol(argv[args]);
335        args++;
336     }
337 
338     /* defaults: */
339     use_vbr = 1;
340     max_payload_bytes = MAX_PACKET;
341     complexity = 10;
342     use_inbandfec = 0;
343     forcechannels = OPUS_AUTO;
344     use_dtx = 0;
345     packet_loss_perc = 0;
346 
347     while( args < argc - 2 ) {
348         /* process command line options */
349         if( strcmp( argv[ args ], "-cbr" ) == 0 ) {
350             check_encoder_option(decode_only, "-cbr");
351             use_vbr = 0;
352             args++;
353         } else if( strcmp( argv[ args ], "-bandwidth" ) == 0 ) {
354             check_encoder_option(decode_only, "-bandwidth");
355             if (strcmp(argv[ args + 1 ], "NB")==0)
356                 bandwidth = OPUS_BANDWIDTH_NARROWBAND;
357             else if (strcmp(argv[ args + 1 ], "MB")==0)
358                 bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
359             else if (strcmp(argv[ args + 1 ], "WB")==0)
360                 bandwidth = OPUS_BANDWIDTH_WIDEBAND;
361             else if (strcmp(argv[ args + 1 ], "SWB")==0)
362                 bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
363             else if (strcmp(argv[ args + 1 ], "FB")==0)
364                 bandwidth = OPUS_BANDWIDTH_FULLBAND;
365             else {
366                 fprintf(stderr, "Unknown bandwidth %s. "
367                                 "Supported are NB, MB, WB, SWB, FB.\n",
368                                 argv[ args + 1 ]);
369                 return EXIT_FAILURE;
370             }
371             args += 2;
372         } else if( strcmp( argv[ args ], "-framesize" ) == 0 ) {
373             check_encoder_option(decode_only, "-framesize");
374             if (strcmp(argv[ args + 1 ], "2.5")==0)
375                 frame_size = sampling_rate/400;
376             else if (strcmp(argv[ args + 1 ], "5")==0)
377                 frame_size = sampling_rate/200;
378             else if (strcmp(argv[ args + 1 ], "10")==0)
379                 frame_size = sampling_rate/100;
380             else if (strcmp(argv[ args + 1 ], "20")==0)
381                 frame_size = sampling_rate/50;
382             else if (strcmp(argv[ args + 1 ], "40")==0)
383                 frame_size = sampling_rate/25;
384             else if (strcmp(argv[ args + 1 ], "60")==0)
385                 frame_size = 3*sampling_rate/50;
386             else if (strcmp(argv[ args + 1 ], "80")==0)
387                 frame_size = 4*sampling_rate/50;
388             else if (strcmp(argv[ args + 1 ], "100")==0)
389                 frame_size = 5*sampling_rate/50;
390             else if (strcmp(argv[ args + 1 ], "120")==0)
391                 frame_size = 6*sampling_rate/50;
392             else {
393                 fprintf(stderr, "Unsupported frame size: %s ms. "
394                                 "Supported are 2.5, 5, 10, 20, 40, 60, 80, 100, 120.\n",
395                                 argv[ args + 1 ]);
396                 return EXIT_FAILURE;
397             }
398             args += 2;
399         } else if( strcmp( argv[ args ], "-max_payload" ) == 0 ) {
400             check_encoder_option(decode_only, "-max_payload");
401             max_payload_bytes = atoi( argv[ args + 1 ] );
402             args += 2;
403         } else if( strcmp( argv[ args ], "-complexity" ) == 0 ) {
404             check_encoder_option(decode_only, "-complexity");
405             complexity = atoi( argv[ args + 1 ] );
406             args += 2;
407         } else if( strcmp( argv[ args ], "-inbandfec" ) == 0 ) {
408             use_inbandfec = 1;
409             args++;
410         } else if( strcmp( argv[ args ], "-forcemono" ) == 0 ) {
411             check_encoder_option(decode_only, "-forcemono");
412             forcechannels = 1;
413             args++;
414         } else if( strcmp( argv[ args ], "-cvbr" ) == 0 ) {
415             check_encoder_option(decode_only, "-cvbr");
416             cvbr = 1;
417             args++;
418         } else if( strcmp( argv[ args ], "-delayed-decision" ) == 0 ) {
419             check_encoder_option(decode_only, "-delayed-decision");
420             delayed_decision = 1;
421             args++;
422         } else if( strcmp( argv[ args ], "-dtx") == 0 ) {
423             check_encoder_option(decode_only, "-dtx");
424             use_dtx = 1;
425             args++;
426         } else if( strcmp( argv[ args ], "-loss" ) == 0 ) {
427             packet_loss_perc = atoi( argv[ args + 1 ] );
428             args += 2;
429         } else if( strcmp( argv[ args ], "-sweep" ) == 0 ) {
430             check_encoder_option(decode_only, "-sweep");
431             sweep_bps = atoi( argv[ args + 1 ] );
432             args += 2;
433         } else if( strcmp( argv[ args ], "-random_framesize" ) == 0 ) {
434             check_encoder_option(decode_only, "-random_framesize");
435             random_framesize = 1;
436             args++;
437         } else if( strcmp( argv[ args ], "-sweep_max" ) == 0 ) {
438             check_encoder_option(decode_only, "-sweep_max");
439             sweep_max = atoi( argv[ args + 1 ] );
440             args += 2;
441         } else if( strcmp( argv[ args ], "-random_fec" ) == 0 ) {
442             check_encoder_option(decode_only, "-random_fec");
443             random_fec = 1;
444             args++;
445         } else if( strcmp( argv[ args ], "-silk8k_test" ) == 0 ) {
446             check_encoder_option(decode_only, "-silk8k_test");
447             mode_list = silk8_test;
448             nb_modes_in_list = 8;
449             args++;
450         } else if( strcmp( argv[ args ], "-silk12k_test" ) == 0 ) {
451             check_encoder_option(decode_only, "-silk12k_test");
452             mode_list = silk12_test;
453             nb_modes_in_list = 8;
454             args++;
455         } else if( strcmp( argv[ args ], "-silk16k_test" ) == 0 ) {
456             check_encoder_option(decode_only, "-silk16k_test");
457             mode_list = silk16_test;
458             nb_modes_in_list = 8;
459             args++;
460         } else if( strcmp( argv[ args ], "-hybrid24k_test" ) == 0 ) {
461             check_encoder_option(decode_only, "-hybrid24k_test");
462             mode_list = hybrid24_test;
463             nb_modes_in_list = 4;
464             args++;
465         } else if( strcmp( argv[ args ], "-hybrid48k_test" ) == 0 ) {
466             check_encoder_option(decode_only, "-hybrid48k_test");
467             mode_list = hybrid48_test;
468             nb_modes_in_list = 4;
469             args++;
470         } else if( strcmp( argv[ args ], "-celt_test" ) == 0 ) {
471             check_encoder_option(decode_only, "-celt_test");
472             mode_list = celt_test;
473             nb_modes_in_list = 32;
474             args++;
475         } else if( strcmp( argv[ args ], "-celt_hq_test" ) == 0 ) {
476             check_encoder_option(decode_only, "-celt_hq_test");
477             mode_list = celt_hq_test;
478             nb_modes_in_list = 4;
479             args++;
480         } else {
481             printf( "Error: unrecognized setting: %s\n\n", argv[ args ] );
482             print_usage( argv );
483             return EXIT_FAILURE;
484         }
485     }
486 
487     if (sweep_max)
488        sweep_min = bitrate_bps;
489 
490     if (max_payload_bytes < 0 || max_payload_bytes > MAX_PACKET)
491     {
492         fprintf (stderr, "max_payload_bytes must be between 0 and %d\n",
493                           MAX_PACKET);
494         return EXIT_FAILURE;
495     }
496 
497     inFile = argv[argc-2];
498     fin = fopen(inFile, "rb");
499     if (!fin)
500     {
501         fprintf (stderr, "Could not open input file %s\n", argv[argc-2]);
502         return EXIT_FAILURE;
503     }
504     if (mode_list)
505     {
506        int size;
507        fseek(fin, 0, SEEK_END);
508        size = ftell(fin);
509        fprintf(stderr, "File size is %d bytes\n", size);
510        fseek(fin, 0, SEEK_SET);
511        mode_switch_time = size/sizeof(short)/channels/nb_modes_in_list;
512        fprintf(stderr, "Switching mode every %d samples\n", mode_switch_time);
513     }
514 
515     outFile = argv[argc-1];
516     fout = fopen(outFile, "wb+");
517     if (!fout)
518     {
519         fprintf (stderr, "Could not open output file %s\n", argv[argc-1]);
520         fclose(fin);
521         return EXIT_FAILURE;
522     }
523 
524     if (!decode_only)
525     {
526        enc = opus_encoder_create(sampling_rate, channels, application, &err);
527        if (err != OPUS_OK)
528        {
529           fprintf(stderr, "Cannot create encoder: %s\n", opus_strerror(err));
530           fclose(fin);
531           fclose(fout);
532           return EXIT_FAILURE;
533        }
534        opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate_bps));
535        opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(bandwidth));
536        opus_encoder_ctl(enc, OPUS_SET_VBR(use_vbr));
537        opus_encoder_ctl(enc, OPUS_SET_VBR_CONSTRAINT(cvbr));
538        opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(complexity));
539        opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(use_inbandfec));
540        opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(forcechannels));
541        opus_encoder_ctl(enc, OPUS_SET_DTX(use_dtx));
542        opus_encoder_ctl(enc, OPUS_SET_PACKET_LOSS_PERC(packet_loss_perc));
543 
544        opus_encoder_ctl(enc, OPUS_GET_LOOKAHEAD(&skip));
545        opus_encoder_ctl(enc, OPUS_SET_LSB_DEPTH(16));
546        opus_encoder_ctl(enc, OPUS_SET_EXPERT_FRAME_DURATION(variable_duration));
547     }
548     if (!encode_only)
549     {
550        dec = opus_decoder_create(sampling_rate, channels, &err);
551        if (err != OPUS_OK)
552        {
553           fprintf(stderr, "Cannot create decoder: %s\n", opus_strerror(err));
554           fclose(fin);
555           fclose(fout);
556           return EXIT_FAILURE;
557        }
558     }
559 
560 
561     switch(bandwidth)
562     {
563     case OPUS_BANDWIDTH_NARROWBAND:
564          bandwidth_string = "narrowband";
565          break;
566     case OPUS_BANDWIDTH_MEDIUMBAND:
567          bandwidth_string = "mediumband";
568          break;
569     case OPUS_BANDWIDTH_WIDEBAND:
570          bandwidth_string = "wideband";
571          break;
572     case OPUS_BANDWIDTH_SUPERWIDEBAND:
573          bandwidth_string = "superwideband";
574          break;
575     case OPUS_BANDWIDTH_FULLBAND:
576          bandwidth_string = "fullband";
577          break;
578     case OPUS_AUTO:
579          bandwidth_string = "auto bandwidth";
580          break;
581     default:
582          bandwidth_string = "unknown";
583          break;
584     }
585 
586     if (decode_only)
587        fprintf(stderr, "Decoding with %ld Hz output (%d channels)\n",
588                        (long)sampling_rate, channels);
589     else
590        fprintf(stderr, "Encoding %ld Hz input at %.3f kb/s "
591                        "in %s with %d-sample frames.\n",
592                        (long)sampling_rate, bitrate_bps*0.001,
593                        bandwidth_string, frame_size);
594 
595     in = (short*)malloc(max_frame_size*channels*sizeof(short));
596     out = (short*)malloc(max_frame_size*channels*sizeof(short));
597     /* We need to allocate for 16-bit PCM data, but we store it as unsigned char. */
598     fbytes = (unsigned char*)malloc(max_frame_size*channels*sizeof(short));
599     data[0] = (unsigned char*)calloc(max_payload_bytes,sizeof(unsigned char));
600     if ( use_inbandfec ) {
601         data[1] = (unsigned char*)calloc(max_payload_bytes,sizeof(unsigned char));
602     }
603     if(delayed_decision)
604     {
605        if (frame_size==sampling_rate/400)
606           variable_duration = OPUS_FRAMESIZE_2_5_MS;
607        else if (frame_size==sampling_rate/200)
608           variable_duration = OPUS_FRAMESIZE_5_MS;
609        else if (frame_size==sampling_rate/100)
610           variable_duration = OPUS_FRAMESIZE_10_MS;
611        else if (frame_size==sampling_rate/50)
612           variable_duration = OPUS_FRAMESIZE_20_MS;
613        else if (frame_size==sampling_rate/25)
614           variable_duration = OPUS_FRAMESIZE_40_MS;
615        else if (frame_size==3*sampling_rate/50)
616           variable_duration = OPUS_FRAMESIZE_60_MS;
617        else if (frame_size==4*sampling_rate/50)
618           variable_duration = OPUS_FRAMESIZE_80_MS;
619        else if (frame_size==5*sampling_rate/50)
620           variable_duration = OPUS_FRAMESIZE_100_MS;
621        else
622           variable_duration = OPUS_FRAMESIZE_120_MS;
623        opus_encoder_ctl(enc, OPUS_SET_EXPERT_FRAME_DURATION(variable_duration));
624        frame_size = 2*48000;
625     }
626     while (!stop)
627     {
628         if (delayed_celt)
629         {
630             frame_size = newsize;
631             delayed_celt = 0;
632         } else if (random_framesize && rand()%20==0)
633         {
634             newsize = rand()%6;
635             switch(newsize)
636             {
637             case 0: newsize=sampling_rate/400; break;
638             case 1: newsize=sampling_rate/200; break;
639             case 2: newsize=sampling_rate/100; break;
640             case 3: newsize=sampling_rate/50; break;
641             case 4: newsize=sampling_rate/25; break;
642             case 5: newsize=3*sampling_rate/50; break;
643             }
644             while (newsize < sampling_rate/25 && bitrate_bps-abs(sweep_bps) <= 3*12*sampling_rate/newsize)
645                newsize*=2;
646             if (newsize < sampling_rate/100 && frame_size >= sampling_rate/100)
647             {
648                 opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY));
649                 delayed_celt=1;
650             } else {
651                 frame_size = newsize;
652             }
653         }
654         if (random_fec && rand()%30==0)
655         {
656            opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(rand()%4==0));
657         }
658         if (decode_only)
659         {
660             unsigned char ch[4];
661             num_read = fread(ch, 1, 4, fin);
662             if (num_read!=4)
663                 break;
664             len[toggle] = char_to_int(ch);
665             if (len[toggle]>max_payload_bytes || len[toggle]<0)
666             {
667                 fprintf(stderr, "Invalid payload length: %d\n",len[toggle]);
668                 break;
669             }
670             num_read = fread(ch, 1, 4, fin);
671             if (num_read!=4)
672                 break;
673             enc_final_range[toggle] = char_to_int(ch);
674             num_read = fread(data[toggle], 1, len[toggle], fin);
675             if (num_read!=(size_t)len[toggle])
676             {
677                 fprintf(stderr, "Ran out of input, "
678                                 "expecting %d bytes got %d\n",
679                                 len[toggle],(int)num_read);
680                 break;
681             }
682         } else {
683             int i;
684             if (mode_list!=NULL)
685             {
686                 opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(mode_list[curr_mode][1]));
687                 opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(mode_list[curr_mode][0]));
688                 opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(mode_list[curr_mode][3]));
689                 frame_size = mode_list[curr_mode][2];
690             }
691             num_read = fread(fbytes, sizeof(short)*channels, frame_size-remaining, fin);
692             curr_read = (int)num_read;
693             tot_in += curr_read;
694             for(i=0;i<curr_read*channels;i++)
695             {
696                 opus_int32 s;
697                 s=fbytes[2*i+1]<<8|fbytes[2*i];
698                 s=((s&0xFFFF)^0x8000)-0x8000;
699                 in[i+remaining*channels]=s;
700             }
701             if (curr_read+remaining < frame_size)
702             {
703                 for (i=(curr_read+remaining)*channels;i<frame_size*channels;i++)
704                    in[i] = 0;
705                 if (encode_only || decode_only)
706                    stop = 1;
707             }
708             len[toggle] = opus_encode(enc, in, frame_size, data[toggle], max_payload_bytes);
709             nb_encoded = opus_packet_get_samples_per_frame(data[toggle], sampling_rate)*opus_packet_get_nb_frames(data[toggle], len[toggle]);
710             remaining = frame_size-nb_encoded;
711             for(i=0;i<remaining*channels;i++)
712                in[i] = in[nb_encoded*channels+i];
713             if (sweep_bps!=0)
714             {
715                bitrate_bps += sweep_bps;
716                if (sweep_max)
717                {
718                   if (bitrate_bps > sweep_max)
719                      sweep_bps = -sweep_bps;
720                   else if (bitrate_bps < sweep_min)
721                      sweep_bps = -sweep_bps;
722                }
723                /* safety */
724                if (bitrate_bps<1000)
725                   bitrate_bps = 1000;
726                opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate_bps));
727             }
728             opus_encoder_ctl(enc, OPUS_GET_FINAL_RANGE(&enc_final_range[toggle]));
729             if (len[toggle] < 0)
730             {
731                 fprintf (stderr, "opus_encode() returned %d\n", len[toggle]);
732                 fclose(fin);
733                 fclose(fout);
734                 return EXIT_FAILURE;
735             }
736             curr_mode_count += frame_size;
737             if (curr_mode_count > mode_switch_time && curr_mode < nb_modes_in_list-1)
738             {
739                curr_mode++;
740                curr_mode_count = 0;
741             }
742         }
743 
744 #if 0 /* This is for testing the padding code, do not enable by default */
745         if (len[toggle]<1275)
746         {
747            int new_len = len[toggle]+rand()%(max_payload_bytes-len[toggle]);
748            if ((err = opus_packet_pad(data[toggle], len[toggle], new_len)) != OPUS_OK)
749            {
750               fprintf(stderr, "padding failed: %s\n", opus_strerror(err));
751               return EXIT_FAILURE;
752            }
753            len[toggle] = new_len;
754         }
755 #endif
756         if (encode_only)
757         {
758             unsigned char int_field[4];
759             int_to_char(len[toggle], int_field);
760             if (fwrite(int_field, 1, 4, fout) != 4) {
761                fprintf(stderr, "Error writing.\n");
762                return EXIT_FAILURE;
763             }
764             int_to_char(enc_final_range[toggle], int_field);
765             if (fwrite(int_field, 1, 4, fout) != 4) {
766                fprintf(stderr, "Error writing.\n");
767                return EXIT_FAILURE;
768             }
769             if (fwrite(data[toggle], 1, len[toggle], fout) != (unsigned)len[toggle]) {
770                fprintf(stderr, "Error writing.\n");
771                return EXIT_FAILURE;
772             }
773             tot_samples += nb_encoded;
774         } else {
775             opus_int32 output_samples;
776             lost = len[toggle]==0 || (packet_loss_perc>0 && rand()%100 < packet_loss_perc);
777             if (lost)
778                opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION(&output_samples));
779             else
780                output_samples = max_frame_size;
781             if( count >= use_inbandfec ) {
782                 /* delay by one packet when using in-band FEC */
783                 if( use_inbandfec  ) {
784                     if( lost_prev ) {
785                         /* attempt to decode with in-band FEC from next packet */
786                         opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION(&output_samples));
787                         output_samples = opus_decode(dec, lost ? NULL : data[toggle], len[toggle], out, output_samples, 1);
788                     } else {
789                         /* regular decode */
790                         output_samples = max_frame_size;
791                         output_samples = opus_decode(dec, data[1-toggle], len[1-toggle], out, output_samples, 0);
792                     }
793                 } else {
794                     output_samples = opus_decode(dec, lost ? NULL : data[toggle], len[toggle], out, output_samples, 0);
795                 }
796                 if (output_samples>0)
797                 {
798                     if (!decode_only && tot_out + output_samples > tot_in)
799                     {
800                        stop=1;
801                        output_samples = (opus_int32)(tot_in - tot_out);
802                     }
803                     if (output_samples>skip) {
804                        int i;
805                        for(i=0;i<(output_samples-skip)*channels;i++)
806                        {
807                           short s;
808                           s=out[i+(skip*channels)];
809                           fbytes[2*i]=s&0xFF;
810                           fbytes[2*i+1]=(s>>8)&0xFF;
811                        }
812                        if (fwrite(fbytes, sizeof(short)*channels, output_samples-skip, fout) != (unsigned)(output_samples-skip)){
813                           fprintf(stderr, "Error writing.\n");
814                           return EXIT_FAILURE;
815                        }
816                        tot_out += output_samples-skip;
817                     }
818                     if (output_samples<skip) skip -= output_samples;
819                     else skip = 0;
820                 } else {
821                    fprintf(stderr, "error decoding frame: %s\n",
822                                    opus_strerror(output_samples));
823                 }
824                 tot_samples += output_samples;
825             }
826         }
827 
828         if (!encode_only)
829            opus_decoder_ctl(dec, OPUS_GET_FINAL_RANGE(&dec_final_range));
830         /* compare final range encoder rng values of encoder and decoder */
831         if( enc_final_range[toggle^use_inbandfec]!=0  && !encode_only
832          && !lost && !lost_prev
833          && dec_final_range != enc_final_range[toggle^use_inbandfec] ) {
834             fprintf (stderr, "Error: Range coder state mismatch "
835                              "between encoder and decoder "
836                              "in frame %ld: 0x%8lx vs 0x%8lx\n",
837                          (long)count,
838                          (unsigned long)enc_final_range[toggle^use_inbandfec],
839                          (unsigned long)dec_final_range);
840             fclose(fin);
841             fclose(fout);
842             return EXIT_FAILURE;
843         }
844 
845         lost_prev = lost;
846         if( count >= use_inbandfec ) {
847             /* count bits */
848             bits += len[toggle]*8;
849             bits_max = ( len[toggle]*8 > bits_max ) ? len[toggle]*8 : bits_max;
850             bits2 += len[toggle]*len[toggle]*64;
851             if (!decode_only)
852             {
853                 nrg = 0.0;
854                 for ( k = 0; k < frame_size * channels; k++ ) {
855                     nrg += in[ k ] * (double)in[ k ];
856                 }
857                 nrg /= frame_size * channels;
858                 if( nrg > 1e5 ) {
859                     bits_act += len[toggle]*8;
860                     count_act++;
861                 }
862             }
863         }
864         count++;
865         toggle = (toggle + use_inbandfec) & 1;
866     }
867 
868     /* Print out bitrate statistics */
869     if(decode_only)
870         frame_size = (int)(tot_samples / count);
871     count -= use_inbandfec;
872     fprintf (stderr, "average bitrate:             %7.3f kb/s\n",
873                      1e-3*bits*sampling_rate/tot_samples);
874     fprintf (stderr, "maximum bitrate:             %7.3f kb/s\n",
875                      1e-3*bits_max*sampling_rate/frame_size);
876     if (!decode_only)
877        fprintf (stderr, "active bitrate:              %7.3f kb/s\n",
878                1e-3*bits_act*sampling_rate/(1e-15+frame_size*(double)count_act));
879     fprintf (stderr, "bitrate standard deviation:  %7.3f kb/s\n",
880             1e-3*sqrt(bits2/count - bits*bits/(count*(double)count))*sampling_rate/frame_size);
881     silk_TimerSave("opus_timing.txt");
882     opus_encoder_destroy(enc);
883     opus_decoder_destroy(dec);
884     free(data[0]);
885     if (use_inbandfec)
886         free(data[1]);
887     fclose(fin);
888     fclose(fout);
889     free(in);
890     free(out);
891     free(fbytes);
892     return EXIT_SUCCESS;
893 }
894