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