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