8fa48dd2434edcbe7e9c78e0f7f9145206f6dae8
[flac.git] / src / flac / encode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002  Josh Coalson
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17  */
18
19 #if defined _WIN32 && !defined __CYGWIN__
20 /* where MSVC puts unlink() */
21 # include <io.h>
22 #else
23 # include <unistd.h>
24 #endif
25 #include <limits.h> /* for LONG_MAX */
26 #include <math.h> /* for floor() */
27 #include <stdarg.h>
28 #include <stdio.h> /* for FILE etc. */
29 #include <stdlib.h> /* for malloc */
30 #include <string.h> /* for strcmp() */
31 #include "FLAC/all.h"
32 #include "share/grabbag.h"
33 #include "encode.h"
34
35 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
38
39 #ifdef FLAC__HAS_OGG
40 #include "OggFLAC/stream_encoder.h"
41 #endif
42
43 #ifdef min
44 #undef min
45 #endif
46 #define min(x,y) ((x)<(y)?(x):(y))
47
48 /* this MUST be >= 588 so that sector aligning can take place with one read */
49 #define CHUNK_OF_SAMPLES 2048
50
51 typedef struct {
52 #ifdef FLAC__HAS_OGG
53         FLAC__bool use_ogg;
54 #endif
55         FLAC__bool verify;
56         FLAC__bool verbose;
57         FLAC__bool is_stdout;
58         const char *inbasefilename;
59         const char *outfilename;
60
61         FLAC__bool replay_gain;
62         unsigned channels;
63         unsigned bits_per_sample;
64         unsigned sample_rate;
65         FLAC__uint64 unencoded_size;
66         FLAC__uint64 total_samples_to_encode;
67         FLAC__uint64 bytes_written;
68         FLAC__uint64 samples_written;
69         unsigned blocksize;
70         unsigned stats_mask;
71
72         /*
73          * We use flac.stream for encoding native FLAC to stdout
74          * We use flac.file for encoding native FLAC to a regular file
75          * We use ogg.stream for encoding Ogg FLAC to either stdout or a regular file
76          */
77         union {
78                 union {
79                         FLAC__StreamEncoder *stream;
80                         FLAC__FileEncoder *file;
81                 } flac;
82 #ifdef FLAC__HAS_OGG
83                 union {
84                         OggFLAC__StreamEncoder *stream;
85                 } ogg;
86 #endif
87         } encoder;
88
89         FILE *fin;
90         FILE *fout;
91         FLAC__StreamMetadata *seek_table_template;
92 } EncoderSession;
93
94
95 static FLAC__bool is_big_endian_host_;
96
97 static unsigned char ucbuffer_[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
98 static signed char *scbuffer_ = (signed char *)ucbuffer_;
99 static FLAC__uint16 *usbuffer_ = (FLAC__uint16 *)ucbuffer_;
100 static FLAC__int16 *ssbuffer_ = (FLAC__int16 *)ucbuffer_;
101
102 static FLAC__int32 in_[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
103 static FLAC__int32 *input_[FLAC__MAX_CHANNELS];
104
105
106 /*
107  * unpublished debug routines from the FLAC libs
108  */
109 extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
110 extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
111 extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
112 extern FLAC__bool FLAC__file_encoder_disable_constant_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
113 extern FLAC__bool FLAC__file_encoder_disable_fixed_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
114 extern FLAC__bool FLAC__file_encoder_disable_verbatim_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
115 extern FLAC__bool OggFLAC__stream_encoder_disable_constant_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
116 extern FLAC__bool OggFLAC__stream_encoder_disable_fixed_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
117 extern FLAC__bool OggFLAC__stream_encoder_disable_verbatim_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
118
119 /*
120  * local routines
121  */
122 static FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FLAC__bool verbose, FILE *infile, const char *infilename, const char *outfilename);
123 static void EncoderSession_destroy(EncoderSession *e);
124 static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero);
125 static int EncoderSession_finish_error(EncoderSession *e);
126 static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate);
127 static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
128 static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, EncoderSession *e);
129 static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps);
130 #ifdef FLAC__HAS_OGG
131 static FLAC__StreamEncoderWriteStatus ogg_stream_encoder_write_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
132 #endif
133 static FLAC__StreamEncoderWriteStatus flac_stream_encoder_write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
134 static void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
135 static void flac_file_encoder_progress_callback(const FLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
136 static void print_stats(const EncoderSession *encoder_session);
137 static void print_error_with_state(const EncoderSession *e, const char *message);
138 static void print_verify_error(EncoderSession *e);
139 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
140 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
141 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
142 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
143 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
144
145 /*
146  * public routines
147  */
148 int
149 flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const char *outfilename,
150         const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
151 {
152         EncoderSession encoder_session;
153         FLAC__uint16 x;
154         FLAC__uint32 xx;
155         unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
156         FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
157         int info_align_carry= -1, info_align_zero= -1;
158
159         FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
160
161         (void)infilesize; /* silence compiler warning about unused parameter */
162         (void)lookahead; /* silence compiler warning about unused parameter */
163         (void)lookahead_length; /* silence compiler warning about unused parameter */
164
165         if(!
166                 EncoderSession_construct(
167                         &encoder_session,
168 #ifdef FLAC__HAS_OGG
169                         options.common.use_ogg,
170 #else
171                         /*use_ogg=*/false,
172 #endif
173                         options.common.verify,
174                         options.common.verbose,
175                         infile,
176                         infilename,
177                         outfilename
178                 )
179         )
180                 return 1;
181
182         /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
183
184         while(1) {
185                 size_t c= 0U;
186                 char chunk_id[4];
187
188                 /* chunk identifier; really conservative about behavior of fread() and feof() */
189                 if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
190                         break;
191                 else if(c<4U || feof(infile)) {
192                         fprintf(stderr, "%s: ERROR: incomplete chunk identifier\n", encoder_session.inbasefilename);
193                         return EncoderSession_finish_error(&encoder_session);
194                 }
195
196                 if(got_comm_chunk==false && !strncmp(chunk_id, "COMM", 4)) { /* common chunk */
197                         unsigned long skip;
198
199                         /* COMM chunk size */
200                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
201                                 return EncoderSession_finish_error(&encoder_session);
202                         else if(xx<18U) {
203                                 fprintf(stderr, "%s: ERROR: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
204                                 return EncoderSession_finish_error(&encoder_session);
205                         }
206                         else if(xx!=18U)
207                                 fprintf(stderr, "%s: WARNING: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
208                         skip= (xx-18U)+(xx & 1U);
209
210                         /* number of channels */
211                         if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
212                                 return EncoderSession_finish_error(&encoder_session);
213                         else if(x==0U || x>FLAC__MAX_CHANNELS) {
214                                 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned int)x);
215                                 return EncoderSession_finish_error(&encoder_session);
216                         }
217                         else if(options.common.sector_align && x!=2U) {
218                                 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
219                                 return EncoderSession_finish_error(&encoder_session);
220                         }
221                         channels= x;
222
223                         /* number of sample frames */
224                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
225                                 return EncoderSession_finish_error(&encoder_session);
226                         sample_frames= xx;
227
228                         /* bits per sample */
229                         if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
230                                 return EncoderSession_finish_error(&encoder_session);
231                         else if(x!=8U && x!=16U && x!=24U) {
232                                 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
233                                 return EncoderSession_finish_error(&encoder_session);
234                         }
235                         else if(options.common.sector_align && x!=16U) {
236                                 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
237                                 return EncoderSession_finish_error(&encoder_session);
238                         }
239                         bps= x;
240
241                         /* sample rate */
242                         if(!read_sane_extended(infile, &xx, false, encoder_session.inbasefilename))
243                                 return EncoderSession_finish_error(&encoder_session);
244                         else if(!FLAC__format_sample_rate_is_valid(xx)) {
245                                 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned int)xx);
246                                 return EncoderSession_finish_error(&encoder_session);
247                         }
248                         else if(options.common.sector_align && xx!=44100U) {
249                                 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)xx);
250                                 return EncoderSession_finish_error(&encoder_session);
251                         }
252                         sample_rate= xx;
253
254                         /* skip any extra data in the COMM chunk */
255                         FLAC__ASSERT(skip<=LONG_MAX);
256                         while(skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
257                                 unsigned int need= min(skip, sizeof ucbuffer_);
258                                 if(fread(ucbuffer_, 1U, need, infile)<need) {
259                                         fprintf(stderr, "%s: ERROR during read while skipping extra COMM data\n", encoder_session.inbasefilename);
260                                         return EncoderSession_finish_error(&encoder_session);
261                                 }
262                                 skip-= need;
263                         }
264
265                         got_comm_chunk= true;
266                 }
267                 else if(got_ssnd_chunk==false && !strncmp(chunk_id, "SSND", 4)) { /* sound data chunk */
268                         unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
269                         size_t bytes_per_frame= channels*(bps>>3);
270                         FLAC__bool pad= false;
271
272                         if(got_comm_chunk==false) {
273                                 fprintf(stderr, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_session.inbasefilename);
274                                 return EncoderSession_finish_error(&encoder_session);
275                         }
276
277                         /* SSND chunk size */
278                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
279                                 return EncoderSession_finish_error(&encoder_session);
280                         else if(xx!=(sample_frames*bytes_per_frame + 8U)) {
281                                 fprintf(stderr, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_session.inbasefilename);
282                                 return EncoderSession_finish_error(&encoder_session);
283                         }
284                         data_bytes= xx;
285                         pad= (data_bytes & 1U) ? true : false;
286
287                         /* offset */
288                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
289                                 return EncoderSession_finish_error(&encoder_session);
290                         else if(xx!=0U) {
291                                 fprintf(stderr, "%s: ERROR: offset is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
292                                 return EncoderSession_finish_error(&encoder_session);
293                         }
294                         offset= xx;
295
296                         /* block size */
297                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
298                                 return EncoderSession_finish_error(&encoder_session);
299                         else if(xx!=0U) {
300                                 fprintf(stderr, "%s: ERROR: block size is %u; must be 0\n", encoder_session.inbasefilename, (unsigned int)xx);
301                                 return EncoderSession_finish_error(&encoder_session);
302                         }
303                         block_size= xx;
304
305                         if(options.common.skip>0U) {
306                                 FLAC__uint64 remaining= options.common.skip*bytes_per_frame;
307
308                                 /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
309                                 /* is guaranteed to be less than LONG_MAX */
310                                 for(; remaining>0U; remaining-= remaining>(1U<<30) ? remaining : (1U<<30))
311                                 {
312                                         unsigned long skip= (unsigned long)(remaining % (1U<<30));
313
314                                         FLAC__ASSERT(skip<=LONG_MAX);
315                                         while(skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
316                                                 unsigned int need= min(skip, sizeof ucbuffer_);
317                                                 if(fread(ucbuffer_, 1U, need, infile)<need) {
318                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
319                                                         return EncoderSession_finish_error(&encoder_session);
320                                                 }
321                                                 skip-= need;
322                                         }
323                                 }
324                         }
325
326                         data_bytes-= (8U + (unsigned int)options.common.skip*bytes_per_frame); /*@@@ WATCHOUT: 4GB limit */
327                         encoder_session.total_samples_to_encode= data_bytes/bytes_per_frame + *options.common.align_reservoir_samples;
328                         if(options.common.sector_align) {
329                                 align_remainder= (unsigned int)(encoder_session.total_samples_to_encode % 588U);
330                                 if(options.common.is_last_file)
331                                         encoder_session.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
332                                 else
333                                         encoder_session.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
334                         }
335
336                         /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
337                         encoder_session.unencoded_size= encoder_session.total_samples_to_encode*bytes_per_frame+54;
338
339                         if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
340                                 return EncoderSession_finish_error(&encoder_session);
341
342                         /* first do any samples in the reservoir */
343                         if(options.common.sector_align && *options.common.align_reservoir_samples>0U) {
344
345                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
346                                         print_error_with_state(&encoder_session, "ERROR during encoding");
347                                         return EncoderSession_finish_error(&encoder_session);
348                                 }
349                         }
350
351                         /* decrement the data_bytes counter if we need to align the file */
352                         if(options.common.sector_align) {
353                                 if(options.common.is_last_file)
354                                         *options.common.align_reservoir_samples= 0U;
355                                 else {
356                                         *options.common.align_reservoir_samples= align_remainder;
357                                         data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
358                                 }
359                         }
360
361                         /* now do from the file */
362                         while(data_bytes>0) {
363                                 size_t bytes_read= fread(ucbuffer_, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
364
365                                 if(bytes_read==0U) {
366                                         if(ferror(infile)) {
367                                                 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
368                                                 return EncoderSession_finish_error(&encoder_session);
369                                         }
370                                         else if(feof(infile)) {
371                                                 fprintf(stderr, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned int)encoder_session.total_samples_to_encode, (unsigned int)encoder_session.samples_written);
372                                                 data_bytes= 0;
373                                         }
374                                 }
375                                 else {
376                                         if(bytes_read % bytes_per_frame != 0U) {
377                                                 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
378                                                 return EncoderSession_finish_error(&encoder_session);
379                                         }
380                                         else {
381                                                 unsigned int frames= bytes_read/bytes_per_frame;
382                                                 format_input(input_, frames, true, false, channels, bps);
383
384                                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, frames)) {
385                                                         print_error_with_state(&encoder_session, "ERROR during encoding");
386                                                         return EncoderSession_finish_error(&encoder_session);
387                                                 }
388                                                 else
389                                                         data_bytes-= bytes_read;
390                                         }
391                                 }
392                         }
393
394                         /* now read unaligned samples into reservoir or pad with zeroes if necessary */
395                         if(options.common.sector_align) {
396                                 if(options.common.is_last_file) {
397                                         unsigned int pad_frames= 588U-align_remainder;
398
399                                         if(pad_frames<588U) {
400                                                 unsigned int i;
401
402                                                 info_align_zero= pad_frames;
403                                                 for(i= 0U; i<channels; ++i)
404                                                         memset(input_[i], 0, pad_frames*(bps>>3));
405
406                                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, pad_frames)) {
407                                                         print_error_with_state(&encoder_session, "ERROR during encoding");
408                                                         return EncoderSession_finish_error(&encoder_session);
409                                                 }
410                                         }
411                                 }
412                                 else {
413                                         if(*options.common.align_reservoir_samples > 0) {
414                                                 size_t bytes_read= fread(ucbuffer_, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
415
416                                                 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
417                                                 if(bytes_read==0U && ferror(infile)) {
418                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
419                                                         return EncoderSession_finish_error(&encoder_session);
420                                                 }
421                                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame)
422                                                         fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned int)bytes_read, (unsigned int)encoder_session.total_samples_to_encode, (unsigned int)encoder_session.samples_written);
423                                                 else {
424                                                         info_align_carry= *options.common.align_reservoir_samples;
425                                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, true, false, channels, bps);
426                                                 }
427                                         }
428                                 }
429                         }
430
431                         if(pad==true) {
432                                 unsigned char tmp;
433
434                                 if(fread(&tmp, 1U, 1U, infile)<1U) {
435                                         fprintf(stderr, "%s: ERROR during read of SSND pad byte\n", encoder_session.inbasefilename);
436                                         return EncoderSession_finish_error(&encoder_session);
437                                 }
438                         }
439
440                         got_ssnd_chunk= true;
441                 }
442                 else { /* other chunk */
443                         if(!strncmp(chunk_id, "COMM", 4))
444                                 fprintf(stderr, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_session.inbasefilename);
445                         else if(!strncmp(chunk_id, "SSND", 4))
446                                 fprintf(stderr, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_session.inbasefilename);
447                         else
448                                 fprintf(stderr, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_session.inbasefilename, chunk_id);
449
450                         /* chunk size */
451                         if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
452                                 return EncoderSession_finish_error(&encoder_session);
453                         else {
454                                 unsigned long skip= xx+(xx & 1U);
455
456                                 FLAC__ASSERT(skip<=LONG_MAX);
457                                 while(skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
458                                         unsigned int need= min(skip, sizeof ucbuffer_);
459                                         if(fread(ucbuffer_, 1U, need, infile)<need) {
460                                                 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_session.inbasefilename);
461                                                 return EncoderSession_finish_error(&encoder_session);
462                                         }
463                                         skip-= need;
464                                 }
465                         }
466                 }
467         }
468
469         if(got_ssnd_chunk==false && sample_frames!=0U) {
470                 fprintf(stderr, "%s: ERROR: missing SSND chunk\n", encoder_session.inbasefilename);
471                 return EncoderSession_finish_error(&encoder_session);
472         }
473
474         return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
475 }
476
477 int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
478 {
479         EncoderSession encoder_session;
480         FLAC__bool is_unsigned_samples = false;
481         unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
482         size_t bytes_per_wide_sample, bytes_read;
483         FLAC__uint16 x;
484         FLAC__uint32 xx;
485         FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
486         unsigned align_remainder = 0;
487         int info_align_carry = -1, info_align_zero = -1;
488
489         FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
490
491         (void)infilesize;
492         (void)lookahead;
493         (void)lookahead_length;
494
495         if(!
496                 EncoderSession_construct(
497                         &encoder_session,
498 #ifdef FLAC__HAS_OGG
499                         options.common.use_ogg,
500 #else
501                         /*use_ogg=*/false,
502 #endif
503                         options.common.verify,
504                         options.common.verbose,
505                         infile,
506                         infilename,
507                         outfilename
508                 )
509         )
510                 return 1;
511
512         /*
513          * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
514          */
515         while(!feof(infile)) {
516                 if(!read_little_endian_uint32(infile, &xx, true, encoder_session.inbasefilename))
517                         return EncoderSession_finish_error(&encoder_session);
518                 if(feof(infile))
519                         break;
520                 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
521                         /* fmt sub-chunk size */
522                         if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
523                                 return EncoderSession_finish_error(&encoder_session);
524                         if(xx < 16) {
525                                 fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
526                                 return EncoderSession_finish_error(&encoder_session);
527                         }
528                         else if(xx != 16 && xx != 18) {
529                                 fprintf(stderr, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
530                         }
531                         data_bytes = xx;
532                         /* compression code */
533                         if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
534                                 return EncoderSession_finish_error(&encoder_session);
535                         if(x != 1) {
536                                 fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_session.inbasefilename, (unsigned)x);
537                                 return EncoderSession_finish_error(&encoder_session);
538                         }
539                         /* number of channels */
540                         if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
541                                 return EncoderSession_finish_error(&encoder_session);
542                         if(x == 0 || x > FLAC__MAX_CHANNELS) {
543                                 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned)x);
544                                 return EncoderSession_finish_error(&encoder_session);
545                         }
546                         else if(options.common.sector_align && x != 2) {
547                                 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
548                                 return EncoderSession_finish_error(&encoder_session);
549                         }
550                         channels = x;
551                         /* sample rate */
552                         if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
553                                 return EncoderSession_finish_error(&encoder_session);
554                         if(!FLAC__format_sample_rate_is_valid(xx)) {
555                                 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned)xx);
556                                 return EncoderSession_finish_error(&encoder_session);
557                         }
558                         else if(options.common.sector_align && xx != 44100) {
559                                 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned)xx);
560                                 return EncoderSession_finish_error(&encoder_session);
561                         }
562                         sample_rate = xx;
563                         /* avg bytes per second (ignored) */
564                         if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
565                                 return EncoderSession_finish_error(&encoder_session);
566                         /* block align (ignored) */
567                         if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
568                                 return EncoderSession_finish_error(&encoder_session);
569                         /* bits per sample */
570                         if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
571                                 return EncoderSession_finish_error(&encoder_session);
572                         if(x != 8 && x != 16 && x != 24) {
573                                 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned)x);
574                                 return EncoderSession_finish_error(&encoder_session);
575                         }
576                         else if(options.common.sector_align && x != 16) {
577                                 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
578                                 return EncoderSession_finish_error(&encoder_session);
579                         }
580                         bps = x;
581                         is_unsigned_samples = (x == 8);
582
583                         /* skip any extra data in the fmt sub-chunk */
584                         data_bytes -= 16;
585                         if(data_bytes > 0) {
586                                 unsigned left, need;
587                                 for(left = data_bytes; left > 0; ) {
588                                         need = min(left, CHUNK_OF_SAMPLES);
589                                         if(fread(ucbuffer_, 1U, need, infile) < need) {
590                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
591                                                 return EncoderSession_finish_error(&encoder_session);
592                                         }
593                                         left -= need;
594                                 }
595                         }
596
597                         got_fmt_chunk = true;
598                 }
599                 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
600                         /* data size */
601                         if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
602                                 return EncoderSession_finish_error(&encoder_session);
603                         data_bytes = xx;
604
605                         bytes_per_wide_sample = channels * (bps >> 3);
606
607                         if(options.common.skip > 0) {
608                                 if(fseek(infile, bytes_per_wide_sample * (unsigned)options.common.skip, SEEK_CUR) < 0) {
609                                         /* can't seek input, read ahead manually... */
610                                         unsigned left, need;
611                                         for(left = (unsigned)options.common.skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
612                                                 need = min(left, CHUNK_OF_SAMPLES);
613                                                 if(fread(ucbuffer_, bytes_per_wide_sample, need, infile) < need) {
614                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
615                                                         return EncoderSession_finish_error(&encoder_session);
616                                                 }
617                                                 left -= need;
618                                         }
619                                 }
620                         }
621
622                         data_bytes -= (unsigned)options.common.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
623                         encoder_session.total_samples_to_encode = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
624                         if(options.common.sector_align) {
625                                 align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
626                                 if(options.common.is_last_file)
627                                         encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
628                                 else
629                                         encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
630                         }
631
632                         /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
633                         encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample + 44;
634
635                         if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
636                                 return EncoderSession_finish_error(&encoder_session);
637
638                         /*
639                          * first do any samples in the reservoir
640                          */
641                         if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
642                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
643                                         print_error_with_state(&encoder_session, "ERROR during encoding");
644                                         return EncoderSession_finish_error(&encoder_session);
645                                 }
646                         }
647
648                         /*
649                          * decrement the data_bytes counter if we need to align the file
650                          */
651                         if(options.common.sector_align) {
652                                 if(options.common.is_last_file) {
653                                         *options.common.align_reservoir_samples = 0;
654                                 }
655                                 else {
656                                         *options.common.align_reservoir_samples = align_remainder;
657                                         data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
658                                 }
659                         }
660
661                         /*
662                          * now do from the file
663                          */
664                         while(data_bytes > 0) {
665                                 bytes_read = fread(ucbuffer_, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
666                                 if(bytes_read == 0) {
667                                         if(ferror(infile)) {
668                                                 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
669                                                 return EncoderSession_finish_error(&encoder_session);
670                                         }
671                                         else if(feof(infile)) {
672                                                 fprintf(stderr, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
673                                                 data_bytes = 0;
674                                         }
675                                 }
676                                 else {
677                                         if(bytes_read % bytes_per_wide_sample != 0) {
678                                                 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
679                                                 return EncoderSession_finish_error(&encoder_session);
680                                         }
681                                         else {
682                                                 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
683                                                 format_input(input_, wide_samples, false, is_unsigned_samples, channels, bps);
684
685                                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
686                                                         print_error_with_state(&encoder_session, "ERROR during encoding");
687                                                         return EncoderSession_finish_error(&encoder_session);
688                                                 }
689                                                 data_bytes -= bytes_read;
690                                         }
691                                 }
692                         }
693
694                         /*
695                          * now read unaligned samples into reservoir or pad with zeroes if necessary
696                          */
697                         if(options.common.sector_align) {
698                                 if(options.common.is_last_file) {
699                                         unsigned wide_samples = 588 - align_remainder;
700                                         if(wide_samples < 588) {
701                                                 unsigned channel;
702
703                                                 info_align_zero = wide_samples;
704                                                 data_bytes = wide_samples * (bps >> 3);
705                                                 for(channel = 0; channel < channels; channel++)
706                                                         memset(input_[channel], 0, data_bytes);
707
708                                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
709                                                         print_error_with_state(&encoder_session, "ERROR during encoding");
710                                                         return EncoderSession_finish_error(&encoder_session);
711                                                 }
712                                         }
713                                 }
714                                 else {
715                                         if(*options.common.align_reservoir_samples > 0) {
716                                                 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
717                                                 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
718                                                 if(bytes_read == 0 && ferror(infile)) {
719                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
720                                                         return EncoderSession_finish_error(&encoder_session);
721                                                 }
722                                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
723                                                         fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
724                                                         data_bytes = 0;
725                                                 }
726                                                 else {
727                                                         info_align_carry = *options.common.align_reservoir_samples;
728                                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, is_unsigned_samples, channels, bps);
729                                                 }
730                                         }
731                                 }
732                         }
733
734                         got_data_chunk = true;
735                 }
736                 else {
737                         if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
738                                 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_session.inbasefilename);
739                         }
740                         else if(xx == 0x61746164) { /* "data" */
741                                 if(got_data_chunk) {
742                                         fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_session.inbasefilename);
743                                 }
744                                 else if(!got_fmt_chunk) {
745                                         fprintf(stderr, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_session.inbasefilename);
746                                         return EncoderSession_finish_error(&encoder_session);
747                                 }
748                                 else {
749                                         FLAC__ASSERT(0);
750                                 }
751                         }
752                         else {
753                                 fprintf(stderr, "%s: WARNING: skipping unknown sub-chunk '%c%c%c%c'\n", encoder_session.inbasefilename, (char)(xx&255), (char)((xx>>8)&255), (char)((xx>>16)&255), (char)(xx>>24));
754                         }
755                         /* sub-chunk size */
756                         if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
757                                 return EncoderSession_finish_error(&encoder_session);
758                         if(fseek(infile, xx, SEEK_CUR) < 0) {
759                                 /* can't seek input, read ahead manually... */
760                                 unsigned left, need;
761                                 const unsigned chunk = sizeof(ucbuffer_);
762                                 for(left = xx; left > 0; ) {
763                                         need = min(left, chunk);
764                                         if(fread(ucbuffer_, 1, need, infile) < need) {
765                                                 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_session.inbasefilename);
766                                                 return EncoderSession_finish_error(&encoder_session);
767                                         }
768                                         left -= need;
769                                 }
770                         }
771                 }
772         }
773
774         return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
775 }
776
777 int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, raw_encode_options_t options)
778 {
779         EncoderSession encoder_session;
780         size_t bytes_read;
781         const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
782         unsigned align_remainder = 0;
783         int info_align_carry = -1, info_align_zero = -1;
784
785         FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
786         FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
787         FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
788         FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
789         FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
790         FLAC__ASSERT(!options.common.replay_gain || options.common.skip == 0);
791         FLAC__ASSERT(!options.common.replay_gain || options.channels <= 2);
792         FLAC__ASSERT(!options.common.replay_gain || grabbag__replaygain_is_valid_sample_frequency(options.sample_rate));
793
794         if(!
795                 EncoderSession_construct(
796                         &encoder_session,
797 #ifdef FLAC__HAS_OGG
798                         options.common.use_ogg,
799 #else
800                         /*use_ogg=*/false,
801 #endif
802                         options.common.verify,
803                         options.common.verbose,
804                         infile,
805                         infilename,
806                         outfilename
807                 )
808         )
809                 return 1;
810
811         /* get the file length */
812         if(infilesize < 0) {
813                 encoder_session.total_samples_to_encode = encoder_session.unencoded_size = 0;
814         }
815         else {
816                 if(options.common.sector_align) {
817                         FLAC__ASSERT(options.common.skip == 0);
818                         encoder_session.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
819                         align_remainder = (unsigned)(encoder_session.total_samples_to_encode % 588);
820                         if(options.common.is_last_file)
821                                 encoder_session.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
822                         else
823                                 encoder_session.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
824                 }
825                 else {
826                         encoder_session.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - options.common.skip;
827                 }
828
829                 encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
830         }
831
832         if(encoder_session.verbose && encoder_session.total_samples_to_encode <= 0)
833                 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
834
835         if(options.common.skip > 0) {
836                 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)options.common.skip;
837                 if(skip_bytes > lookahead_length) {
838                         skip_bytes -= lookahead_length;
839                         lookahead_length = 0;
840                         if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
841                                 /* can't seek input, read ahead manually... */
842                                 unsigned left, need;
843                                 const unsigned chunk = sizeof(ucbuffer_);
844                                 for(left = skip_bytes; left > 0; ) {
845                                         need = min(left, chunk);
846                                         if(fread(ucbuffer_, 1, need, infile) < need) {
847                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
848                                                 return EncoderSession_finish_error(&encoder_session);
849                                         }
850                                         left -= need;
851                                 }
852                         }
853                 }
854                 else {
855                         lookahead += skip_bytes;
856                         lookahead_length -= skip_bytes;
857                 }
858         }
859
860         if(!EncoderSession_init_encoder(&encoder_session, options.common, options.channels, options.bps, options.sample_rate))
861                 return EncoderSession_finish_error(&encoder_session);
862
863         /*
864          * first do any samples in the reservoir
865          */
866         if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
867                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
868                         print_error_with_state(&encoder_session, "ERROR during encoding");
869                         return EncoderSession_finish_error(&encoder_session);
870                 }
871         }
872
873         /*
874          * decrement infilesize if we need to align the file
875          */
876         if(options.common.sector_align) {
877                 FLAC__ASSERT(infilesize >= 0);
878                 if(options.common.is_last_file) {
879                         *options.common.align_reservoir_samples = 0;
880                 }
881                 else {
882                         *options.common.align_reservoir_samples = align_remainder;
883                         infilesize -= (long)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
884                 }
885         }
886
887         /*
888          * now do from the file
889          */
890         while(!feof(infile)) {
891                 if(lookahead_length > 0) {
892                         FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
893                         memcpy(ucbuffer_, lookahead, lookahead_length);
894                         bytes_read = fread(ucbuffer_+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
895                         if(ferror(infile)) {
896                                 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
897                                 return EncoderSession_finish_error(&encoder_session);
898                         }
899                         lookahead_length = 0;
900                 }
901                 else
902                         bytes_read = fread(ucbuffer_, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
903
904                 if(bytes_read == 0) {
905                         if(ferror(infile)) {
906                                 fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
907                                 return EncoderSession_finish_error(&encoder_session);
908                         }
909                 }
910                 else if(bytes_read % bytes_per_wide_sample != 0) {
911                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_session.inbasefilename);
912                         return EncoderSession_finish_error(&encoder_session);
913                 }
914                 else {
915                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
916                         format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
917
918                         if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
919                                 print_error_with_state(&encoder_session, "ERROR during encoding");
920                                 return EncoderSession_finish_error(&encoder_session);
921                         }
922                 }
923         }
924
925         /*
926          * now read unaligned samples into reservoir or pad with zeroes if necessary
927          */
928         if(options.common.sector_align) {
929                 if(options.common.is_last_file) {
930                         unsigned wide_samples = 588 - align_remainder;
931                         if(wide_samples < 588) {
932                                 unsigned channel, data_bytes;
933
934                                 info_align_zero = wide_samples;
935                                 data_bytes = wide_samples * (options.bps >> 3);
936                                 for(channel = 0; channel < options.channels; channel++)
937                                         memset(input_[channel], 0, data_bytes);
938
939                                 if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
940                                         print_error_with_state(&encoder_session, "ERROR during encoding");
941                                         return EncoderSession_finish_error(&encoder_session);
942                                 }
943                         }
944                 }
945                 else {
946                         if(*options.common.align_reservoir_samples > 0) {
947                                 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
948                                 bytes_read = fread(ucbuffer_, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
949                                 if(bytes_read == 0 && ferror(infile)) {
950                                         fprintf(stderr, "%s: ERROR during read\n", encoder_session.inbasefilename);
951                                         return EncoderSession_finish_error(&encoder_session);
952                                 }
953                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
954                                         fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
955                                 }
956                                 else {
957                                         info_align_carry = *options.common.align_reservoir_samples;
958                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, options.is_unsigned_samples, options.channels, options.bps);
959                                 }
960                         }
961                 }
962         }
963
964         return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
965 }
966
967 FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FLAC__bool verbose, FILE *infile, const char *infilename, const char *outfilename)
968 {
969         unsigned i;
970         FLAC__uint32 test = 1;
971
972         /*
973          * initialize globals
974          */
975
976         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
977
978         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
979                 input_[i] = &(in_[i][0]);
980
981
982         /*
983          * initialize instance
984          */
985
986 #ifdef FLAC__HAS_OGG
987         e->use_ogg = use_ogg;
988 #else
989         (void)use_ogg;
990 #endif
991         e->verify = verify;
992         e->verbose = verbose;
993
994         e->is_stdout = (0 == strcmp(outfilename, "-"));
995
996         e->inbasefilename = grabbag__file_get_basename(infilename);
997         e->outfilename = outfilename;
998
999         e->unencoded_size = 0;
1000         e->total_samples_to_encode = 0;
1001         e->bytes_written = 0;
1002         e->samples_written = 0;
1003         e->blocksize = 0;
1004         e->stats_mask = 0;
1005
1006         e->encoder.flac.stream = 0;
1007         e->encoder.flac.file = 0;
1008 #ifdef FLAC__HAS_OGG
1009         e->encoder.ogg.stream = 0;
1010 #endif
1011
1012         e->fin = infile;
1013         e->fout = 0;
1014         e->seek_table_template = 0;
1015
1016         if(e->is_stdout) {
1017                 e->fout = grabbag__file_get_binary_stdout();
1018         }
1019 #ifdef FLAC__HAS_OGG
1020         else {
1021                 if(e->use_ogg) {
1022                         if(0 == (e->fout = fopen(outfilename, "wb"))) {
1023                                 fprintf(stderr, "%s: ERROR: can't open output file %s\n", e->inbasefilename, outfilename);
1024                                 EncoderSession_destroy(e);
1025                                 return false;
1026                         }
1027                 }
1028         }
1029 #endif
1030
1031         if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1032                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1033                 return false;
1034         }
1035
1036 #ifdef FLAC__HAS_OGG
1037         if(e->use_ogg) {
1038                 e->encoder.ogg.stream = OggFLAC__stream_encoder_new();
1039                 if(0 == e->encoder.ogg.stream) {
1040                         fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1041                         EncoderSession_destroy(e);
1042                         return false;
1043                 }
1044         }
1045         else
1046 #endif
1047         if(e->is_stdout) {
1048                 e->encoder.flac.stream = FLAC__stream_encoder_new();
1049                 if(0 == e->encoder.flac.stream) {
1050                         fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1051                         EncoderSession_destroy(e);
1052                         return false;
1053                 }
1054         }
1055         else {
1056                 e->encoder.flac.file = FLAC__file_encoder_new();
1057                 if(0 == e->encoder.flac.file) {
1058                         fprintf(stderr, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1059                         EncoderSession_destroy(e);
1060                         return false;
1061                 }
1062         }
1063
1064         return true;
1065 }
1066
1067 void EncoderSession_destroy(EncoderSession *e)
1068 {
1069         if(e->fin != stdin)
1070                 fclose(e->fin);
1071
1072 #ifdef FLAC__HAS_OGG
1073         if(e->use_ogg) {
1074                 if(0 != e->encoder.ogg.stream) {
1075                         OggFLAC__stream_encoder_delete(e->encoder.ogg.stream);
1076                         e->encoder.ogg.stream = 0;
1077                 }
1078         }
1079         else
1080 #endif
1081         if(e->is_stdout) {
1082                 if(0 != e->encoder.flac.stream) {
1083                         FLAC__stream_encoder_delete(e->encoder.flac.stream);
1084                         e->encoder.flac.stream = 0;
1085                 }
1086         }
1087         else {
1088                 if(0 != e->encoder.flac.file) {
1089                         FLAC__file_encoder_delete(e->encoder.flac.file);
1090                         e->encoder.flac.file = 0;
1091                 }
1092         }
1093
1094         if(0 != e->seek_table_template) {
1095                 FLAC__metadata_object_delete(e->seek_table_template);
1096                 e->seek_table_template = 0;
1097         }
1098 }
1099
1100 int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero)
1101 {
1102         FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1103         int ret = 0;
1104
1105 #ifdef FLAC__HAS_OGG
1106         if(e->use_ogg) {
1107                 if(e->encoder.ogg.stream) {
1108                         fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1109                         OggFLAC__stream_encoder_finish(e->encoder.ogg.stream);
1110                 }
1111         }
1112         else
1113 #endif
1114         if(e->is_stdout) {
1115                 if(e->encoder.flac.stream) {
1116                         fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1117                         FLAC__stream_encoder_finish(e->encoder.flac.stream);
1118                 }
1119         }
1120         else {
1121                 if(e->encoder.flac.file) {
1122                         fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1123                         FLAC__file_encoder_finish(e->encoder.flac.file);
1124                 }
1125         }
1126
1127         if(e->verbose && e->total_samples_to_encode > 0) {
1128                 print_stats(e);
1129                 fprintf(stderr, "\n");
1130         }
1131
1132         if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
1133                 print_verify_error(e);
1134                 ret = 1;
1135         }
1136         else {
1137                 if(info_align_carry >= 0)
1138                         fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", e->inbasefilename, info_align_carry);
1139                 if(info_align_zero >= 0)
1140                         fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", e->inbasefilename, info_align_zero);
1141         }
1142
1143         EncoderSession_destroy(e);
1144
1145         return ret;
1146 }
1147
1148 int EncoderSession_finish_error(EncoderSession *e)
1149 {
1150         FLAC__StreamEncoderState fse_state;
1151
1152         if(e->verbose && e->total_samples_to_encode > 0)
1153                 fprintf(stderr, "\n");
1154
1155 #ifdef FLAC__HAS_OGG
1156         if(e->use_ogg) {
1157                 fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1158         }
1159         else
1160 #endif
1161         if(e->is_stdout) {
1162                 fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1163         }
1164         else {
1165                 fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1166         }
1167
1168         if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1169                 print_verify_error(e);
1170         else
1171                 unlink(e->outfilename);
1172
1173         EncoderSession_destroy(e);
1174
1175         return 1;
1176 }
1177
1178 FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate)
1179 {
1180         unsigned num_metadata;
1181         FLAC__StreamMetadata padding;
1182         FLAC__StreamMetadata *metadata[3];
1183
1184         e->replay_gain = options.replay_gain;
1185         e->channels = channels;
1186         e->bits_per_sample = bps;
1187         e->sample_rate = sample_rate;
1188
1189         if(e->replay_gain) {
1190                 if(channels != 1 && channels != 2) {
1191                         fprintf(stderr, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1192                         return false;
1193                 }
1194                 if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) {
1195                         fprintf(stderr, "%s: ERROR, invalid sample rate (%u) for --replay-gain\n", e->inbasefilename, sample_rate);
1196                         return false;
1197                 }
1198                 if(options.is_first_file) {
1199                         if(!grabbag__replaygain_init(sample_rate)) {
1200                                 fprintf(stderr, "%s: ERROR initializing ReplayGain stage\n", e->inbasefilename);
1201                                 return false;
1202                         }
1203                 }
1204         }
1205
1206         if(channels != 2)
1207                 options.do_mid_side = options.loose_mid_side = false;
1208
1209         if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, e)) {
1210                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1211                 return false;
1212         }
1213
1214         num_metadata = 0;
1215         metadata[num_metadata++] = options.vorbis_comment;
1216         if(e->seek_table_template->data.seek_table.num_points > 0) {
1217                 e->seek_table_template->is_last = false; /* the encoder will set this for us */
1218                 metadata[num_metadata++] = e->seek_table_template;
1219         }
1220         if(options.padding > 0) {
1221                 padding.is_last = false; /* the encoder will set this for us */
1222                 padding.type = FLAC__METADATA_TYPE_PADDING;
1223                 padding.length = (unsigned)options.padding;
1224                 metadata[num_metadata++] = &padding;
1225         }
1226
1227         e->blocksize = options.blocksize;
1228         e->stats_mask = (options.do_exhaustive_model_search || options.do_qlp_coeff_prec_search)? 0x0f : 0x3f;
1229
1230 #ifdef FLAC__HAS_OGG
1231         if(e->use_ogg) {
1232                 if(options.has_serial_number)
1233                         OggFLAC__stream_encoder_set_serial_number(e->encoder.ogg.stream, options.serial_number);
1234                 OggFLAC__stream_encoder_set_verify(e->encoder.ogg.stream, options.verify);
1235                 OggFLAC__stream_encoder_set_streamable_subset(e->encoder.ogg.stream, !options.lax);
1236                 OggFLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.ogg.stream, options.do_mid_side);
1237                 OggFLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.ogg.stream, options.loose_mid_side);
1238                 OggFLAC__stream_encoder_set_channels(e->encoder.ogg.stream, channels);
1239                 OggFLAC__stream_encoder_set_bits_per_sample(e->encoder.ogg.stream, bps);
1240                 OggFLAC__stream_encoder_set_sample_rate(e->encoder.ogg.stream, sample_rate);
1241                 OggFLAC__stream_encoder_set_blocksize(e->encoder.ogg.stream, options.blocksize);
1242                 OggFLAC__stream_encoder_set_max_lpc_order(e->encoder.ogg.stream, options.max_lpc_order);
1243                 OggFLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.ogg.stream, options.qlp_coeff_precision);
1244                 OggFLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg.stream, options.do_qlp_coeff_prec_search);
1245                 OggFLAC__stream_encoder_set_do_escape_coding(e->encoder.ogg.stream, options.do_escape_coding);
1246                 OggFLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.ogg.stream, options.do_exhaustive_model_search);
1247                 OggFLAC__stream_encoder_set_min_residual_partition_order(e->encoder.ogg.stream, options.min_residual_partition_order);
1248                 OggFLAC__stream_encoder_set_max_residual_partition_order(e->encoder.ogg.stream, options.max_residual_partition_order);
1249                 OggFLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.ogg.stream, options.rice_parameter_search_dist);
1250                 OggFLAC__stream_encoder_set_total_samples_estimate(e->encoder.ogg.stream, e->total_samples_to_encode);
1251                 OggFLAC__stream_encoder_set_metadata(e->encoder.ogg.stream, (num_metadata > 0)? metadata : 0, num_metadata);
1252                 OggFLAC__stream_encoder_set_write_callback(e->encoder.ogg.stream, ogg_stream_encoder_write_callback);
1253                 OggFLAC__stream_encoder_set_client_data(e->encoder.ogg.stream, e);
1254
1255                 OggFLAC__stream_encoder_disable_constant_subframes(e->encoder.ogg.stream, options.debug.disable_constant_subframes);
1256                 OggFLAC__stream_encoder_disable_fixed_subframes(e->encoder.ogg.stream, options.debug.disable_fixed_subframes);
1257                 OggFLAC__stream_encoder_disable_verbatim_subframes(e->encoder.ogg.stream, options.debug.disable_verbatim_subframes);
1258
1259                 if(OggFLAC__stream_encoder_init(e->encoder.ogg.stream) != FLAC__STREAM_ENCODER_OK) {
1260                         print_error_with_state(e, "ERROR initializing encoder");
1261                         return false;
1262                 }
1263         }
1264         else
1265 #endif
1266         if(e->is_stdout) {
1267                 FLAC__stream_encoder_set_verify(e->encoder.flac.stream, options.verify);
1268                 FLAC__stream_encoder_set_streamable_subset(e->encoder.flac.stream, !options.lax);
1269                 FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.flac.stream, options.do_mid_side);
1270                 FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.flac.stream, options.loose_mid_side);
1271                 FLAC__stream_encoder_set_channels(e->encoder.flac.stream, channels);
1272                 FLAC__stream_encoder_set_bits_per_sample(e->encoder.flac.stream, bps);
1273                 FLAC__stream_encoder_set_sample_rate(e->encoder.flac.stream, sample_rate);
1274                 FLAC__stream_encoder_set_blocksize(e->encoder.flac.stream, options.blocksize);
1275                 FLAC__stream_encoder_set_max_lpc_order(e->encoder.flac.stream, options.max_lpc_order);
1276                 FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.flac.stream, options.qlp_coeff_precision);
1277                 FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.stream, options.do_qlp_coeff_prec_search);
1278                 FLAC__stream_encoder_set_do_escape_coding(e->encoder.flac.stream, options.do_escape_coding);
1279                 FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.flac.stream, options.do_exhaustive_model_search);
1280                 FLAC__stream_encoder_set_min_residual_partition_order(e->encoder.flac.stream, options.min_residual_partition_order);
1281                 FLAC__stream_encoder_set_max_residual_partition_order(e->encoder.flac.stream, options.max_residual_partition_order);
1282                 FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.flac.stream, options.rice_parameter_search_dist);
1283                 FLAC__stream_encoder_set_total_samples_estimate(e->encoder.flac.stream, e->total_samples_to_encode);
1284                 FLAC__stream_encoder_set_metadata(e->encoder.flac.stream, (num_metadata > 0)? metadata : 0, num_metadata);
1285                 FLAC__stream_encoder_set_write_callback(e->encoder.flac.stream, flac_stream_encoder_write_callback);
1286                 FLAC__stream_encoder_set_metadata_callback(e->encoder.flac.stream, flac_stream_encoder_metadata_callback);
1287                 FLAC__stream_encoder_set_client_data(e->encoder.flac.stream, e);
1288
1289                 FLAC__stream_encoder_disable_constant_subframes(e->encoder.flac.stream, options.debug.disable_constant_subframes);
1290                 FLAC__stream_encoder_disable_fixed_subframes(e->encoder.flac.stream, options.debug.disable_fixed_subframes);
1291                 FLAC__stream_encoder_disable_verbatim_subframes(e->encoder.flac.stream, options.debug.disable_verbatim_subframes);
1292
1293                 if(FLAC__stream_encoder_init(e->encoder.flac.stream) != FLAC__STREAM_ENCODER_OK) {
1294                         print_error_with_state(e, "ERROR initializing encoder");
1295                         return false;
1296                 }
1297         }
1298         else {
1299                 FLAC__file_encoder_set_filename(e->encoder.flac.file, e->outfilename);
1300                 FLAC__file_encoder_set_verify(e->encoder.flac.file, options.verify);
1301                 FLAC__file_encoder_set_streamable_subset(e->encoder.flac.file, !options.lax);
1302                 FLAC__file_encoder_set_do_mid_side_stereo(e->encoder.flac.file, options.do_mid_side);
1303                 FLAC__file_encoder_set_loose_mid_side_stereo(e->encoder.flac.file, options.loose_mid_side);
1304                 FLAC__file_encoder_set_channels(e->encoder.flac.file, channels);
1305                 FLAC__file_encoder_set_bits_per_sample(e->encoder.flac.file, bps);
1306                 FLAC__file_encoder_set_sample_rate(e->encoder.flac.file, sample_rate);
1307                 FLAC__file_encoder_set_blocksize(e->encoder.flac.file, options.blocksize);
1308                 FLAC__file_encoder_set_max_lpc_order(e->encoder.flac.file, options.max_lpc_order);
1309                 FLAC__file_encoder_set_qlp_coeff_precision(e->encoder.flac.file, options.qlp_coeff_precision);
1310                 FLAC__file_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.file, options.do_qlp_coeff_prec_search);
1311                 FLAC__file_encoder_set_do_escape_coding(e->encoder.flac.file, options.do_escape_coding);
1312                 FLAC__file_encoder_set_do_exhaustive_model_search(e->encoder.flac.file, options.do_exhaustive_model_search);
1313                 FLAC__file_encoder_set_min_residual_partition_order(e->encoder.flac.file, options.min_residual_partition_order);
1314                 FLAC__file_encoder_set_max_residual_partition_order(e->encoder.flac.file, options.max_residual_partition_order);
1315                 FLAC__file_encoder_set_rice_parameter_search_dist(e->encoder.flac.file, options.rice_parameter_search_dist);
1316                 FLAC__file_encoder_set_total_samples_estimate(e->encoder.flac.file, e->total_samples_to_encode);
1317                 FLAC__file_encoder_set_metadata(e->encoder.flac.file, (num_metadata > 0)? metadata : 0, num_metadata);
1318                 FLAC__file_encoder_set_progress_callback(e->encoder.flac.file, flac_file_encoder_progress_callback);
1319                 FLAC__file_encoder_set_client_data(e->encoder.flac.file, e);
1320
1321                 FLAC__file_encoder_disable_constant_subframes(e->encoder.flac.file, options.debug.disable_constant_subframes);
1322                 FLAC__file_encoder_disable_fixed_subframes(e->encoder.flac.file, options.debug.disable_fixed_subframes);
1323                 FLAC__file_encoder_disable_verbatim_subframes(e->encoder.flac.file, options.debug.disable_verbatim_subframes);
1324
1325                 if(FLAC__file_encoder_init(e->encoder.flac.file) != FLAC__FILE_ENCODER_OK) {
1326                         print_error_with_state(e, "ERROR initializing encoder");
1327                         return false;
1328                 }
1329         }
1330
1331         return true;
1332 }
1333
1334 FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples)
1335 {
1336         if(e->replay_gain) {
1337                 if(!grabbag__replaygain_analyze(buffer, e->channels==2, e->bits_per_sample, samples))
1338                         fprintf(stderr, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
1339         }
1340
1341 #ifdef FLAC__HAS_OGG
1342         if(e->use_ogg) {
1343                 return OggFLAC__stream_encoder_process(e->encoder.ogg.stream, buffer, samples);
1344         }
1345         else
1346 #endif
1347         if(e->is_stdout) {
1348                 return FLAC__stream_encoder_process(e->encoder.flac.stream, buffer, samples);
1349         }
1350         else {
1351                 return FLAC__file_encoder_process(e->encoder.flac.file, buffer, samples);
1352         }
1353 }
1354
1355 FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, EncoderSession *e)
1356 {
1357         FLAC__bool only_placeholders;
1358         FLAC__bool has_real_points;
1359
1360         if(num_requested_seek_points == 0)
1361                 return true;
1362
1363         if(num_requested_seek_points < 0)
1364                 requested_seek_points = "100x;";
1365
1366         if(e->is_stdout)
1367                 only_placeholders = true;
1368 #ifdef FLAC__HAS_OGG
1369         else if(e->use_ogg)
1370                 only_placeholders = true;
1371 #endif
1372         else
1373                 only_placeholders = false;
1374
1375         if(!grabbag__seektable_convert_specification_to_template(requested_seek_points, only_placeholders, e->total_samples_to_encode, e->sample_rate, e->seek_table_template, &has_real_points))
1376                 return false;
1377
1378         if(has_real_points) {
1379                 if(e->is_stdout)
1380                         fprintf(stderr, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
1381 #ifdef FLAC__HAS_OGG
1382                 else if(e->use_ogg)
1383                         fprintf(stderr, "%s: WARNING, cannot write back seekpoints when encoding to Ogg\n", e->inbasefilename);
1384 #endif
1385         }
1386
1387         return true;
1388 }
1389
1390 void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps)
1391 {
1392         unsigned wide_sample, sample, channel, byte;
1393
1394         if(bps == 8) {
1395                 if(is_unsigned_samples) {
1396                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1397                                 for(channel = 0; channel < channels; channel++, sample++)
1398                                         dest[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
1399                 }
1400                 else {
1401                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1402                                 for(channel = 0; channel < channels; channel++, sample++)
1403                                         dest[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
1404                 }
1405         }
1406         else if(bps == 16) {
1407                 if(is_big_endian != is_big_endian_host_) {
1408                         unsigned char tmp;
1409                         const unsigned bytes = wide_samples * channels * (bps >> 3);
1410                         for(byte = 0; byte < bytes; byte += 2) {
1411                                 tmp = ucbuffer_[byte];
1412                                 ucbuffer_[byte] = ucbuffer_[byte+1];
1413                                 ucbuffer_[byte+1] = tmp;
1414                         }
1415                 }
1416                 if(is_unsigned_samples) {
1417                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1418                                 for(channel = 0; channel < channels; channel++, sample++)
1419                                         dest[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
1420                 }
1421                 else {
1422                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1423                                 for(channel = 0; channel < channels; channel++, sample++)
1424                                         dest[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
1425                 }
1426         }
1427         else if(bps == 24) {
1428                 if(!is_big_endian) {
1429                         unsigned char tmp;
1430                         const unsigned bytes = wide_samples * channels * (bps >> 3);
1431                         for(byte = 0; byte < bytes; byte += 3) {
1432                                 tmp = ucbuffer_[byte];
1433                                 ucbuffer_[byte] = ucbuffer_[byte+2];
1434                                 ucbuffer_[byte+2] = tmp;
1435                         }
1436                 }
1437                 if(is_unsigned_samples) {
1438                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1439                                 for(channel = 0; channel < channels; channel++, sample++) {
1440                                         dest[channel][wide_sample]  = ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1441                                         dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1442                                         dest[channel][wide_sample] |= ucbuffer_[byte++];
1443                                         dest[channel][wide_sample] -= 0x800000;
1444                                 }
1445                 }
1446                 else {
1447                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1448                                 for(channel = 0; channel < channels; channel++, sample++) {
1449                                         dest[channel][wide_sample]  = scbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1450                                         dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1451                                         dest[channel][wide_sample] |= ucbuffer_[byte++];
1452                                 }
1453                 }
1454         }
1455         else {
1456                 FLAC__ASSERT(0);
1457         }
1458 }
1459
1460 #ifdef FLAC__HAS_OGG
1461 FLAC__StreamEncoderWriteStatus ogg_stream_encoder_write_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
1462 {
1463         EncoderSession *encoder_session = (EncoderSession*)client_data;
1464
1465         (void)encoder;
1466
1467         encoder_session->bytes_written += bytes;
1468         /*
1469          * With Ogg FLAC we don't get one write callback per frame and
1470          * we don't have good number for 'samples', so we estimate based
1471          * on the frame number and the knowledge that all blocks (except
1472          * the last) are the same size.
1473          */
1474         (void)samples;
1475         encoder_session->samples_written = (current_frame+1) * encoder_session->blocksize;
1476
1477         if(encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
1478                 print_stats(encoder_session);
1479
1480         if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
1481                 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1482         else
1483                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1484 }
1485 #endif
1486
1487 FLAC__StreamEncoderWriteStatus flac_stream_encoder_write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
1488 {
1489         EncoderSession *encoder_session = (EncoderSession*)client_data;
1490
1491         (void)encoder;
1492
1493         encoder_session->bytes_written += bytes;
1494         encoder_session->samples_written += samples;
1495
1496         if(samples && encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
1497                 print_stats(encoder_session);
1498
1499         if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
1500                 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1501         else
1502                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1503 }
1504
1505 void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1506 {
1507         /*
1508          * Nothing to do; if we get here, we're decoding to stdout, in
1509          * which case we can't seek backwards to write new metadata.
1510          */
1511         (void)encoder, (void)metadata, (void)client_data;
1512 }
1513
1514 void flac_file_encoder_progress_callback(const FLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
1515 {
1516         EncoderSession *encoder_session = (EncoderSession*)client_data;
1517
1518         (void)encoder, (void)total_frames_estimate;
1519
1520         encoder_session->bytes_written = bytes_written;
1521         encoder_session->samples_written = samples_written;
1522
1523         if(encoder_session->verbose && encoder_session->total_samples_to_encode > 0 && !((frames_written-1) & encoder_session->stats_mask))
1524                 print_stats(encoder_session);
1525 }
1526
1527 void print_stats(const EncoderSession *encoder_session)
1528 {
1529         const FLAC__uint64 samples_written = min(encoder_session->total_samples_to_encode, encoder_session->samples_written);
1530 #if defined _MSC_VER || defined __MINGW32__
1531         /* with VC++ you have to spoon feed it the casting */
1532         const double progress = (double)(FLAC__int64)samples_written / (double)(FLAC__int64)encoder_session->total_samples_to_encode;
1533         const double ratio = (double)(FLAC__int64)encoder_session->bytes_written / ((double)(FLAC__int64)encoder_session->unencoded_size * progress);
1534 #else
1535         const double progress = (double)samples_written / (double)encoder_session->total_samples_to_encode;
1536         const double ratio = (double)encoder_session->bytes_written / ((double)encoder_session->unencoded_size * progress);
1537 #endif
1538
1539         if(samples_written == encoder_session->total_samples_to_encode) {
1540                 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1541                         encoder_session->inbasefilename,
1542                         encoder_session->verify? " Verify OK," : "",
1543                         (unsigned)encoder_session->bytes_written,
1544                         ratio
1545                 );
1546         }
1547         else {
1548                 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_session->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1549         }
1550 }
1551
1552 void print_error_with_state(const EncoderSession *e, const char *message)
1553 {
1554         const int ilen = strlen(e->inbasefilename) + 1;
1555
1556         fprintf(stderr, "\n%s: %s\n", e->inbasefilename, message);
1557
1558 #ifdef FLAC__HAS_OGG
1559         if(e->use_ogg) {
1560                 const OggFLAC__StreamEncoderState ose_state = OggFLAC__stream_encoder_get_state(e->encoder.ogg.stream);
1561                 if(ose_state != OggFLAC__STREAM_ENCODER_FLAC_STREAM_ENCODER_ERROR) {
1562                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ose_state, OggFLAC__StreamEncoderStateString[ose_state]);
1563                 }
1564                 else {
1565                         const FLAC__StreamEncoderState fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1566                         if(fse_state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) {
1567                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fse_state, FLAC__StreamEncoderStateString[fse_state]);
1568                         }
1569                         else {
1570                                 const FLAC__StreamDecoderState fsd_state = OggFLAC__stream_encoder_get_verify_decoder_state(e->encoder.ogg.stream);
1571                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1572                         }
1573                 }
1574         }
1575         else
1576 #endif
1577         if(e->is_stdout) {
1578                 const FLAC__StreamEncoderState fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1579                 if(fse_state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) {
1580                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fse_state, FLAC__StreamEncoderStateString[fse_state]);
1581                 }
1582                 else {
1583                         const FLAC__StreamDecoderState fsd_state = FLAC__stream_encoder_get_verify_decoder_state(e->encoder.flac.stream);
1584                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1585                 }
1586         }
1587         else {
1588                 const FLAC__FileEncoderState ffe_state = FLAC__file_encoder_get_state(e->encoder.flac.file);
1589                 if(ffe_state != FLAC__FILE_ENCODER_SEEKABLE_STREAM_ENCODER_ERROR) {
1590                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)ffe_state, FLAC__FileEncoderStateString[ffe_state]);
1591                 }
1592                 else {
1593                         const FLAC__SeekableStreamEncoderState fsse_state = FLAC__file_encoder_get_seekable_stream_encoder_state(e->encoder.flac.file);
1594                         if(fsse_state != FLAC__SEEKABLE_STREAM_ENCODER_STREAM_ENCODER_ERROR) {
1595                                 fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsse_state, FLAC__SeekableStreamEncoderStateString[fsse_state]);
1596                         }
1597                         else {
1598                                 const FLAC__StreamEncoderState fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1599                                 if(fse_state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) {
1600                                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fse_state, FLAC__StreamEncoderStateString[fse_state]);
1601                                 }
1602                                 else {
1603                                         const FLAC__StreamDecoderState fsd_state = FLAC__file_encoder_get_verify_decoder_state(e->encoder.flac.file);
1604                                         fprintf(stderr, "%*s state = %d:%s\n", ilen, "", (int)fsd_state, FLAC__StreamDecoderStateString[fsd_state]);
1605                                 }
1606                         }
1607                 }
1608         }
1609 }
1610
1611 void print_verify_error(EncoderSession *e)
1612 {
1613         FLAC__uint64 absolute_sample;
1614         unsigned frame_number;
1615         unsigned channel;
1616         unsigned sample;
1617         FLAC__int32 expected;
1618         FLAC__int32 got;
1619
1620 #ifdef FLAC__HAS_OGG
1621         if(e->use_ogg) {
1622                 OggFLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.ogg.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1623         }
1624         else
1625 #endif
1626         if(e->is_stdout) {
1627                 FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.flac.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1628         }
1629         else {
1630                 FLAC__file_encoder_get_verify_decoder_error_stats(e->encoder.flac.file, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1631         }
1632
1633         fprintf(stderr, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
1634         fprintf(stderr, "       Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)absolute_sample, frame_number, channel, sample, expected, got);
1635         fprintf(stderr, "       Please submit a bug report to\n");
1636         fprintf(stderr, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1637         fprintf(stderr, "       Make sure to include an email contact in the comment and/or use the\n");
1638         fprintf(stderr, "       \"Monitor\" feature to monitor the bug status.\n");
1639         fprintf(stderr, "Verify FAILED!  Do not trust %s\n", e->outfilename);
1640 }
1641
1642 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1643 {
1644         size_t bytes_read = fread(val, 1, 2, f);
1645
1646         if(bytes_read == 0) {
1647                 if(!eof_ok) {
1648                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1649                         return false;
1650                 }
1651                 else
1652                         return true;
1653         }
1654         else if(bytes_read < 2) {
1655                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1656                 return false;
1657         }
1658         else {
1659                 if(is_big_endian_host_) {
1660                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1661                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1662                 }
1663                 return true;
1664         }
1665 }
1666
1667 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1668 {
1669         size_t bytes_read = fread(val, 1, 4, f);
1670
1671         if(bytes_read == 0) {
1672                 if(!eof_ok) {
1673                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1674                         return false;
1675                 }
1676                 else
1677                         return true;
1678         }
1679         else if(bytes_read < 4) {
1680                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1681                 return false;
1682         }
1683         else {
1684                 if(is_big_endian_host_) {
1685                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1686                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1687                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1688                 }
1689                 return true;
1690         }
1691 }
1692
1693 FLAC__bool
1694 read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1695 {
1696         unsigned char buf[4];
1697         size_t bytes_read= fread(buf, 1, 2, f);
1698
1699         if(bytes_read==0U && eof_ok)
1700                 return true;
1701         else if(bytes_read<2U) {
1702                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1703                 return false;
1704         }
1705
1706         /* this is independent of host endianness */
1707         *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
1708
1709         return true;
1710 }
1711
1712 FLAC__bool
1713 read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1714 {
1715         unsigned char buf[4];
1716         size_t bytes_read= fread(buf, 1, 4, f);
1717
1718         if(bytes_read==0U && eof_ok)
1719                 return true;
1720         else if(bytes_read<4U) {
1721                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1722                 return false;
1723         }
1724
1725         /* this is independent of host endianness */
1726         *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
1727                 (FLAC__uint32)(buf[2])<<8 | buf[3];
1728
1729         return true;
1730 }
1731
1732 FLAC__bool
1733 read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1734         /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
1735          * convert it into an integral value and store in 'val'.  Return false if only
1736          * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
1737          * false, or if the value is negative, between zero and one, or too large to be
1738          * represented by 'val'; return true otherwise.
1739          */
1740 {
1741         unsigned int i;
1742         unsigned char buf[10];
1743         size_t bytes_read= fread(buf, 1U, 10U, f);
1744         FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
1745         FLAC__int16 shift= 63-e;
1746         FLAC__uint64 p= 0U;
1747
1748         if(bytes_read==0U && eof_ok)
1749                 return true;
1750         else if(bytes_read<10U) {
1751                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1752                 return false;
1753         }
1754         else if((buf[0]>>7)==1U || e<0 || e>63) {
1755                 fprintf(stderr, "%s: ERROR: invalid floating-point value\n", fn);
1756                 return false;
1757         }
1758
1759         for(i= 0U; i<8U; ++i)
1760                 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
1761         *val= (FLAC__uint32)((p>>shift)+(p>>(shift-1) & 0x1));
1762
1763         return true;
1764 }