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