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