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