xref: /aosp_15_r20/external/libopus/src/opus_demo.c (revision a58d3d2adb790c104798cd88c8a3aff4fa8b82cc)
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 #ifdef ENABLE_LOSSGEN
43 #include "lossgen.h"
44 #endif
45 
46 #define MAX_PACKET 1500
47 
48 #ifdef USE_WEIGHTS_FILE
49 # if __unix__
50 #  include <fcntl.h>
51 #  include <sys/mman.h>
52 #  include <unistd.h>
53 #  include <sys/stat.h>
54 /* When available, mmap() is preferable to reading the file, as it leads to
55    better resource utilization, especially if multiple processes are using the same
56    file (mapping will be shared in cache). */
load_blob(const char * filename,int * len)57 void *load_blob(const char *filename, int *len) {
58   int fd;
59   void *data;
60   struct stat st;
61   if (stat(filename, &st)) {
62      *len = 0;
63      return NULL;
64   }
65   *len = st.st_size;
66   fd = open(filename, O_RDONLY);
67   if (fd<0) {
68      *len = 0;
69      return NULL;
70   }
71   data = mmap(NULL, *len, PROT_READ, MAP_SHARED, fd, 0);
72   if (data == MAP_FAILED) {
73      *len = 0;
74      data = NULL;
75   }
76   close(fd);
77   return data;
78 }
free_blob(void * blob,int len)79 void free_blob(void *blob, int len) {
80   if (blob) munmap(blob, len);
81 }
82 # else
load_blob(const char * filename,int * len)83 void *load_blob(const char *filename, int *len) {
84   FILE *file;
85   void *data;
86   file = fopen(filename, "r");
87   if (file == NULL)
88   {
89     perror("could not open blob file");
90     *len = 0;
91     return NULL;
92   }
93   fseek(file, 0L, SEEK_END);
94   *len = ftell(file);
95   fseek(file, 0L, SEEK_SET);
96   if (*len <= 0) {
97      *len = 0;
98      return NULL;
99   }
100   data = malloc(*len);
101   if (!data) {
102      *len = 0;
103      return NULL;
104   }
105   *len = fread(data, 1, *len, file);
106   return data;
107 }
free_blob(void * blob,int len)108 void free_blob(void *blob, int len) {
109   free(blob);
110   (void)len;
111 }
112 # endif
113 #endif
114 
115 
print_usage(char * argv[])116 void print_usage( char* argv[] )
117 {
118     fprintf(stderr, "Usage: %s [-e] <application> <sampling rate (Hz)> <channels (1/2)> "
119         "<bits per second>  [options] <input> <output>\n", argv[0]);
120     fprintf(stderr, "       %s -d <sampling rate (Hz)> <channels (1/2)> "
121         "[options] <input> <output>\n\n", argv[0]);
122     fprintf(stderr, "application: voip | audio | restricted-lowdelay\n" );
123     fprintf(stderr, "options:\n" );
124     fprintf(stderr, "-e                   : only runs the encoder (output the bit-stream)\n" );
125     fprintf(stderr, "-d                   : only runs the decoder (reads the bit-stream as input)\n" );
126     fprintf(stderr, "-cbr                 : enable constant bitrate; default: variable bitrate\n" );
127     fprintf(stderr, "-cvbr                : enable constrained variable bitrate; default: unconstrained\n" );
128     fprintf(stderr, "-delayed-decision    : use look-ahead for speech/music detection (experts only); default: disabled\n" );
129     fprintf(stderr, "-bandwidth <NB|MB|WB|SWB|FB> : audio bandwidth (from narrowband to fullband); default: sampling rate\n" );
130     fprintf(stderr, "-framesize <2.5|5|10|20|40|60|80|100|120> : frame size in ms; default: 20 \n" );
131     fprintf(stderr, "-max_payload <bytes> : maximum payload size in bytes, default: 1024\n" );
132     fprintf(stderr, "-complexity <comp>   : encoder complexity, 0 (lowest) ... 10 (highest); default: 10\n" );
133     fprintf(stderr, "-dec_complexity <comp> : decoder complexity, 0 (lowest) ... 10 (highest); default: 0\n" );
134     fprintf(stderr, "-inbandfec           : enable SILK inband FEC\n" );
135     fprintf(stderr, "-forcemono           : force mono encoding, even for stereo input\n" );
136     fprintf(stderr, "-dtx                 : enable SILK DTX\n" );
137     fprintf(stderr, "-loss <perc>         : optimize for loss percentage and simulate packet loss, in percent (0-100); default: 0\n" );
138 #ifdef ENABLE_LOSSGEN
139     fprintf(stderr, "-sim_loss <perc>     : simulate realistic (bursty) packet loss from percentage, using generative model\n" );
140 #endif
141     fprintf(stderr, "-lossfile <file>     : simulate packet loss, reading loss from file\n" );
142     fprintf(stderr, "-dred <frames>       : add Deep REDundancy (in units of 10-ms frames)\n" );
143 }
144 
int_to_char(opus_uint32 i,unsigned char ch[4])145 static void int_to_char(opus_uint32 i, unsigned char ch[4])
146 {
147     ch[0] = i>>24;
148     ch[1] = (i>>16)&0xFF;
149     ch[2] = (i>>8)&0xFF;
150     ch[3] = i&0xFF;
151 }
152 
char_to_int(unsigned char ch[4])153 static opus_uint32 char_to_int(unsigned char ch[4])
154 {
155     return ((opus_uint32)ch[0]<<24) | ((opus_uint32)ch[1]<<16)
156          | ((opus_uint32)ch[2]<< 8) |  (opus_uint32)ch[3];
157 }
158 
159 #define check_encoder_option(decode_only, opt) do {if (decode_only) {fprintf(stderr, "option %s is only for encoding\n", opt); goto failure;}} while(0)
160 #define check_decoder_option(encode_only, opt) do {if (encode_only) {fprintf(stderr, "option %s is only for decoding\n", opt); goto failure;}} while(0)
161 
162 static const int silk8_test[][4] = {
163       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*3, 1},
164       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*2, 1},
165       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960,   1},
166       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 480,   1},
167       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*3, 2},
168       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960*2, 2},
169       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 960,   2},
170       {MODE_SILK_ONLY, OPUS_BANDWIDTH_NARROWBAND, 480,   2}
171 };
172 
173 static const int silk12_test[][4] = {
174       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*3, 1},
175       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*2, 1},
176       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960,   1},
177       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 480,   1},
178       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*3, 2},
179       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960*2, 2},
180       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 960,   2},
181       {MODE_SILK_ONLY, OPUS_BANDWIDTH_MEDIUMBAND, 480,   2}
182 };
183 
184 static const int silk16_test[][4] = {
185       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*3, 1},
186       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*2, 1},
187       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960,   1},
188       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 480,   1},
189       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*3, 2},
190       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960*2, 2},
191       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 960,   2},
192       {MODE_SILK_ONLY, OPUS_BANDWIDTH_WIDEBAND, 480,   2}
193 };
194 
195 static const int hybrid24_test[][4] = {
196       {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 1},
197       {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 1},
198       {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 2},
199       {MODE_SILK_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 2}
200 };
201 
202 static const int hybrid48_test[][4] = {
203       {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 1},
204       {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 1},
205       {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 960, 2},
206       {MODE_SILK_ONLY, OPUS_BANDWIDTH_FULLBAND, 480, 2}
207 };
208 
209 static const int celt_test[][4] = {
210       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      960, 1},
211       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 1},
212       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      960, 1},
213       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    960, 1},
214 
215       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      480, 1},
216       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 1},
217       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      480, 1},
218       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    480, 1},
219 
220       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      240, 1},
221       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 240, 1},
222       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      240, 1},
223       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    240, 1},
224 
225       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      120, 1},
226       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 120, 1},
227       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      120, 1},
228       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    120, 1},
229 
230       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      960, 2},
231       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 960, 2},
232       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      960, 2},
233       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    960, 2},
234 
235       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      480, 2},
236       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 480, 2},
237       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      480, 2},
238       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    480, 2},
239 
240       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      240, 2},
241       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 240, 2},
242       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      240, 2},
243       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    240, 2},
244 
245       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      120, 2},
246       {MODE_CELT_ONLY, OPUS_BANDWIDTH_SUPERWIDEBAND, 120, 2},
247       {MODE_CELT_ONLY, OPUS_BANDWIDTH_WIDEBAND,      120, 2},
248       {MODE_CELT_ONLY, OPUS_BANDWIDTH_NARROWBAND,    120, 2},
249 
250 };
251 
252 static const int celt_hq_test[][4] = {
253       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      960, 2},
254       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      480, 2},
255       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      240, 2},
256       {MODE_CELT_ONLY, OPUS_BANDWIDTH_FULLBAND,      120, 2},
257 };
258 
259 #if 0 /* This is a hack that replaces the normal encoder/decoder with the multistream version */
260 #define OpusEncoder OpusMSEncoder
261 #define OpusDecoder OpusMSDecoder
262 #define opus_encode opus_multistream_encode
263 #define opus_decode opus_multistream_decode
264 #define opus_encoder_ctl opus_multistream_encoder_ctl
265 #define opus_decoder_ctl opus_multistream_decoder_ctl
266 #define opus_encoder_create ms_opus_encoder_create
267 #define opus_decoder_create ms_opus_decoder_create
268 #define opus_encoder_destroy opus_multistream_encoder_destroy
269 #define opus_decoder_destroy opus_multistream_decoder_destroy
270 
271 static OpusEncoder *ms_opus_encoder_create(opus_int32 Fs, int channels, int application, int *error)
272 {
273    int streams, coupled_streams;
274    unsigned char mapping[256];
275    return (OpusEncoder *)opus_multistream_surround_encoder_create(Fs, channels, 1, &streams, &coupled_streams, mapping, application, error);
276 }
277 static OpusDecoder *ms_opus_decoder_create(opus_int32 Fs, int channels, int *error)
278 {
279    int streams;
280    int coupled_streams;
281    unsigned char mapping[256]={0,1};
282    streams = 1;
283    coupled_streams = channels==2;
284    return (OpusDecoder *)opus_multistream_decoder_create(Fs, channels, streams, coupled_streams, mapping, error);
285 }
286 #endif
287 
288 
289 #ifdef ENABLE_OSCE_TRAINING_DATA
290 #define COMPLEXITY_MIN 0
291 #define COMPLEXITY_MAX 10
292 
293 #define PACKET_LOSS_PERC_MIN 0
294 #define PACKET_LOSS_PERC_MAX 50
295 #define PACKET_LOSS_PERC_STEP 5
296 
297 #define CBR_BITRATE_LIMIT 8000
298 
299 #define NUM_BITRATES 102
300 static int bitrates[NUM_BITRATES] = {
301         6000,  6060,  6120,  6180,  6240,  6300,  6360,  6420,  6480,
302         6525,  6561,  6598,  6634,  6670,  6707,  6743,  6780,  6816,
303         6853,  6889,  6926,  6962,  6999,  7042,  7085,  7128,  7171,
304         7215,  7258,  7301,  7344,  7388,  7431,  7474,  7512,  7541,
305         7570,  7599,  7628,  7657,  7686,  7715,  7744,  7773,  7802,
306         7831,  7860,  7889,  7918,  7947,  7976,  8013,  8096,  8179,
307         8262,  8344,  8427,  8511,  8605,  8699,  8792,  8886,  8980,
308         9100,  9227,  9354,  9480,  9561,  9634,  9706,  9779,  9851,
309         9924,  9996, 10161, 10330, 10499, 10698, 10898, 11124, 11378,
310        11575, 11719, 11862, 12014, 12345, 12751, 13195, 13561, 13795,
311        14069, 14671, 15403, 15790, 16371, 17399, 17968, 19382, 20468,
312        22000, 32000, 64000
313 };
314 
randint(int min,int max,int step)315 static int randint(int min, int max, int step)
316 {
317     double r = ((double) rand())/ (RAND_MAX + 1.);
318     int d;
319 
320     d = ((int) ((max + 1 - min) * r / step) * step) + min;
321 
322     return d;
323 }
324 
new_random_setting(OpusEncoder * enc)325 static void new_random_setting(OpusEncoder *enc)
326 {
327     int bitrate_bps;
328     int complexity;
329     int packet_loss_perc;
330     int use_vbr;
331 
332     bitrate_bps = bitrates[randint(0, NUM_BITRATES - 1, 1)];
333     complexity  = randint(COMPLEXITY_MIN, COMPLEXITY_MAX, 1);
334     packet_loss_perc = randint(PACKET_LOSS_PERC_MIN, PACKET_LOSS_PERC_MAX, PACKET_LOSS_PERC_STEP);
335     use_vbr = bitrate_bps < CBR_BITRATE_LIMIT ? 1 : randint(0, 1, 1);
336 
337     if (1)
338     {
339         printf("changing settings to %d\t%d\t%d\t%d\n", bitrate_bps, complexity, packet_loss_perc, use_vbr);
340     }
341 
342     opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate_bps));
343     opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(complexity));
344     opus_encoder_ctl(enc, OPUS_SET_PACKET_LOSS_PERC(packet_loss_perc));
345     opus_encoder_ctl(enc, OPUS_SET_VBR(use_vbr));
346 }
347 
348 #endif
349 
main(int argc,char * argv[])350 int main(int argc, char *argv[])
351 {
352     int err;
353     char *inFile, *outFile;
354     FILE *fin=NULL;
355     FILE *fout=NULL;
356     OpusEncoder *enc=NULL;
357     OpusDecoder *dec=NULL;
358     OpusDRED *dred=NULL;
359     OpusDREDDecoder *dred_dec=NULL;
360     int args;
361     int len;
362     int frame_size, channels;
363     opus_int32 bitrate_bps=0;
364     unsigned char *data = NULL;
365     unsigned char *fbytes=NULL;
366     opus_int32 sampling_rate;
367     int use_vbr;
368     int max_payload_bytes;
369     int complexity;
370     int dec_complexity;
371     int use_inbandfec;
372     int use_dtx;
373     int forcechannels;
374     int cvbr = 0;
375     int packet_loss_perc;
376 #ifdef ENABLE_LOSSGEN
377     float lossgen_perc = -1.f;
378     LossGenState lossgen;
379 #endif
380     opus_int32 count=0, count_act=0;
381     int k;
382     opus_int32 skip=0;
383     int stop=0;
384     short *in=NULL;
385     short *out=NULL;
386     int application=OPUS_APPLICATION_AUDIO;
387     double bits=0.0, bits_max=0.0, bits_act=0.0, bits2=0.0, nrg;
388     double tot_samples=0;
389     opus_uint64 tot_in, tot_out;
390     int bandwidth=OPUS_AUTO;
391     const char *bandwidth_string;
392     int lost = 0, lost_prev = 1;
393     opus_uint32 enc_final_range;
394     opus_uint32 dec_final_range;
395     int encode_only=0, decode_only=0;
396     int max_frame_size = 48000*2;
397     size_t num_read;
398     int curr_read=0;
399     int sweep_bps = 0;
400     int random_framesize=0, newsize=0, delayed_celt=0;
401     int sweep_max=0, sweep_min=0;
402     int random_fec=0;
403     const int (*mode_list)[4]=NULL;
404     int nb_modes_in_list=0;
405     int curr_mode=0;
406     int curr_mode_count=0;
407     int mode_switch_time = 48000;
408     int nb_encoded=0;
409     int remaining=0;
410     int variable_duration=OPUS_FRAMESIZE_ARG;
411     int delayed_decision=0;
412     int ret = EXIT_FAILURE;
413     int lost_count=0;
414     FILE *packet_loss_file=NULL;
415     int dred_duration=0;
416 #ifdef ENABLE_OSCE_TRAINING_DATA
417     int silk_random_switching = 0;
418     int silk_frame_counter = 0;
419 #endif
420 #ifdef USE_WEIGHTS_FILE
421     int blob_len;
422     void *blob_data;
423     const char *filename = "weights_blob.bin";
424     blob_data = load_blob(filename, &blob_len);
425 #endif
426 
427     if (argc < 5 )
428     {
429        print_usage( argv );
430        goto failure;
431     }
432 
433     tot_in=tot_out=0;
434     fprintf(stderr, "%s\n", opus_get_version_string());
435 
436     args = 1;
437     if (strcmp(argv[args], "-e")==0)
438     {
439         encode_only = 1;
440         args++;
441     } else if (strcmp(argv[args], "-d")==0)
442     {
443         decode_only = 1;
444         args++;
445     }
446     if (!decode_only && argc < 7 )
447     {
448        print_usage( argv );
449        goto failure;
450     }
451 
452     if (!decode_only)
453     {
454        if (strcmp(argv[args], "voip")==0)
455           application = OPUS_APPLICATION_VOIP;
456        else if (strcmp(argv[args], "restricted-lowdelay")==0)
457           application = OPUS_APPLICATION_RESTRICTED_LOWDELAY;
458        else if (strcmp(argv[args], "audio")!=0) {
459           fprintf(stderr, "unknown application: %s\n", argv[args]);
460           print_usage(argv);
461           goto failure;
462        }
463        args++;
464     }
465     sampling_rate = (opus_int32)atol(argv[args]);
466     args++;
467 
468     if (sampling_rate != 8000 && sampling_rate != 12000
469      && sampling_rate != 16000 && sampling_rate != 24000
470      && sampling_rate != 48000)
471     {
472         fprintf(stderr, "Supported sampling rates are 8000, 12000, "
473                 "16000, 24000 and 48000.\n");
474         goto failure;
475     }
476     frame_size = sampling_rate/50;
477 
478     channels = atoi(argv[args]);
479     args++;
480 
481     if (channels < 1 || channels > 2)
482     {
483         fprintf(stderr, "Opus_demo supports only 1 or 2 channels.\n");
484         goto failure;
485     }
486 
487     if (!decode_only)
488     {
489        bitrate_bps = (opus_int32)atol(argv[args]);
490        args++;
491     }
492 
493     /* defaults: */
494     use_vbr = 1;
495     max_payload_bytes = MAX_PACKET;
496     complexity = 10;
497     dec_complexity = 0;
498     use_inbandfec = 0;
499     forcechannels = OPUS_AUTO;
500     use_dtx = 0;
501     packet_loss_perc = 0;
502 
503     while( args < argc - 2 ) {
504         /* process command line options */
505         if( strcmp( argv[ args ], "-cbr" ) == 0 ) {
506             check_encoder_option(decode_only, "-cbr");
507             use_vbr = 0;
508             args++;
509         } else if( strcmp( argv[ args ], "-bandwidth" ) == 0 ) {
510             check_encoder_option(decode_only, "-bandwidth");
511             if (strcmp(argv[ args + 1 ], "NB")==0)
512                 bandwidth = OPUS_BANDWIDTH_NARROWBAND;
513             else if (strcmp(argv[ args + 1 ], "MB")==0)
514                 bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;
515             else if (strcmp(argv[ args + 1 ], "WB")==0)
516                 bandwidth = OPUS_BANDWIDTH_WIDEBAND;
517             else if (strcmp(argv[ args + 1 ], "SWB")==0)
518                 bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;
519             else if (strcmp(argv[ args + 1 ], "FB")==0)
520                 bandwidth = OPUS_BANDWIDTH_FULLBAND;
521             else {
522                 fprintf(stderr, "Unknown bandwidth %s. "
523                                 "Supported are NB, MB, WB, SWB, FB.\n",
524                                 argv[ args + 1 ]);
525                 goto failure;
526             }
527             args += 2;
528         } else if( strcmp( argv[ args ], "-framesize" ) == 0 ) {
529             check_encoder_option(decode_only, "-framesize");
530             if (strcmp(argv[ args + 1 ], "2.5")==0)
531                 frame_size = sampling_rate/400;
532             else if (strcmp(argv[ args + 1 ], "5")==0)
533                 frame_size = sampling_rate/200;
534             else if (strcmp(argv[ args + 1 ], "10")==0)
535                 frame_size = sampling_rate/100;
536             else if (strcmp(argv[ args + 1 ], "20")==0)
537                 frame_size = sampling_rate/50;
538             else if (strcmp(argv[ args + 1 ], "40")==0)
539                 frame_size = sampling_rate/25;
540             else if (strcmp(argv[ args + 1 ], "60")==0)
541                 frame_size = 3*sampling_rate/50;
542             else if (strcmp(argv[ args + 1 ], "80")==0)
543                 frame_size = 4*sampling_rate/50;
544             else if (strcmp(argv[ args + 1 ], "100")==0)
545                 frame_size = 5*sampling_rate/50;
546             else if (strcmp(argv[ args + 1 ], "120")==0)
547                 frame_size = 6*sampling_rate/50;
548             else {
549                 fprintf(stderr, "Unsupported frame size: %s ms. "
550                                 "Supported are 2.5, 5, 10, 20, 40, 60, 80, 100, 120.\n",
551                                 argv[ args + 1 ]);
552                 goto failure;
553             }
554             args += 2;
555         } else if( strcmp( argv[ args ], "-max_payload" ) == 0 ) {
556             check_encoder_option(decode_only, "-max_payload");
557             max_payload_bytes = atoi( argv[ args + 1 ] );
558             args += 2;
559         } else if( strcmp( argv[ args ], "-complexity" ) == 0 ) {
560             check_encoder_option(decode_only, "-complexity");
561             complexity = atoi( argv[ args + 1 ] );
562             args += 2;
563         } else if( strcmp( argv[ args ], "-dec_complexity" ) == 0 ) {
564             check_decoder_option(encode_only, "-dec_complexity");
565             dec_complexity = atoi( argv[ args + 1 ] );
566             args += 2;
567         } else if( strcmp( argv[ args ], "-inbandfec" ) == 0 ) {
568             use_inbandfec = 1;
569             args++;
570         } else if( strcmp( argv[ args ], "-forcemono" ) == 0 ) {
571             check_encoder_option(decode_only, "-forcemono");
572             forcechannels = 1;
573             args++;
574         } else if( strcmp( argv[ args ], "-cvbr" ) == 0 ) {
575             check_encoder_option(decode_only, "-cvbr");
576             cvbr = 1;
577             args++;
578         } else if( strcmp( argv[ args ], "-delayed-decision" ) == 0 ) {
579             check_encoder_option(decode_only, "-delayed-decision");
580             delayed_decision = 1;
581             args++;
582         } else if( strcmp( argv[ args ], "-dtx") == 0 ) {
583             check_encoder_option(decode_only, "-dtx");
584             use_dtx = 1;
585             args++;
586         } else if( strcmp( argv[ args ], "-loss" ) == 0 ) {
587             packet_loss_perc = atoi( argv[ args + 1 ] );
588             args += 2;
589 #ifdef ENABLE_LOSSGEN
590         } else if( strcmp( argv[ args ], "-sim_loss" ) == 0 ) {
591             lossgen_perc = atof( argv[ args + 1 ] );
592             lossgen_init(&lossgen);
593             args += 2;
594 #endif
595         } else if( strcmp( argv[ args ], "-lossfile" ) == 0 ) {
596             packet_loss_file = fopen( argv[ args + 1 ], "r" );
597             if (packet_loss_file == NULL) {
598                 fprintf(stderr, "failed to open loss file %s\n", argv[ args + 1 ] );
599                 exit(1);
600             }
601             args += 2;
602         } else if( strcmp( argv[ args ], "-dred" ) == 0 ) {
603             dred_duration = atoi( argv[ args + 1 ] );
604             args += 2;
605         } else if( strcmp( argv[ args ], "-sweep" ) == 0 ) {
606             check_encoder_option(decode_only, "-sweep");
607             sweep_bps = atoi( argv[ args + 1 ] );
608             args += 2;
609         } else if( strcmp( argv[ args ], "-random_framesize" ) == 0 ) {
610             check_encoder_option(decode_only, "-random_framesize");
611             random_framesize = 1;
612             args++;
613         } else if( strcmp( argv[ args ], "-sweep_max" ) == 0 ) {
614             check_encoder_option(decode_only, "-sweep_max");
615             sweep_max = atoi( argv[ args + 1 ] );
616             args += 2;
617         } else if( strcmp( argv[ args ], "-random_fec" ) == 0 ) {
618             check_encoder_option(decode_only, "-random_fec");
619             random_fec = 1;
620             args++;
621         } else if( strcmp( argv[ args ], "-silk8k_test" ) == 0 ) {
622             check_encoder_option(decode_only, "-silk8k_test");
623             mode_list = silk8_test;
624             nb_modes_in_list = 8;
625             args++;
626         } else if( strcmp( argv[ args ], "-silk12k_test" ) == 0 ) {
627             check_encoder_option(decode_only, "-silk12k_test");
628             mode_list = silk12_test;
629             nb_modes_in_list = 8;
630             args++;
631         } else if( strcmp( argv[ args ], "-silk16k_test" ) == 0 ) {
632             check_encoder_option(decode_only, "-silk16k_test");
633             mode_list = silk16_test;
634             nb_modes_in_list = 8;
635             args++;
636         } else if( strcmp( argv[ args ], "-hybrid24k_test" ) == 0 ) {
637             check_encoder_option(decode_only, "-hybrid24k_test");
638             mode_list = hybrid24_test;
639             nb_modes_in_list = 4;
640             args++;
641         } else if( strcmp( argv[ args ], "-hybrid48k_test" ) == 0 ) {
642             check_encoder_option(decode_only, "-hybrid48k_test");
643             mode_list = hybrid48_test;
644             nb_modes_in_list = 4;
645             args++;
646         } else if( strcmp( argv[ args ], "-celt_test" ) == 0 ) {
647             check_encoder_option(decode_only, "-celt_test");
648             mode_list = celt_test;
649             nb_modes_in_list = 32;
650             args++;
651         } else if( strcmp( argv[ args ], "-celt_hq_test" ) == 0 ) {
652             check_encoder_option(decode_only, "-celt_hq_test");
653             mode_list = celt_hq_test;
654             nb_modes_in_list = 4;
655             args++;
656 #ifdef ENABLE_OSCE_TRAINING_DATA
657         } else if( strcmp( argv[ args ], "-silk_random_switching" ) == 0 ){
658             silk_random_switching = atoi( argv[ args + 1 ] );
659             printf("switching encoding parameters every %dth frame\n", silk_random_switching);
660             args += 2;
661 #endif
662         } else {
663             printf( "Error: unrecognized setting: %s\n\n", argv[ args ] );
664             print_usage( argv );
665             goto failure;
666         }
667     }
668 
669     if (sweep_max)
670        sweep_min = bitrate_bps;
671 
672     if (max_payload_bytes < 0 || max_payload_bytes > MAX_PACKET)
673     {
674         fprintf (stderr, "max_payload_bytes must be between 0 and %d\n",
675                           MAX_PACKET);
676         goto failure;
677     }
678 
679     inFile = argv[argc-2];
680     fin = fopen(inFile, "rb");
681     if (!fin)
682     {
683         fprintf (stderr, "Could not open input file %s\n", argv[argc-2]);
684         goto failure;
685     }
686     if (mode_list)
687     {
688        int size;
689        fseek(fin, 0, SEEK_END);
690        size = ftell(fin);
691        fprintf(stderr, "File size is %d bytes\n", size);
692        fseek(fin, 0, SEEK_SET);
693        mode_switch_time = size/sizeof(short)/channels/nb_modes_in_list;
694        fprintf(stderr, "Switching mode every %d samples\n", mode_switch_time);
695     }
696 
697     outFile = argv[argc-1];
698     fout = fopen(outFile, "wb+");
699     if (!fout)
700     {
701         fprintf (stderr, "Could not open output file %s\n", argv[argc-1]);
702         goto failure;
703     }
704 
705     if (!decode_only)
706     {
707        enc = opus_encoder_create(sampling_rate, channels, application, &err);
708        if (err != OPUS_OK)
709        {
710           fprintf(stderr, "Cannot create encoder: %s\n", opus_strerror(err));
711           goto failure;
712        }
713        opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate_bps));
714        opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(bandwidth));
715        opus_encoder_ctl(enc, OPUS_SET_VBR(use_vbr));
716        opus_encoder_ctl(enc, OPUS_SET_VBR_CONSTRAINT(cvbr));
717        opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(complexity));
718        opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(use_inbandfec));
719        opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(forcechannels));
720        opus_encoder_ctl(enc, OPUS_SET_DTX(use_dtx));
721        opus_encoder_ctl(enc, OPUS_SET_PACKET_LOSS_PERC(packet_loss_perc));
722 
723        opus_encoder_ctl(enc, OPUS_GET_LOOKAHEAD(&skip));
724        opus_encoder_ctl(enc, OPUS_SET_LSB_DEPTH(16));
725        opus_encoder_ctl(enc, OPUS_SET_EXPERT_FRAME_DURATION(variable_duration));
726        if (dred_duration > 0)
727        {
728           opus_encoder_ctl(enc, OPUS_SET_DRED_DURATION(dred_duration));
729        }
730     }
731     if (!encode_only)
732     {
733        dec = opus_decoder_create(sampling_rate, channels, &err);
734        if (err != OPUS_OK)
735        {
736           fprintf(stderr, "Cannot create decoder: %s\n", opus_strerror(err));
737           goto failure;
738        }
739        opus_decoder_ctl(dec, OPUS_SET_COMPLEXITY(dec_complexity));
740     }
741     switch(bandwidth)
742     {
743     case OPUS_BANDWIDTH_NARROWBAND:
744          bandwidth_string = "narrowband";
745          break;
746     case OPUS_BANDWIDTH_MEDIUMBAND:
747          bandwidth_string = "mediumband";
748          break;
749     case OPUS_BANDWIDTH_WIDEBAND:
750          bandwidth_string = "wideband";
751          break;
752     case OPUS_BANDWIDTH_SUPERWIDEBAND:
753          bandwidth_string = "superwideband";
754          break;
755     case OPUS_BANDWIDTH_FULLBAND:
756          bandwidth_string = "fullband";
757          break;
758     case OPUS_AUTO:
759          bandwidth_string = "auto bandwidth";
760          break;
761     default:
762          bandwidth_string = "unknown";
763          break;
764     }
765 
766     if (decode_only)
767        fprintf(stderr, "Decoding with %ld Hz output (%d channels)\n",
768                        (long)sampling_rate, channels);
769     else
770        fprintf(stderr, "Encoding %ld Hz input at %.3f kb/s "
771                        "in %s with %d-sample frames.\n",
772                        (long)sampling_rate, bitrate_bps*0.001,
773                        bandwidth_string, frame_size);
774 
775     in = (short*)malloc(max_frame_size*channels*sizeof(short));
776     out = (short*)malloc(max_frame_size*channels*sizeof(short));
777     /* We need to allocate for 16-bit PCM data, but we store it as unsigned char. */
778     fbytes = (unsigned char*)malloc(max_frame_size*channels*sizeof(short));
779     data = (unsigned char*)calloc(max_payload_bytes,sizeof(unsigned char));
780     if(delayed_decision)
781     {
782        if (frame_size==sampling_rate/400)
783           variable_duration = OPUS_FRAMESIZE_2_5_MS;
784        else if (frame_size==sampling_rate/200)
785           variable_duration = OPUS_FRAMESIZE_5_MS;
786        else if (frame_size==sampling_rate/100)
787           variable_duration = OPUS_FRAMESIZE_10_MS;
788        else if (frame_size==sampling_rate/50)
789           variable_duration = OPUS_FRAMESIZE_20_MS;
790        else if (frame_size==sampling_rate/25)
791           variable_duration = OPUS_FRAMESIZE_40_MS;
792        else if (frame_size==3*sampling_rate/50)
793           variable_duration = OPUS_FRAMESIZE_60_MS;
794        else if (frame_size==4*sampling_rate/50)
795           variable_duration = OPUS_FRAMESIZE_80_MS;
796        else if (frame_size==5*sampling_rate/50)
797           variable_duration = OPUS_FRAMESIZE_100_MS;
798        else
799           variable_duration = OPUS_FRAMESIZE_120_MS;
800        opus_encoder_ctl(enc, OPUS_SET_EXPERT_FRAME_DURATION(variable_duration));
801        frame_size = 2*48000;
802     }
803     dred_dec = opus_dred_decoder_create(&err);
804     dred = opus_dred_alloc(&err);
805 #ifdef USE_WEIGHTS_FILE
806     if (enc) opus_encoder_ctl(enc, OPUS_SET_DNN_BLOB(blob_data, blob_len));
807     if (dec) opus_decoder_ctl(dec, OPUS_SET_DNN_BLOB(blob_data, blob_len));
808     if (dred_dec) opus_dred_decoder_ctl(dred_dec, OPUS_SET_DNN_BLOB(blob_data, blob_len));
809 #endif
810     while (!stop)
811     {
812         if (delayed_celt)
813         {
814             frame_size = newsize;
815             delayed_celt = 0;
816         } else if (random_framesize && rand()%20==0)
817         {
818             newsize = rand()%6;
819             switch(newsize)
820             {
821             case 0: newsize=sampling_rate/400; break;
822             case 1: newsize=sampling_rate/200; break;
823             case 2: newsize=sampling_rate/100; break;
824             case 3: newsize=sampling_rate/50; break;
825             case 4: newsize=sampling_rate/25; break;
826             case 5: newsize=3*sampling_rate/50; break;
827             }
828             while (newsize < sampling_rate/25 && bitrate_bps-abs(sweep_bps) <= 3*12*sampling_rate/newsize)
829                newsize*=2;
830             if (newsize < sampling_rate/100 && frame_size >= sampling_rate/100)
831             {
832                 opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY));
833                 delayed_celt=1;
834             } else {
835                 frame_size = newsize;
836             }
837         }
838         if (random_fec && rand()%30==0)
839         {
840            opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(rand()%4==0));
841         }
842         if (decode_only)
843         {
844             unsigned char ch[4];
845             num_read = fread(ch, 1, 4, fin);
846             if (num_read!=4)
847                 break;
848             len = char_to_int(ch);
849             if (len>max_payload_bytes || len<0)
850             {
851                 fprintf(stderr, "Invalid payload length: %d\n",len);
852                 break;
853             }
854             num_read = fread(ch, 1, 4, fin);
855             if (num_read!=4)
856                 break;
857             enc_final_range = char_to_int(ch);
858             num_read = fread(data, 1, len, fin);
859             if (num_read!=(size_t)len)
860             {
861                 fprintf(stderr, "Ran out of input, "
862                                 "expecting %d bytes got %d\n",
863                                 len,(int)num_read);
864                 break;
865             }
866         } else {
867             int i;
868             if (mode_list!=NULL)
869             {
870                 opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(mode_list[curr_mode][1]));
871                 opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(mode_list[curr_mode][0]));
872                 opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(mode_list[curr_mode][3]));
873                 frame_size = mode_list[curr_mode][2];
874             }
875 #ifdef ENABLE_OSCE_TRAINING_DATA
876             if (silk_random_switching)
877             {
878                 silk_frame_counter += 1;
879                 if (silk_frame_counter % silk_random_switching == 0) {
880                     new_random_setting(enc);
881                 }
882             }
883 #endif
884             num_read = fread(fbytes, sizeof(short)*channels, frame_size-remaining, fin);
885             curr_read = (int)num_read;
886             tot_in += curr_read;
887             for(i=0;i<curr_read*channels;i++)
888             {
889                 opus_int32 s;
890                 s=fbytes[2*i+1]<<8|fbytes[2*i];
891                 s=((s&0xFFFF)^0x8000)-0x8000;
892                 in[i+remaining*channels]=s;
893             }
894             if (curr_read+remaining < frame_size)
895             {
896                 for (i=(curr_read+remaining)*channels;i<frame_size*channels;i++)
897                    in[i] = 0;
898                 if (encode_only || decode_only)
899                    stop = 1;
900             }
901             len = opus_encode(enc, in, frame_size, data, max_payload_bytes);
902             if (len < 0)
903             {
904                 fprintf (stderr, "opus_encode() returned %d\n", len);
905                 goto failure;
906             }
907             nb_encoded = opus_packet_get_samples_per_frame(data, sampling_rate)*opus_packet_get_nb_frames(data, len);
908             remaining = frame_size-nb_encoded;
909             for(i=0;i<remaining*channels;i++)
910                in[i] = in[nb_encoded*channels+i];
911             if (sweep_bps!=0)
912             {
913                bitrate_bps += sweep_bps;
914                if (sweep_max)
915                {
916                   if (bitrate_bps > sweep_max)
917                      sweep_bps = -sweep_bps;
918                   else if (bitrate_bps < sweep_min)
919                      sweep_bps = -sweep_bps;
920                }
921                /* safety */
922                if (bitrate_bps<1000)
923                   bitrate_bps = 1000;
924                opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate_bps));
925             }
926             opus_encoder_ctl(enc, OPUS_GET_FINAL_RANGE(&enc_final_range));
927             curr_mode_count += frame_size;
928             if (curr_mode_count > mode_switch_time && curr_mode < nb_modes_in_list-1)
929             {
930                curr_mode++;
931                curr_mode_count = 0;
932             }
933         }
934 
935 #if 0 /* This is for testing the padding code, do not enable by default */
936         if (len<1275)
937         {
938            int new_len = len+rand()%(max_payload_bytes-len);
939            if ((err = opus_packet_pad(data, len, new_len)) != OPUS_OK)
940            {
941               fprintf(stderr, "padding failed: %s\n", opus_strerror(err));
942               goto failure;
943            }
944            len = new_len;
945         }
946 #endif
947         if (encode_only)
948         {
949             unsigned char int_field[4];
950             int_to_char(len, int_field);
951             if (fwrite(int_field, 1, 4, fout) != 4) {
952                fprintf(stderr, "Error writing.\n");
953                goto failure;
954             }
955             int_to_char(enc_final_range, int_field);
956             if (fwrite(int_field, 1, 4, fout) != 4) {
957                fprintf(stderr, "Error writing.\n");
958                goto failure;
959             }
960             if (fwrite(data, 1, len, fout) != (unsigned)len) {
961                fprintf(stderr, "Error writing.\n");
962                goto failure;
963             }
964             tot_samples += nb_encoded;
965         } else {
966             int fr;
967             int run_decoder;
968             int dred_input=0;
969             int dred_end=0;
970             if (packet_loss_file != NULL) {
971                 if ( fscanf(packet_loss_file, "%d", &lost) != 1) {
972                     lost = 0;
973                 }
974 #ifdef ENABLE_LOSSGEN
975             } else if (lossgen_perc >= 0) {
976                lost = sample_loss(&lossgen, lossgen_perc*.01f);
977 #endif
978             } else {
979               lost = (packet_loss_perc>0) && (rand()%100 < packet_loss_perc);
980             }
981             if (len == 0) lost = 1;
982             if (lost)
983             {
984                lost_count++;
985                run_decoder = 0;
986             } else {
987                run_decoder= 1;
988             }
989             if (run_decoder)
990                 run_decoder += lost_count;
991             if (!lost && lost_count > 0) {
992                 opus_int32 output_samples=0;
993                 opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION(&output_samples));
994                 dred_input = lost_count*output_samples;
995                 /* Only decode the amount we need to fill in the gap. */
996                 ret = opus_dred_parse(dred_dec, dred, data, len, IMIN(48000, IMAX(0, dred_input)), sampling_rate, &dred_end, 0);
997                 dred_input = ret > 0 ? ret : 0;
998             }
999             /* FIXME: Figure out how to trigger the decoder when the last packet of the file is lost. */
1000             for (fr=0;fr<run_decoder;fr++) {
1001                 opus_int32 output_samples=0;
1002                 if (fr == lost_count-1 && opus_packet_has_lbrr(data, len)) {
1003                    opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION(&output_samples));
1004                    output_samples = opus_decode(dec, data, len, out, output_samples, 1);
1005                 } else if (fr < lost_count) {
1006                    opus_decoder_ctl(dec, OPUS_GET_LAST_PACKET_DURATION(&output_samples));
1007                    if (dred_input > 0)
1008                       output_samples = opus_decoder_dred_decode(dec, dred, (lost_count-fr)*output_samples, out, output_samples);
1009                    else
1010                       output_samples = opus_decode(dec, NULL, 0, out, output_samples, 0);
1011                 } else {
1012                    output_samples = max_frame_size;
1013                    output_samples = opus_decode(dec, data, len, out, output_samples, 0);
1014                 }
1015                 if (output_samples>0)
1016                 {
1017                     if (!decode_only && tot_out + output_samples > tot_in)
1018                     {
1019                        stop=1;
1020                        output_samples = (opus_int32)(tot_in - tot_out);
1021                     }
1022                     if (output_samples>skip) {
1023                        int i;
1024                        for(i=0;i<(output_samples-skip)*channels;i++)
1025                        {
1026                           short s;
1027                           s=out[i+(skip*channels)];
1028                           fbytes[2*i]=s&0xFF;
1029                           fbytes[2*i+1]=(s>>8)&0xFF;
1030                        }
1031                        if (fwrite(fbytes, sizeof(short)*channels, output_samples-skip, fout) != (unsigned)(output_samples-skip)){
1032                           fprintf(stderr, "Error writing.\n");
1033                           goto failure;
1034                        }
1035                        tot_out += output_samples-skip;
1036                     }
1037                     if (output_samples<skip) skip -= output_samples;
1038                     else skip = 0;
1039                 } else {
1040                    fprintf(stderr, "error decoding frame: %s\n",
1041                                    opus_strerror(output_samples));
1042                 }
1043                 tot_samples += output_samples;
1044             }
1045         }
1046 
1047         if (!encode_only)
1048            opus_decoder_ctl(dec, OPUS_GET_FINAL_RANGE(&dec_final_range));
1049         /* compare final range encoder rng values of encoder and decoder */
1050         if( enc_final_range!=0  && !encode_only
1051          && !lost && !lost_prev
1052          && dec_final_range != enc_final_range ) {
1053             fprintf (stderr, "Error: Range coder state mismatch "
1054                              "between encoder and decoder "
1055                              "in frame %ld: 0x%8lx vs 0x%8lx\n",
1056                          (long)count,
1057                          (unsigned long)enc_final_range,
1058                          (unsigned long)dec_final_range);
1059             goto failure;
1060         }
1061 
1062         lost_prev = lost;
1063         if (!lost)
1064            lost_count = 0;
1065         if( count >= use_inbandfec ) {
1066             /* count bits */
1067             bits += len*8;
1068             bits_max = ( len*8 > bits_max ) ? len*8 : bits_max;
1069             bits2 += len*len*64;
1070             if (!decode_only)
1071             {
1072                 nrg = 0.0;
1073                 for ( k = 0; k < frame_size * channels; k++ ) {
1074                     nrg += in[ k ] * (double)in[ k ];
1075                 }
1076                 nrg /= frame_size * channels;
1077                 if( nrg > 1e5 ) {
1078                     bits_act += len*8;
1079                     count_act++;
1080                 }
1081             }
1082         }
1083         count++;
1084     }
1085 
1086     if(decode_only && count > 0)
1087         frame_size = (int)(tot_samples / count);
1088     count -= use_inbandfec;
1089     if (tot_samples >= 1 && count > 0 && frame_size)
1090     {
1091        /* Print out bitrate statistics */
1092        double var;
1093        fprintf (stderr, "average bitrate:             %7.3f kb/s\n",
1094                         1e-3*bits*sampling_rate/tot_samples);
1095        fprintf (stderr, "maximum bitrate:             %7.3f kb/s\n",
1096                         1e-3*bits_max*sampling_rate/frame_size);
1097        if (!decode_only)
1098           fprintf (stderr, "active bitrate:              %7.3f kb/s\n",
1099                            1e-3*bits_act*sampling_rate/(1e-15+frame_size*(double)count_act));
1100        var = bits2/count - bits*bits/(count*(double)count);
1101        if (var < 0)
1102           var = 0;
1103        fprintf (stderr, "bitrate standard deviation:  %7.3f kb/s\n",
1104                         1e-3*sqrt(var)*sampling_rate/frame_size);
1105     } else {
1106        fprintf(stderr, "bitrate statistics are undefined\n");
1107     }
1108     silk_TimerSave("opus_timing.txt");
1109     ret = EXIT_SUCCESS;
1110 failure:
1111     opus_encoder_destroy(enc);
1112     opus_decoder_destroy(dec);
1113     opus_dred_free(dred);
1114     opus_dred_decoder_destroy(dred_dec);
1115     free(data);
1116     if (fin)
1117         fclose(fin);
1118     if (fout)
1119         fclose(fout);
1120     free(in);
1121     free(out);
1122     free(fbytes);
1123 #ifdef USE_WEIGHTS_FILE
1124     free_blob(blob_data, blob_len);
1125 #endif
1126     return ret;
1127 }
1128