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