travis-ci: Fix CI on macOS
[opus-tools.git] / src / opusenc.c
1 /* Copyright (C)2002-2011 Jean-Marc Valin
2    Copyright (C)2007-2013 Xiph.Org Foundation
3    Copyright (C)2008-2013 Gregory Maxwell
4    File: opusenc.c
5
6    Redistribution and use in source and binary forms, with or without
7    modification, are permitted provided that the following conditions
8    are met:
9
10    - Redistributions of source code must retain the above copyright
11    notice, this list of conditions and the following disclaimer.
12
13    - Redistributions in binary form must reproduce the above copyright
14    notice, this list of conditions and the following disclaimer in the
15    documentation and/or other materials provided with the distribution.
16
17    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18    ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20    A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
21    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <stdio.h>
35 #include <getopt.h>
36
37 #include <stdlib.h>
38 #include <string.h>
39 #if (!defined WIN32 && !defined _WIN32) || defined(__MINGW32__)
40 #include <unistd.h>
41 #include <time.h>
42 #endif
43 #include <math.h>
44
45 #ifdef _MSC_VER
46 #define snprintf _snprintf
47 #endif
48
49 #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
50 # include "unicode_support.h"
51 /* We need the following two to set stdout to binary */
52 # include <io.h>
53 # include <fcntl.h>
54 # define I64FORMAT "I64d"
55 #else
56 # define I64FORMAT "lld"
57 # define fopen_utf8(_x,_y) fopen((_x),(_y))
58 # define argc_utf8 argc
59 # define argv_utf8 argv
60 #endif
61
62 #include <opus.h>
63 #include <opus_multistream.h>
64 #include <ogg/ogg.h>
65 #include "wav_io.h"
66
67 #include "picture.h"
68 #include "opus_header.h"
69 #include "opusenc.h"
70 #include "diag_range.h"
71 #include "cpusupport.h"
72
73 #ifdef VALGRIND
74 #include <valgrind/memcheck.h>
75 #define VG_UNDEF(x,y) VALGRIND_MAKE_MEM_UNDEFINED((x),(y))
76 #define VG_CHECK(x,y) VALGRIND_CHECK_MEM_IS_DEFINED((x),(y))
77 #else
78 #define VG_UNDEF(x,y)
79 #define VG_CHECK(x,y)
80 #endif
81
82 static void comment_init(char **comments, int* length, const char *vendor_string);
83 static void comment_pad(char **comments, int* length, int amount);
84
85 /*Write an Ogg page to a file pointer*/
86 static inline int oe_write_page(ogg_page *page, FILE *fp)
87 {
88    int written;
89    written=fwrite(page->header,1,page->header_len, fp);
90    written+=fwrite(page->body,1,page->body_len, fp);
91    return written;
92 }
93
94 #define MAX_FRAME_BYTES 61295
95 #define IMIN(a,b) ((a) < (b) ? (a) : (b))   /**< Minimum int value.   */
96 #define IMAX(a,b) ((a) > (b) ? (a) : (b))   /**< Maximum int value.   */
97
98 void opustoolsversion(const char *opusversion)
99 {
100   printf("opusenc %s %s (using %s)\n",PACKAGE_NAME,PACKAGE_VERSION,opusversion);
101   printf("Copyright (C) 2008-2013 Xiph.Org Foundation\n");
102 }
103
104 void opustoolsversion_short(const char *opusversion)
105 {
106   opustoolsversion(opusversion);
107 }
108
109 void usage(void)
110 {
111   printf("Usage: opusenc [options] input_file output_file.opus\n");
112   printf("\n");
113   printf("Encodes input_file using Opus.\n");
114 #if defined(HAVE_LIBFLAC)
115   printf("It can read the WAV, AIFF, FLAC, Ogg/FLAC, or raw files.\n");
116 #else
117   printf("It can read the WAV, AIFF, or raw files.\n");
118 #endif
119   printf("\nGeneral options:\n");
120   printf(" -h, --help         This help\n");
121   printf(" -V, --version      Version information\n");
122   printf(" --quiet            Quiet mode\n");
123   printf("\n");
124   printf("input_file can be:\n");
125   printf("  filename.wav      file\n");
126   printf("  -                 stdin\n");
127   printf("\n");
128   printf("output_file can be:\n");
129   printf("  filename.opus     compressed file\n");
130   printf("  -                 stdout\n");
131   printf("\nEncoding options:\n");
132   printf(" --bitrate n.nnn    Target bitrate in kbit/sec (6-256/channel)\n");
133   printf(" --vbr              Use variable bitrate encoding (default)\n");
134   printf(" --cvbr             Use constrained variable bitrate encoding\n");
135   printf(" --hard-cbr         Use hard constant bitrate encoding\n");
136   printf(" --comp n           Encoding complexity (0-10, default: 10 (slowest))\n");
137   printf(" --framesize n      Maximum frame size in milliseconds\n");
138   printf("                      (2.5, 5, 10, 20, 40, 60, default: 20)\n");
139   printf(" --expect-loss      Percentage packet loss to expect (default: 0)\n");
140   printf(" --downmix-mono     Downmix to mono\n");
141   printf(" --downmix-stereo   Downmix to stereo (if >2 channels)\n");
142   printf(" --max-delay n      Maximum container delay in milliseconds\n");
143   printf("                      (0-1000, default: 1000)\n");
144   printf("\nDiagnostic options:\n");
145   printf(" --serial n         Forces a specific stream serial number\n");
146   printf(" --save-range file  Saves check values for every frame to a file\n");
147   printf(" --set-ctl-int x=y  Pass the encoder control x with value y (advanced)\n");
148   printf("                      Preface with s: to direct the ctl to multistream s\n");
149   printf("                      This may be used multiple times\n");
150   printf("\nMetadata options:\n");
151   printf(" --comment          Add the given string as an extra comment\n");
152   printf("                      This may be used multiple times\n");
153   printf(" --artist           Author of this track\n");
154   printf(" --title            Title for this track\n");
155   printf(" --album            Album or collection this track belongs to\n");
156   printf(" --date             Date for this track\n");
157   printf(" --genre            Genre for this track\n");
158   printf(" --picture          Album art for this track\n");
159   printf("                      More than one --picture option can be specified.\n");
160   printf("                      Either a FILENAME for the picture file or a more\n");
161   printf("                      complete SPECIFICATION form can be used. The\n");
162   printf("                      SPECIFICATION is a string whose parts are\n");
163   printf("                      separated by | (pipe) characters. Some parts may\n");
164   printf("                      be left empty to invoke default values. A\n");
165   printf("                      FILENAME is just shorthand for \"||||FILENAME\".\n");
166   printf("                      The format of SPECIFICATION is\n");
167   printf("\n");
168   printf("                      [TYPE]|[MIME-TYPE]|[DESCRIPTION]|[WIDTHxHEIGHT\n");
169   printf("                      xDEPTH[/COLORS]]|FILENAME\n");
170   printf("\n");
171   printf("                      TYPE is an optional number from one of:\n");
172   printf("                      0: Other\n");
173   printf("                      1: 32x32 pixel 'file icon' (PNG only)\n");
174   printf("                      2: Other file icon\n");
175   printf("                      3: Cover (front)\n");
176   printf("                      4: Cover (back)\n");
177   printf("                      5: Leaflet page\n");
178   printf("                      6: Media (e.g., label side of a CD)\n");
179   printf("                      7: Lead artist/lead performer/soloist\n");
180   printf("                      8: Artist/performer\n");
181   printf("                      9: Conductor\n");
182   printf("                      10: Band/Orchestra\n");
183   printf("                      11: Composer\n");
184   printf("                      12: Lyricist/text writer\n");
185   printf("                      13: Recording location\n");
186   printf("                      14: During recording\n");
187   printf("                      15: During performance\n");
188   printf("                      16: Movie/video screen capture\n");
189   printf("                      17: A bright colored fish\n");
190   printf("                      18: Illustration\n");
191   printf("                      19: Band/artist logotype\n");
192   printf("                      20: Publisher/studio logotype\n");
193   printf("\n");
194   printf("                      The default is 3 (front cover). There may only be\n");
195   printf("                      one picture each of type 1 and 2 in a file.\n");
196   printf("\n");
197   printf("                      MIME-TYPE is optional. If left blank, it will be\n");
198   printf("                      detected from the file. For best compatibility\n");
199   printf("                      with players, use pictures with a MIME-TYPE of\n");
200   printf("                      image/jpeg or image/png. The MIME-TYPE can also\n");
201   printf("                      be --> to mean that FILENAME is actually a URL to\n");
202   printf("                      an image, though this use is discouraged. The\n");
203   printf("                      file at the URL will not be fetched. The URL\n");
204   printf("                      itself is stored in the metadata.\n");
205   printf("\n");
206   printf("                      DESCRIPTION is optional. The default is an empty\n");
207   printf("                      string.\n");
208   printf("\n");
209   printf("                      The next part specifies the resolution and color\n");
210   printf("                      information. If the MIME-TYPE is image/jpeg,\n");
211   printf("                      image/png, or image/gif, you can usually leave\n");
212   printf("                      this empty and they can be detected from the\n");
213   printf("                      file. Otherwise, you must specify the width in\n");
214   printf("                      pixels, height in pixels, and color depth in\n");
215   printf("                      bits-per-pixel. If the image has indexed colors\n");
216   printf("                      you should also specify the number of colors\n");
217   printf("                      used. If possible, these are checked against the\n");
218   printf("                      file for accuracy.\n");
219   printf("\n");
220   printf("                      FILENAME is the path to the picture file to be\n");
221   printf("                      imported, or the URL if the MIME-TYPE is -->.\n");
222   printf(" --padding n        Extra bytes to reserve for metadata (default: 512)\n");
223   printf(" --discard-comments Don't keep metadata when transcoding\n");
224   printf(" --discard-pictures Don't keep pictures when transcoding\n");
225   printf("\nInput options:\n");
226   printf(" --raw              Raw input\n");
227   printf(" --raw-bits n       Set bits/sample for raw input (default: 16)\n");
228   printf(" --raw-rate n       Set sampling rate for raw input (default: 48000)\n");
229   printf(" --raw-chan n       Set number of channels for raw input (default: 2)\n");
230   printf(" --raw-endianness n 1 for bigendian, 0 for little (defaults to 0)\n");
231   printf(" --ignorelength     Always ignore the datalength in Wave headers\n");
232 }
233
234 static inline void print_time(double seconds)
235 {
236   opus_int64 hours, minutes;
237   hours=seconds/3600;
238   seconds-=hours*3600.;
239   minutes=seconds/60;
240   seconds-=minutes*60.;
241   if(hours)fprintf(stderr," %" I64FORMAT " hour%s%s",hours,hours>1?"s":"",
242                    minutes&&!(seconds>0)?" and":"");
243   if(minutes)fprintf(stderr,"%s%" I64FORMAT " minute%s%s",hours?", ":" ",minutes,
244                      minutes>1?"s":"",!hours&&seconds>0?" and":seconds>0?", and":"");
245   if(seconds>0)fprintf(stderr," %0.4g second%s",seconds,seconds!=1?"s":"");
246 }
247
248 int main(int argc, char **argv)
249 {
250   static const input_format raw_format = {NULL, 0, raw_open, wav_close, "raw",N_("RAW file reader")};
251   int option_index=0;
252   struct option long_options[] =
253   {
254     {"quiet", no_argument, NULL, 0},
255     {"bitrate", required_argument, NULL, 0},
256     {"hard-cbr",no_argument,NULL, 0},
257     {"vbr",no_argument,NULL, 0},
258     {"cvbr",no_argument,NULL, 0},
259     {"comp", required_argument, NULL, 0},
260     {"complexity", required_argument, NULL, 0},
261     {"framesize", required_argument, NULL, 0},
262     {"expect-loss", required_argument, NULL, 0},
263     {"downmix-mono",no_argument,NULL, 0},
264     {"downmix-stereo",no_argument,NULL, 0},
265     {"no-downmix",no_argument,NULL, 0},
266     {"max-delay", required_argument, NULL, 0},
267     {"serial", required_argument, NULL, 0},
268     {"save-range", required_argument, NULL, 0},
269     {"set-ctl-int", required_argument, NULL, 0},
270     {"help", no_argument, NULL, 0},
271     {"raw", no_argument, NULL, 0},
272     {"raw-bits", required_argument, NULL, 0},
273     {"raw-rate", required_argument, NULL, 0},
274     {"raw-chan", required_argument, NULL, 0},
275     {"raw-endianness", required_argument, NULL, 0},
276     {"ignorelength", no_argument, NULL, 0},
277     {"rate", required_argument, NULL, 0},
278     {"version", no_argument, NULL, 0},
279     {"version-short", no_argument, NULL, 0},
280     {"comment", required_argument, NULL, 0},
281     {"artist", required_argument, NULL, 0},
282     {"title", required_argument, NULL, 0},
283     {"album", required_argument, NULL, 0},
284     {"date", required_argument, NULL, 0},
285     {"genre", required_argument, NULL, 0},
286     {"picture", required_argument, NULL, 0},
287     {"padding", required_argument, NULL, 0},
288     {"discard-comments", no_argument, NULL, 0},
289     {"discard-pictures", no_argument, NULL, 0},
290     {0, 0, 0, 0}
291   };
292   int i, ret;
293   int                cline_size;
294   OpusMSEncoder      *st;
295   const char         *opus_version;
296   unsigned char      *packet;
297   float              *input;
298   /*I/O*/
299   oe_enc_opt         inopt;
300   const input_format *in_format;
301   char               *inFile;
302   char               *outFile;
303   char               *range_file;
304   FILE               *fin;
305   FILE               *fout;
306   FILE               *frange;
307   ogg_stream_state   os;
308   ogg_page           og;
309   ogg_packet         op;
310   ogg_int64_t        last_granulepos=0;
311   ogg_int64_t        enc_granulepos=0;
312   ogg_int64_t        original_samples=0;
313   ogg_int32_t        id=-1;
314   int                last_segments=0;
315   int                eos=0;
316   OpusHeader         header;
317   char               ENCODER_string[1024];
318   /*Counters*/
319   opus_int64         nb_encoded=0;
320   opus_int64         bytes_written=0;
321   opus_int64         pages_out=0;
322   opus_int64         total_bytes=0;
323   opus_int64         total_samples=0;
324   opus_int32         nbBytes;
325   opus_int32         nb_samples;
326   opus_int32         peak_bytes=0;
327   opus_int32         min_bytes;
328   time_t             start_time;
329   time_t             stop_time;
330   time_t             last_spin=0;
331   int                last_spin_len=0;
332   /*Settings*/
333   int                quiet=0;
334   int                max_frame_bytes;
335   opus_int32         bitrate=-1;
336   opus_int32         rate=48000;
337   opus_int32         coding_rate=48000;
338   opus_int32         frame_size=960;
339   int                chan=2;
340   int                with_hard_cbr=0;
341   int                with_cvbr=0;
342   int                expect_loss=0;
343   int                complexity=10;
344   int                downmix=0;
345   int                *opt_ctls_ctlval;
346   int                opt_ctls=0;
347   int                max_ogg_delay=48000; /*48kHz samples*/
348   int                seen_file_icons=0;
349   int                comment_padding=512;
350   int                serialno;
351   opus_int32         lookahead=0;
352 #ifdef WIN_UNICODE
353    int argc_utf8;
354    char **argv_utf8;
355 #endif
356
357    if(query_cpu_support()){
358      fprintf(stderr,"\n\n** WARNING: This program was compiled with SSE%s\n",query_cpu_support()>1?"2":"");
359      fprintf(stderr,"            but this CPU claims to lack these instructions. **\n\n");
360    }
361
362 #ifdef WIN_UNICODE
363    (void)argc;
364    (void)argv;
365
366    init_commandline_arguments_utf8(&argc_utf8, &argv_utf8);
367 #endif
368
369   opt_ctls_ctlval=NULL;
370   frange=NULL;
371   range_file=NULL;
372   in_format=NULL;
373   inopt.channels=chan;
374   inopt.rate=coding_rate=rate;
375   /* 0 dB gain is recommended unless you know what you're doing */
376   inopt.gain=0;
377   inopt.samplesize=16;
378   inopt.endianness=0;
379   inopt.rawmode=0;
380   inopt.ignorelength=0;
381   inopt.copy_comments=1;
382   inopt.copy_pictures=1;
383
384   start_time = time(NULL);
385   srand(((getpid()&65535)<<15)^start_time);
386   serialno=rand();
387
388   opus_version=opus_get_version_string();
389   /*Vendor string should just be the encoder library,
390     the ENCODER comment specifies the tool used.*/
391   comment_init(&inopt.comments, &inopt.comments_length, opus_version);
392   snprintf(ENCODER_string, sizeof(ENCODER_string), "opusenc from %s %s",PACKAGE_NAME,PACKAGE_VERSION);
393   comment_add(&inopt.comments, &inopt.comments_length, "ENCODER", ENCODER_string);
394
395   /*Process command-line options*/
396   cline_size=0;
397   while(1){
398     int c;
399     int save_cmd=1;
400     c=getopt_long(argc_utf8, argv_utf8, "hV",
401                   long_options, &option_index);
402     if(c==-1)
403        break;
404
405     switch(c){
406       case 0:
407         if(strcmp(long_options[option_index].name,"quiet")==0){
408           quiet=1;
409         }else if(strcmp(long_options[option_index].name,"bitrate")==0){
410           bitrate=atof(optarg)*1000.;
411         }else if(strcmp(long_options[option_index].name,"hard-cbr")==0){
412           with_hard_cbr=1;
413           with_cvbr=0;
414         }else if(strcmp(long_options[option_index].name,"cvbr")==0){
415           with_cvbr=1;
416           with_hard_cbr=0;
417         }else if(strcmp(long_options[option_index].name,"vbr")==0){
418           with_cvbr=0;
419           with_hard_cbr=0;
420         }else if(strcmp(long_options[option_index].name,"help")==0){
421           usage();
422           exit(0);
423         }else if(strcmp(long_options[option_index].name,"version")==0){
424           opustoolsversion(opus_version);
425           exit(0);
426         }else if(strcmp(long_options[option_index].name,"version-short")==0){
427           opustoolsversion_short(opus_version);
428           exit(0);
429         }else if(strcmp(long_options[option_index].name,"ignorelength")==0){
430           inopt.ignorelength=1;
431         }else if(strcmp(long_options[option_index].name,"raw")==0){
432           inopt.rawmode=1;
433           save_cmd=0;
434         }else if(strcmp(long_options[option_index].name,"raw-bits")==0){
435           inopt.rawmode=1;
436           inopt.samplesize=atoi(optarg);
437           save_cmd=0;
438           if(inopt.samplesize!=8&&inopt.samplesize!=16&&inopt.samplesize!=24){
439             fprintf(stderr,"Invalid bit-depth: %s\n",optarg);
440             fprintf(stderr,"--raw-bits must be one of 8,16, or 24\n");
441             exit(1);
442           }
443         }else if(strcmp(long_options[option_index].name,"raw-rate")==0){
444           inopt.rawmode=1;
445           inopt.rate=atoi(optarg);
446           save_cmd=0;
447         }else if(strcmp(long_options[option_index].name,"raw-chan")==0){
448           inopt.rawmode=1;
449           inopt.channels=atoi(optarg);
450           save_cmd=0;
451         }else if(strcmp(long_options[option_index].name,"raw-endianness")==0){
452           inopt.rawmode=1;
453           inopt.endianness=atoi(optarg);
454           save_cmd=0;
455         }else if(strcmp(long_options[option_index].name,"downmix-mono")==0){
456           downmix=1;
457         }else if(strcmp(long_options[option_index].name,"downmix-stereo")==0){
458           downmix=2;
459         }else if(strcmp(long_options[option_index].name,"no-downmix")==0){
460           downmix=-1;
461         }else if(strcmp(long_options[option_index].name,"expect-loss")==0){
462           expect_loss=atoi(optarg);
463           if(expect_loss>100||expect_loss<0){
464             fprintf(stderr,"Invalid expect-loss: %s\n",optarg);
465             fprintf(stderr,"Expected loss is a percent and must be 0-100.\n");
466             exit(1);
467           }
468         }else if(strcmp(long_options[option_index].name,"comp")==0 ||
469                  strcmp(long_options[option_index].name,"complexity")==0){
470           complexity=atoi(optarg);
471           if(complexity>10||complexity<0){
472             fprintf(stderr,"Invalid complexity: %s\n",optarg);
473             fprintf(stderr,"Complexity must be 0-10.\n");
474             exit(1);
475           }
476         }else if(strcmp(long_options[option_index].name,"framesize")==0){
477           if(strcmp(optarg,"2.5")==0)frame_size=120;
478           else if(strcmp(optarg,"5")==0)frame_size=240;
479           else if(strcmp(optarg,"10")==0)frame_size=480;
480           else if(strcmp(optarg,"20")==0)frame_size=960;
481           else if(strcmp(optarg,"40")==0)frame_size=1920;
482           else if(strcmp(optarg,"60")==0)frame_size=2880;
483           else{
484             fprintf(stderr,"Invalid framesize: %s\n",optarg);
485             fprintf(stderr,"Framesize must be 2.5, 5, 10, 20, 40, or 60.\n");
486             exit(1);
487           }
488         }else if(strcmp(long_options[option_index].name,"max-delay")==0){
489           max_ogg_delay=floor(atof(optarg)*48.);
490           if(max_ogg_delay<0||max_ogg_delay>48000){
491             fprintf(stderr,"Invalid max-delay: %s\n",optarg);
492             fprintf(stderr,"max-delay 0-1000 ms.\n");
493             exit(1);
494           }
495         }else if(strcmp(long_options[option_index].name,"serial")==0){
496           serialno=atoi(optarg);
497         }else if(strcmp(long_options[option_index].name,"set-ctl-int")==0){
498           int len=strlen(optarg),target;
499           char *spos,*tpos;
500           spos=strchr(optarg,'=');
501           if(len<3||spos==NULL||(spos-optarg)<1||(spos-optarg)>=len){
502             fprintf(stderr, "Invalid set-ctl-int: %s\n", optarg);
503             fprintf(stderr, "Syntax is --set-ctl-int intX=intY or\n");
504             fprintf(stderr, "Syntax is --set-ctl-int intS:intX=intY\n");
505             exit(1);
506           }
507           tpos=strchr(optarg,':');
508           if(tpos==NULL){
509             target=-1;
510             tpos=optarg-1;
511           }else target=atoi(optarg);
512           if((atoi(tpos+1)&1)!=0){
513             fprintf(stderr, "Invalid set-ctl-int: %s\n", optarg);
514             fprintf(stderr, "libopus set CTL values are even.\n");
515             exit(1);
516           }
517           if(opt_ctls==0)opt_ctls_ctlval=malloc(sizeof(int)*3);
518           else opt_ctls_ctlval=realloc(opt_ctls_ctlval,sizeof(int)*(opt_ctls+1)*3);
519           if(!opt_ctls_ctlval)
520           {
521             fprintf(stderr, "Memory allocation failure.\n");
522             exit(1);
523           }
524           opt_ctls_ctlval[opt_ctls*3]=target;
525           opt_ctls_ctlval[opt_ctls*3+1]=atoi(tpos+1);
526           opt_ctls_ctlval[opt_ctls*3+2]=atoi(spos+1);
527           opt_ctls++;
528         }else if(strcmp(long_options[option_index].name,"save-range")==0){
529           frange=fopen_utf8(optarg,"w");
530           save_cmd=0;
531           if(frange==NULL){
532             perror(optarg);
533             fprintf(stderr,"Could not open save-range file: %s\n",optarg);
534             fprintf(stderr,"Must provide a writable file name.\n");
535             exit(1);
536           }
537           range_file=optarg;
538         }else if(strcmp(long_options[option_index].name,"comment")==0){
539           save_cmd=0;
540           if(!strchr(optarg,'=')){
541             fprintf(stderr, "Invalid comment: %s\n", optarg);
542             fprintf(stderr, "Comments must be of the form name=value\n");
543             exit(1);
544           }
545           comment_add(&inopt.comments, &inopt.comments_length, NULL, optarg);
546         }else if(strcmp(long_options[option_index].name,"artist")==0){
547           save_cmd=0;
548           comment_add(&inopt.comments, &inopt.comments_length, "artist", optarg);
549         } else if(strcmp(long_options[option_index].name,"title")==0){
550           save_cmd=0;
551           comment_add(&inopt.comments, &inopt.comments_length, "title", optarg);
552         } else if(strcmp(long_options[option_index].name,"album")==0){
553           save_cmd=0;
554           comment_add(&inopt.comments, &inopt.comments_length, "album", optarg);
555         } else if(strcmp(long_options[option_index].name,"date")==0){
556           save_cmd=0;
557           comment_add(&inopt.comments, &inopt.comments_length, "date", optarg);
558         } else if(strcmp(long_options[option_index].name,"genre")==0){
559           save_cmd=0;
560           comment_add(&inopt.comments, &inopt.comments_length, "genre", optarg);
561         } else if(strcmp(long_options[option_index].name,"picture")==0){
562           const char *error_message;
563           char       *picture_data;
564           save_cmd=0;
565           picture_data=parse_picture_specification(optarg,&error_message,
566                                                    &seen_file_icons);
567           if(picture_data==NULL){
568             fprintf(stderr,"Error parsing picture option: %s\n",error_message);
569             exit(1);
570           }
571           comment_add(&inopt.comments,&inopt.comments_length,
572                       "METADATA_BLOCK_PICTURE",picture_data);
573           free(picture_data);
574         } else if(strcmp(long_options[option_index].name,"padding")==0){
575           comment_padding=atoi(optarg);
576         } else if(strcmp(long_options[option_index].name,"discard-comments")==0){
577           inopt.copy_comments=0;
578           inopt.copy_pictures=0;
579         } else if(strcmp(long_options[option_index].name,"discard-pictures")==0){
580           inopt.copy_pictures=0;
581         }
582         /*Commands whos arguments would leak file paths or just end up as metadata
583            should have save_cmd=0; to prevent them from being saved in the
584            command-line tag.*/
585         break;
586       case 'h':
587         usage();
588         exit(0);
589         break;
590       case 'V':
591         opustoolsversion(opus_version);
592         exit(0);
593         break;
594       case '?':
595         usage();
596         exit(1);
597         break;
598     }
599     if(save_cmd && cline_size<(int)sizeof(ENCODER_string)){
600       ret=snprintf(&ENCODER_string[cline_size], sizeof(ENCODER_string)-cline_size, "%s--%s",cline_size==0?"":" ",long_options[option_index].name);
601       if(ret<0||ret>=((int)sizeof(ENCODER_string)-cline_size)){
602         cline_size=sizeof(ENCODER_string);
603       } else {
604         cline_size+=ret;
605         if(optarg){
606           ret=snprintf(&ENCODER_string[cline_size], sizeof(ENCODER_string)-cline_size, " %s",optarg);
607           if(ret<0||ret>=((int)sizeof(ENCODER_string)-cline_size)){
608             cline_size=sizeof(ENCODER_string);
609           } else {
610             cline_size+=ret;
611           }
612         }
613       }
614     }
615   }
616   if(argc_utf8-optind!=2){
617     usage();
618     exit(1);
619   }
620   inFile=argv_utf8[optind];
621   outFile=argv_utf8[optind+1];
622
623   if(cline_size>0)comment_add(&inopt.comments, &inopt.comments_length, "ENCODER_OPTIONS", ENCODER_string);
624
625   if(strcmp(inFile, "-")==0){
626 #if defined WIN32 || defined _WIN32
627     _setmode(_fileno(stdin), _O_BINARY);
628 #elif defined OS2
629     _fsetmode(stdin,"b");
630 #endif
631     fin=stdin;
632   }else{
633     fin=fopen_utf8(inFile, "rb");
634     if(!fin){
635       perror(inFile);
636       exit(1);
637     }
638   }
639
640   if(inopt.rawmode){
641     in_format = &raw_format;
642     in_format->open_func(fin, &inopt, NULL, 0);
643   }else in_format=open_audio_file(fin,&inopt);
644
645   if(!in_format){
646     fprintf(stderr,"Error parsing input file: %s\n",inFile);
647     exit(1);
648   }
649
650   if(inopt.rate<100||inopt.rate>768000){
651     /*Crazy rates excluded to avoid excessive memory usage for padding/resampling.*/
652     fprintf(stderr,"Error parsing input file: %s unhandled sampling rate: %ld hz\n",inFile,inopt.rate);
653     exit(1);
654   }
655
656   if(inopt.channels>255||inopt.channels<1){
657     fprintf(stderr,"Error parsing input file: %s unhandled number of channels: %d\n",inFile,inopt.channels);
658     exit(1);
659   }
660
661   if(downmix==0&&inopt.channels>2&&bitrate>0&&bitrate<(16000*inopt.channels)){
662     if(!quiet)fprintf(stderr,"Notice: Surround bitrate less than 16kbit/sec/channel, downmixing.\n");
663     downmix=inopt.channels>8?1:2;
664   }
665
666   if(downmix>0&&downmix<inopt.channels)downmix=setup_downmix(&inopt,downmix);
667   else downmix=0;
668
669   rate=inopt.rate;
670   chan=inopt.channels;
671   inopt.skip=0;
672
673   /*In order to code the complete length we'll need to do a little padding*/
674   setup_padder(&inopt,&original_samples);
675
676   if(rate>24000)coding_rate=48000;
677   else if(rate>16000)coding_rate=24000;
678   else if(rate>12000)coding_rate=16000;
679   else if(rate>8000)coding_rate=12000;
680   else coding_rate=8000;
681
682   frame_size=frame_size/(48000/coding_rate);
683
684   /*Scale the resampler complexity, but only for 48000 output because
685     the near-cutoff behavior matters a lot more at lower rates.*/
686   if(rate!=coding_rate)setup_resample(&inopt,coding_rate==48000?(complexity+1)/2:5,coding_rate);
687
688   if(rate!=coding_rate&&complexity!=10&&!quiet){
689     fprintf(stderr,"Notice: Using resampling with complexity<10.\n");
690     fprintf(stderr,"Opusenc is fastest with 48, 24, 16, 12, or 8kHz input.\n\n");
691   }
692
693   /*OggOpus headers*/ /*FIXME: broke forcemono*/
694   header.channels=chan;
695   header.channel_mapping=header.channels>8?255:chan>2;
696   header.input_sample_rate=rate;
697   header.gain=inopt.gain;
698
699   /*Initialize OPUS encoder*/
700   /*Framesizes <10ms can only use the MDCT modes, so we switch on RESTRICTED_LOWDELAY
701     to save the extra 2.5ms of codec lookahead when we'll be using only small frames.*/
702   st=opus_multistream_surround_encoder_create(coding_rate, chan, header.channel_mapping, &header.nb_streams, &header.nb_coupled,
703      header.stream_map, frame_size<480/(48000/coding_rate)?OPUS_APPLICATION_RESTRICTED_LOWDELAY:OPUS_APPLICATION_AUDIO, &ret);
704   if(ret!=OPUS_OK){
705     fprintf(stderr, "Error cannot create encoder: %s\n", opus_strerror(ret));
706     exit(1);
707   }
708
709   min_bytes=max_frame_bytes=(1275*3+7)*header.nb_streams;
710   packet=malloc(sizeof(unsigned char)*max_frame_bytes);
711   if(packet==NULL){
712     fprintf(stderr,"Error allocating packet buffer.\n");
713     exit(1);
714   }
715
716   if(bitrate<0){
717     /*Lower default rate for sampling rates [8000-44100) by a factor of (rate+16k)/(64k)*/
718     bitrate=((64000*header.nb_streams+32000*header.nb_coupled)*
719              (IMIN(48,IMAX(8,((rate<44100?rate:48000)+1000)/1000))+16)+32)>>6;
720   }
721
722   if(bitrate>(1024000*chan)||bitrate<500){
723     fprintf(stderr,"Error: Bitrate %d bits/sec is insane.\nDid you mistake bits for kilobits?\n",bitrate);
724     fprintf(stderr,"--bitrate values from 6-256 kbit/sec per channel are meaningful.\n");
725     exit(1);
726   }
727   bitrate=IMIN(chan*256000,bitrate);
728
729   ret=opus_multistream_encoder_ctl(st, OPUS_SET_BITRATE(bitrate));
730   if(ret!=OPUS_OK){
731     fprintf(stderr,"Error OPUS_SET_BITRATE returned: %s\n",opus_strerror(ret));
732     exit(1);
733   }
734
735   ret=opus_multistream_encoder_ctl(st, OPUS_SET_VBR(!with_hard_cbr));
736   if(ret!=OPUS_OK){
737     fprintf(stderr,"Error OPUS_SET_VBR returned: %s\n",opus_strerror(ret));
738     exit(1);
739   }
740
741   if(!with_hard_cbr){
742     ret=opus_multistream_encoder_ctl(st, OPUS_SET_VBR_CONSTRAINT(with_cvbr));
743     if(ret!=OPUS_OK){
744       fprintf(stderr,"Error OPUS_SET_VBR_CONSTRAINT returned: %s\n",opus_strerror(ret));
745       exit(1);
746     }
747   }
748
749   ret=opus_multistream_encoder_ctl(st, OPUS_SET_COMPLEXITY(complexity));
750   if(ret!=OPUS_OK){
751     fprintf(stderr,"Error OPUS_SET_COMPLEXITY returned: %s\n",opus_strerror(ret));
752     exit(1);
753   }
754
755   ret=opus_multistream_encoder_ctl(st, OPUS_SET_PACKET_LOSS_PERC(expect_loss));
756   if(ret!=OPUS_OK){
757     fprintf(stderr,"Error OPUS_SET_PACKET_LOSS_PERC returned: %s\n",opus_strerror(ret));
758     exit(1);
759   }
760
761 #ifdef OPUS_SET_LSB_DEPTH
762   ret=opus_multistream_encoder_ctl(st, OPUS_SET_LSB_DEPTH(IMAX(8,IMIN(24,inopt.samplesize))));
763   if(ret!=OPUS_OK){
764     fprintf(stderr,"Warning OPUS_SET_LSB_DEPTH returned: %s\n",opus_strerror(ret));
765   }
766 #endif
767
768   /*This should be the last set of CTLs, except the lookahead get, so it can override the defaults.*/
769   for(i=0;i<opt_ctls;i++){
770     int target=opt_ctls_ctlval[i*3];
771     if(target==-1){
772       ret=opus_multistream_encoder_ctl(st,opt_ctls_ctlval[i*3+1],opt_ctls_ctlval[i*3+2]);
773       if(ret!=OPUS_OK){
774         fprintf(stderr,"Error opus_multistream_encoder_ctl(st,%d,%d) returned: %s\n",opt_ctls_ctlval[i*3+1],opt_ctls_ctlval[i*3+2],opus_strerror(ret));
775         exit(1);
776       }
777     }else if(target<header.nb_streams){
778       OpusEncoder *oe;
779       opus_multistream_encoder_ctl(st,OPUS_MULTISTREAM_GET_ENCODER_STATE(i,&oe));
780       ret=opus_encoder_ctl(oe, opt_ctls_ctlval[i*3+1],opt_ctls_ctlval[i*3+2]);
781       if(ret!=OPUS_OK){
782         fprintf(stderr,"Error opus_encoder_ctl(st[%d],%d,%d) returned: %s\n",target,opt_ctls_ctlval[i*3+1],opt_ctls_ctlval[i*3+2],opus_strerror(ret));
783         exit(1);
784       }
785     }else{
786       fprintf(stderr,"Error --set-ctl-int target stream %d is higher than the maximum stream number %d.\n",target,header.nb_streams-1);
787       exit(1);
788     }
789   }
790
791   /*We do the lookahead check late so user CTLs can change it*/
792   ret=opus_multistream_encoder_ctl(st, OPUS_GET_LOOKAHEAD(&lookahead));
793   if(ret!=OPUS_OK){
794     fprintf(stderr,"Error OPUS_GET_LOOKAHEAD returned: %s\n",opus_strerror(ret));
795     exit(1);
796   }
797   inopt.skip+=lookahead;
798   /*Regardless of the rate we're coding at the ogg timestamping/skip is
799     always timed at 48000.*/
800   header.preskip=inopt.skip*(48000./coding_rate);
801   /* Extra samples that need to be read to compensate for the pre-skip */
802   inopt.extraout=(int)header.preskip*(rate/48000.);
803
804   if(!quiet){
805     int opus_app;
806     fprintf(stderr,"Encoding using %s",opus_version);
807     opus_multistream_encoder_ctl(st,OPUS_GET_APPLICATION(&opus_app));
808     if(opus_app==OPUS_APPLICATION_VOIP)fprintf(stderr," (VoIP)\n");
809     else if(opus_app==OPUS_APPLICATION_AUDIO)fprintf(stderr," (audio)\n");
810     else if(opus_app==OPUS_APPLICATION_RESTRICTED_LOWDELAY)fprintf(stderr," (low-delay)\n");
811     else fprintf(stderr," (unknown)\n");
812     fprintf(stderr,"-----------------------------------------------------\n");
813     fprintf(stderr,"   Input: %0.6gkHz %d channel%s\n",
814             header.input_sample_rate/1000.,chan,chan<2?"":"s");
815     fprintf(stderr,"  Output: %d channel%s (",header.channels,header.channels<2?"":"s");
816     if(header.nb_coupled>0)fprintf(stderr,"%d coupled",header.nb_coupled*2);
817     if(header.nb_streams-header.nb_coupled>0)fprintf(stderr,
818        "%s%d uncoupled",header.nb_coupled>0?", ":"",
819        header.nb_streams-header.nb_coupled);
820     fprintf(stderr,")\n          %0.2gms packets, %0.6gkbit/sec%s\n",
821        frame_size/(coding_rate/1000.), bitrate/1000.,
822        with_hard_cbr?" CBR":with_cvbr?" CVBR":" VBR");
823     fprintf(stderr," Preskip: %d\n",header.preskip);
824
825     if(frange!=NULL)fprintf(stderr,"         Writing final range file %s\n",range_file);
826     fprintf(stderr,"\n");
827   }
828
829   if(strcmp(outFile,"-")==0){
830 #if defined WIN32 || defined _WIN32
831     _setmode(_fileno(stdout), _O_BINARY);
832 #endif
833     fout=stdout;
834   }else{
835     fout=fopen_utf8(outFile, "wb");
836     if(!fout){
837       perror(outFile);
838       exit(1);
839     }
840   }
841
842   /*Initialize Ogg stream struct*/
843   if(ogg_stream_init(&os, serialno)==-1){
844     fprintf(stderr,"Error: stream init failed\n");
845     exit(1);
846   }
847
848   /*Write header*/
849   {
850     unsigned char header_data[100];
851     int packet_size=opus_header_to_packet(&header, header_data, 100);
852     op.packet=header_data;
853     op.bytes=packet_size;
854     op.b_o_s=1;
855     op.e_o_s=0;
856     op.granulepos=0;
857     op.packetno=0;
858     ogg_stream_packetin(&os, &op);
859
860     while((ret=ogg_stream_flush(&os, &og))){
861       if(!ret)break;
862       ret=oe_write_page(&og, fout);
863       if(ret!=og.header_len+og.body_len){
864         fprintf(stderr,"Error: failed writing header to output stream\n");
865         exit(1);
866       }
867       bytes_written+=ret;
868       pages_out++;
869     }
870
871     comment_pad(&inopt.comments, &inopt.comments_length, comment_padding);
872     op.packet=(unsigned char *)inopt.comments;
873     op.bytes=inopt.comments_length;
874     op.b_o_s=0;
875     op.e_o_s=0;
876     op.granulepos=0;
877     op.packetno=1;
878     ogg_stream_packetin(&os, &op);
879   }
880
881   /* writing the rest of the opus header packets */
882   while((ret=ogg_stream_flush(&os, &og))){
883     if(!ret)break;
884     ret=oe_write_page(&og, fout);
885     if(ret!=og.header_len + og.body_len){
886       fprintf(stderr,"Error: failed writing header to output stream\n");
887       exit(1);
888     }
889     bytes_written+=ret;
890     pages_out++;
891   }
892
893   free(inopt.comments);
894
895   input=malloc(sizeof(float)*frame_size*chan);
896   if(input==NULL){
897     fprintf(stderr,"Error: couldn't allocate sample buffer.\n");
898     exit(1);
899   }
900
901   /*Main encoding loop (one frame per iteration)*/
902   eos=0;
903   nb_samples=-1;
904   while(!op.e_o_s){
905     int size_segments,cur_frame_size;
906     id++;
907
908     if(nb_samples<0){
909       nb_samples = inopt.read_samples(inopt.readdata,input,frame_size);
910       total_samples+=nb_samples;
911       if(nb_samples<frame_size)op.e_o_s=1;
912       else op.e_o_s=0;
913     }
914     op.e_o_s|=eos;
915
916     if(start_time==0){
917       start_time = time(NULL);
918     }
919
920     cur_frame_size=frame_size;
921
922     /*No fancy end padding, just fill with zeros for now.*/
923     if(nb_samples<cur_frame_size)for(i=nb_samples*chan;i<cur_frame_size*chan;i++)input[i]=0;
924
925     /*Encode current frame*/
926     VG_UNDEF(packet,max_frame_bytes);
927     VG_CHECK(input,sizeof(float)*chan*cur_frame_size);
928     nbBytes=opus_multistream_encode_float(st, input, cur_frame_size, packet, max_frame_bytes);
929     if(nbBytes<0){
930       fprintf(stderr, "Encoding failed: %s. Aborting.\n", opus_strerror(nbBytes));
931       break;
932     }
933     VG_CHECK(packet,nbBytes);
934     VG_UNDEF(input,sizeof(float)*chan*cur_frame_size);
935     nb_encoded+=cur_frame_size;
936     enc_granulepos+=cur_frame_size*48000/coding_rate;
937     total_bytes+=nbBytes;
938     size_segments=(nbBytes+255)/255;
939     peak_bytes=IMAX(nbBytes,peak_bytes);
940     min_bytes=IMIN(nbBytes,min_bytes);
941
942     if(frange!=NULL){
943       opus_uint32 rngs[256];
944       OpusEncoder *oe;
945       for(i=0;i<header.nb_streams;i++){
946         ret=opus_multistream_encoder_ctl(st,OPUS_MULTISTREAM_GET_ENCODER_STATE(i,&oe));
947         ret=opus_encoder_ctl(oe,OPUS_GET_FINAL_RANGE(&rngs[i]));
948       }
949       save_range(frange,cur_frame_size*(48000/coding_rate),packet,nbBytes,
950                  rngs,header.nb_streams);
951     }
952
953     /*Flush early if adding this packet would make us end up with a
954       continued page which we wouldn't have otherwise.*/
955     while((((size_segments<=255)&&(last_segments+size_segments>255))||
956            (enc_granulepos-last_granulepos>max_ogg_delay))&&
957 #ifdef OLD_LIBOGG
958            ogg_stream_flush(&os, &og)){
959 #else
960            ogg_stream_flush_fill(&os, &og,255*255)){
961 #endif
962       if(ogg_page_packets(&og)!=0)last_granulepos=ogg_page_granulepos(&og);
963       last_segments-=og.header[26];
964       ret=oe_write_page(&og, fout);
965       if(ret!=og.header_len+og.body_len){
966          fprintf(stderr,"Error: failed writing data to output stream\n");
967          exit(1);
968       }
969       bytes_written+=ret;
970       pages_out++;
971     }
972
973     /*The downside of early reading is if the input is an exact
974       multiple of the frame_size you'll get an extra frame that needs
975       to get cropped off. The downside of late reading is added delay.
976       If your ogg_delay is 120ms or less we'll assume you want the
977       low delay behavior.*/
978     if((!op.e_o_s)&&max_ogg_delay>5760){
979       nb_samples = inopt.read_samples(inopt.readdata,input,frame_size);
980       total_samples+=nb_samples;
981       if(nb_samples<frame_size)eos=1;
982       if(nb_samples==0)op.e_o_s=1;
983     } else nb_samples=-1;
984
985     op.packet=(unsigned char *)packet;
986     op.bytes=nbBytes;
987     op.b_o_s=0;
988     op.granulepos=enc_granulepos;
989     if(op.e_o_s){
990       /*We compute the final GP as ceil(len*48k/input_rate). When a resampling
991         decoder does the matching floor(len*input/48k) conversion the length will
992         be exactly the same as the input.*/
993       op.granulepos=((original_samples*48000+rate-1)/rate)+header.preskip;
994     }
995     op.packetno=2+id;
996     ogg_stream_packetin(&os, &op);
997     last_segments+=size_segments;
998
999     /*If the stream is over or we're sure that the delayed flush will fire,
1000       go ahead and flush now to avoid adding delay.*/
1001     while((op.e_o_s||(enc_granulepos+(frame_size*48000/coding_rate)-last_granulepos>max_ogg_delay)||
1002            (last_segments>=255))?
1003 #ifdef OLD_LIBOGG
1004     /*Libogg > 1.2.2 allows us to achieve lower overhead by
1005       producing larger pages. For 20ms frames this is only relevant
1006       above ~32kbit/sec.*/
1007            ogg_stream_flush(&os, &og):
1008            ogg_stream_pageout(&os, &og)){
1009 #else
1010            ogg_stream_flush_fill(&os, &og,255*255):
1011            ogg_stream_pageout_fill(&os, &og,255*255)){
1012 #endif
1013       if(ogg_page_packets(&og)!=0)last_granulepos=ogg_page_granulepos(&og);
1014       last_segments-=og.header[26];
1015       ret=oe_write_page(&og, fout);
1016       if(ret!=og.header_len+og.body_len){
1017          fprintf(stderr,"Error: failed writing data to output stream\n");
1018          exit(1);
1019       }
1020       bytes_written+=ret;
1021       pages_out++;
1022     }
1023
1024     if(!quiet){
1025       stop_time = time(NULL);
1026       if(stop_time>last_spin){
1027         double estbitrate;
1028         double coded_seconds=nb_encoded/(double)coding_rate;
1029         double wall_time=(stop_time-start_time)+1e-6;
1030         char sbuf[55];
1031         static const char spinner[]="|/-\\";
1032         if(!with_hard_cbr){
1033           double tweight=1./(1+exp(-((coded_seconds/10.)-3.)));
1034           estbitrate=(total_bytes*8.0/coded_seconds)*tweight+
1035                       bitrate*(1.-tweight);
1036         }else estbitrate=nbBytes*8*((double)coding_rate/frame_size);
1037         fprintf(stderr,"\r");
1038         for(i=0;i<last_spin_len;i++)fprintf(stderr," ");
1039         if(inopt.total_samples_per_channel>0 && inopt.total_samples_per_channel<nb_encoded){
1040           snprintf(sbuf,54,"\r[%c] %02d%% ",spinner[last_spin&3],
1041           (int)floor(nb_encoded/(double)(inopt.total_samples_per_channel+inopt.skip)*100.));
1042         }else{
1043           snprintf(sbuf,54,"\r[%c] ",spinner[last_spin&3]);
1044         }
1045         last_spin_len=strlen(sbuf);
1046         snprintf(sbuf+last_spin_len,54-last_spin_len,
1047           "%02d:%02d:%02d.%02d %4.3gx realtime, %5.4gkbit/s",
1048           (int)(coded_seconds/3600),(int)(coded_seconds/60)%60,
1049           (int)(coded_seconds)%60,(int)(coded_seconds*100)%100,
1050           coded_seconds/wall_time,
1051           estbitrate/1000.);
1052         fprintf(stderr,"%s",sbuf);
1053         fflush(stderr);
1054         last_spin_len=strlen(sbuf);
1055         last_spin=stop_time;
1056       }
1057     }
1058   }
1059   stop_time = time(NULL);
1060
1061   for(i=0;i<last_spin_len;i++)fprintf(stderr," ");
1062   if(last_spin_len)fprintf(stderr,"\r");
1063
1064   if(!quiet){
1065     double coded_seconds=nb_encoded/(double)coding_rate;
1066     double wall_time=(stop_time-start_time)+1e-6;
1067     fprintf(stderr,"Encoding complete                                    \n");
1068     fprintf(stderr,"-----------------------------------------------------\n");
1069     fprintf(stderr,"       Encoded:");
1070     print_time(coded_seconds);
1071     fprintf(stderr,"\n       Runtime:");
1072     print_time(wall_time);
1073     fprintf(stderr,"\n                (%0.4gx realtime)\n",coded_seconds/wall_time);
1074     fprintf(stderr,"         Wrote: %" I64FORMAT " bytes, %d packets, %" I64FORMAT " pages\n",bytes_written,id+1,pages_out);
1075     fprintf(stderr,"       Bitrate: %0.6gkbit/s (without overhead)\n",
1076             total_bytes*8.0/(coded_seconds)/1000.0);
1077     fprintf(stderr," Instant rates: %0.6gkbit/s to %0.6gkbit/s\n                (%d to %d bytes per packet)\n",
1078             min_bytes*8*((double)coding_rate/frame_size/1000.),
1079             peak_bytes*8*((double)coding_rate/frame_size/1000.),min_bytes,peak_bytes);
1080     fprintf(stderr,"      Overhead: %0.3g%% (container+metadata)\n",(bytes_written-total_bytes)/(double)bytes_written*100.);
1081 #ifdef OLD_LIBOGG
1082     if(max_ogg_delay>(frame_size*(48000/coding_rate)*4))fprintf(stderr,"    (use libogg 1.3 or later for lower overhead)\n");
1083 #endif
1084     fprintf(stderr,"\n");
1085   }
1086
1087   opus_multistream_encoder_destroy(st);
1088   ogg_stream_clear(&os);
1089   free(packet);
1090   free(input);
1091   if(opt_ctls)free(opt_ctls_ctlval);
1092
1093   if(rate!=coding_rate)clear_resample(&inopt);
1094   clear_padder(&inopt);
1095   if(downmix)clear_downmix(&inopt);
1096   in_format->close_func(inopt.readdata);
1097   if(fin)fclose(fin);
1098   if(fout)fclose(fout);
1099   if(frange)fclose(frange);
1100 #ifdef WIN_UNICODE
1101    free_commandline_arguments_utf8(&argc_utf8, &argv_utf8);
1102 #endif
1103   return 0;
1104 }
1105
1106 /*
1107  Comments will be stored in the Vorbis style.
1108  It is describled in the "Structure" section of
1109     http://www.xiph.org/ogg/vorbis/doc/v-comment.html
1110
1111  However, Opus and other non-vorbis formats omit the "framing_bit".
1112
1113 The comment header is decoded as follows:
1114   1) [vendor_length] = read an unsigned integer of 32 bits
1115   2) [vendor_string] = read a UTF-8 vector as [vendor_length] octets
1116   3) [user_comment_list_length] = read an unsigned integer of 32 bits
1117   4) iterate [user_comment_list_length] times {
1118      5) [length] = read an unsigned integer of 32 bits
1119      6) this iteration's user comment = read a UTF-8 vector as [length] octets
1120      }
1121   7) done.
1122 */
1123
1124 #define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \
1125                            ((buf[base+2]<<16)&0xff0000)| \
1126                            ((buf[base+1]<<8)&0xff00)| \
1127                            (buf[base]&0xff))
1128 #define writeint(buf, base, val) do{ buf[base+3]=((val)>>24)&0xff; \
1129                                      buf[base+2]=((val)>>16)&0xff; \
1130                                      buf[base+1]=((val)>>8)&0xff; \
1131                                      buf[base]=(val)&0xff; \
1132                                  }while(0)
1133
1134 static void comment_init(char **comments, int* length, const char *vendor_string)
1135 {
1136   /*The 'vendor' field should be the actual encoding library used.*/
1137   int vendor_length=strlen(vendor_string);
1138   int user_comment_list_length=0;
1139   int len=8+4+vendor_length+4;
1140   char *p=(char*)malloc(len);
1141   if(p==NULL){
1142     fprintf(stderr, "malloc failed in comment_init()\n");
1143     exit(1);
1144   }
1145   memcpy(p, "OpusTags", 8);
1146   writeint(p, 8, vendor_length);
1147   memcpy(p+12, vendor_string, vendor_length);
1148   writeint(p, 12+vendor_length, user_comment_list_length);
1149   *length=len;
1150   *comments=p;
1151 }
1152
1153 void comment_add(char **comments, int* length, char *tag, char *val)
1154 {
1155   char* p=*comments;
1156   int vendor_length=readint(p, 8);
1157   int user_comment_list_length=readint(p, 8+4+vendor_length);
1158   int tag_len=(tag?strlen(tag)+1:0);
1159   int val_len=strlen(val);
1160   int len=(*length)+4+tag_len+val_len;
1161
1162   p=(char*)realloc(p, len);
1163   if(p==NULL){
1164     fprintf(stderr, "realloc failed in comment_add()\n");
1165     exit(1);
1166   }
1167
1168   writeint(p, *length, tag_len+val_len);      /* length of comment */
1169   if(tag){
1170     memcpy(p+*length+4, tag, tag_len);        /* comment tag */
1171     (p+*length+4)[tag_len-1] = '=';           /* separator */
1172   }
1173   memcpy(p+*length+4+tag_len, val, val_len);  /* comment */
1174   writeint(p, 8+4+vendor_length, user_comment_list_length+1);
1175   *comments=p;
1176   *length=len;
1177 }
1178
1179 static void comment_pad(char **comments, int* length, int amount)
1180 {
1181   if(amount>0){
1182     int i;
1183     int newlen;
1184     char* p=*comments;
1185     /*Make sure there is at least amount worth of padding free, and
1186        round up to the maximum that fits in the current ogg segments.*/
1187     newlen=(*length+amount+255)/255*255-1;
1188     p=realloc(p,newlen);
1189     if(p==NULL){
1190       fprintf(stderr,"realloc failed in comment_pad()\n");
1191       exit(1);
1192     }
1193     for(i=*length;i<newlen;i++)p[i]=0;
1194     *comments=p;
1195     *length=newlen;
1196   }
1197 }
1198 #undef readint
1199 #undef writeint