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