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