~ubuntu-branches/ubuntu/precise/flac/precise-updates

« back to all changes in this revision

Viewing changes to src/flac/encode.c

  • Committer: Bazaar Package Importer
  • Author(s): Joshua Kwan
  • Date: 2007-05-29 22:56:36 UTC
  • mfrom: (1.1.4 upstream)
  • Revision ID: james.westby@ubuntu.com-20070529225636-ljeff8xxip09qaap
Tags: 1.1.4-1
* New upstream release. closes: #405167, #411311
  - libOggFLAC and libOggFLAC++ have been merged into libFLAC, so
    remove their corresponding packages.
  - Because of the API changes required to effect the above, there has
    been yet another soname bump. libflac7 -> libflac8 and
    libflac++5 -> libflac++6. Emails have been dispatched to the
    maintainers of dependent packages.
* Some notes on patches that were removed:
  - 02_stdin_stdout, 06_manpage_mention_utf8_convert: merged upstream
  - 08_manpage_warnings: Upstream has changed the manpage so it defintely
    can't fit in in 80 cols, so just forget about it. We'll live.
  - 05_eof_warnings_are_errors: Upstream decided to add a -w option to
    flac to treat all warnings as errors. I am going to defer to that
    for now, but if people think it's stupid let me know and I'll port
    the patch forward.
  - 04_stack_smasher: was a backport from 1.1.3, so it's obsolete.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* flac - Command-line FLAC encoder/decoder
2
 
 * Copyright (C) 2000,2001,2002,2003,2004,2005  Josh Coalson
 
2
 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3
3
 *
4
4
 * This program is free software; you can redistribute it and/or
5
5
 * modify it under the terms of the GNU General Public License
16
16
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17
17
 */
18
18
 
 
19
#if HAVE_CONFIG_H
 
20
#  include <config.h>
 
21
#endif
 
22
 
19
23
#if defined _WIN32 && !defined __CYGWIN__
20
24
/* where MSVC puts unlink() */
21
25
# include <io.h>
22
26
#else
23
27
# include <unistd.h>
24
28
#endif
 
29
#if defined _MSC_VER || defined __MINGW32__
 
30
#include <sys/types.h> /* for off_t */
 
31
#if _MSC_VER <= 1600 /* @@@ [2G limit] */
 
32
#define fseeko fseek
 
33
#define ftello ftell
 
34
#endif
 
35
#endif
 
36
#include <errno.h>
25
37
#include <limits.h> /* for LONG_MAX */
26
38
#include <math.h> /* for floor() */
27
39
#include <stdio.h> /* for FILE etc. */
28
40
#include <stdlib.h> /* for malloc */
29
 
#include <string.h> /* for strcmp() */
 
41
#include <string.h> /* for strcmp(), strerror( */
30
42
#include "FLAC/all.h"
31
43
#include "share/grabbag.h"
32
44
#include "encode.h"
33
45
 
34
 
#ifdef HAVE_CONFIG_H
35
 
#include <config.h>
36
 
#endif
37
 
 
38
 
#ifdef FLAC__HAS_OGG
39
 
#include "OggFLAC/stream_encoder.h"
40
 
#include "OggFLAC/file_encoder.h"
41
 
#endif
42
 
 
43
46
#ifdef min
44
47
#undef min
45
48
#endif
53
56
#define CHUNK_OF_SAMPLES 2048
54
57
 
55
58
typedef struct {
56
 
#ifdef FLAC__HAS_OGG
 
59
#if FLAC__HAS_OGG
57
60
        FLAC__bool use_ogg;
58
61
#endif
59
62
        FLAC__bool verify;
60
63
        FLAC__bool is_stdout;
 
64
        FLAC__bool outputfile_opened; /* true if we successfully opened the output file and we want it to be deleted if there is an error */
61
65
        const char *inbasefilename;
62
66
        const char *outfilename;
63
67
 
64
68
        FLAC__uint64 skip;
65
69
        FLAC__uint64 until; /* a value of 0 mean end-of-stream (i.e. --until=-0) */
 
70
        FLAC__bool treat_warnings_as_errors;
 
71
        FLAC__bool continue_through_decode_errors;
66
72
        FLAC__bool replay_gain;
67
73
        unsigned channels;
68
74
        unsigned bits_per_sample;
71
77
        FLAC__uint64 total_samples_to_encode;
72
78
        FLAC__uint64 bytes_written;
73
79
        FLAC__uint64 samples_written;
74
 
        unsigned blocksize;
75
80
        unsigned stats_mask;
76
81
 
77
 
        /*
78
 
         * We use *.stream for encoding to stdout
79
 
         * We use *.file for encoding to a regular file
80
 
         */
81
 
        union {
82
 
                union {
83
 
                        FLAC__StreamEncoder *stream;
84
 
                        FLAC__FileEncoder *file;
85
 
                } flac;
86
 
#ifdef FLAC__HAS_OGG
87
 
                union {
88
 
                        OggFLAC__StreamEncoder *stream;
89
 
                        OggFLAC__FileEncoder *file;
90
 
                } ogg;
91
 
#endif
92
 
        } encoder;
 
82
        FLAC__StreamEncoder *encoder;
93
83
 
94
84
        FILE *fin;
95
 
        FILE *fout;
96
85
        FLAC__StreamMetadata *seek_table_template;
97
86
} EncoderSession;
98
87
 
 
88
/* this is data attached to the FLAC decoder when encoding from a FLAC file */
 
89
typedef struct {
 
90
        EncoderSession *encoder_session;
 
91
        off_t filesize;
 
92
        const FLAC__byte *lookahead;
 
93
        unsigned lookahead_length;
 
94
        size_t num_metadata_blocks;
 
95
        FLAC__StreamMetadata *metadata_blocks[1024]; /*@@@ BAD MAGIC number */
 
96
        FLAC__uint64 samples_left_to_process;
 
97
        FLAC__bool fatal_error;
 
98
} FLACDecoderData;
 
99
 
 
100
const int FLAC_ENCODE__DEFAULT_PADDING = 8192;
99
101
 
100
102
static FLAC__bool is_big_endian_host_;
101
103
 
114
116
extern FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
115
117
extern FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
116
118
extern FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value);
117
 
extern FLAC__bool FLAC__file_encoder_disable_constant_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
118
 
extern FLAC__bool FLAC__file_encoder_disable_fixed_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
119
 
extern FLAC__bool FLAC__file_encoder_disable_verbatim_subframes(FLAC__FileEncoder *encoder, FLAC__bool value);
120
 
#ifdef FLAC__HAS_OGG
121
 
extern FLAC__bool OggFLAC__stream_encoder_disable_constant_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
122
 
extern FLAC__bool OggFLAC__stream_encoder_disable_fixed_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
123
 
extern FLAC__bool OggFLAC__stream_encoder_disable_verbatim_subframes(OggFLAC__StreamEncoder *encoder, FLAC__bool value);
124
 
extern FLAC__bool OggFLAC__file_encoder_disable_constant_subframes(OggFLAC__FileEncoder *encoder, FLAC__bool value);
125
 
extern FLAC__bool OggFLAC__file_encoder_disable_fixed_subframes(OggFLAC__FileEncoder *encoder, FLAC__bool value);
126
 
extern FLAC__bool OggFLAC__file_encoder_disable_verbatim_subframes(OggFLAC__FileEncoder *encoder, FLAC__bool value);
127
 
#endif
128
119
 
129
120
/*
130
121
 * local routines
131
122
 */
132
 
static FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FILE *infile, const char *infilename, const char *outfilename);
 
123
static FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FLAC__bool treat_warnings_as_errors, FLAC__bool continue_through_decode_errors, FILE *infile, const char *infilename, const char *outfilename);
133
124
static void EncoderSession_destroy(EncoderSession *e);
134
125
static int EncoderSession_finish_ok(EncoderSession *e, int info_align_carry, int info_align_zero);
135
126
static int EncoderSession_finish_error(EncoderSession *e);
136
 
static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate);
 
127
static FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, FLAC__uint32 channel_mask, unsigned channels, unsigned bps, unsigned sample_rate, FLACDecoderData *flac_decoder_data);
137
128
static FLAC__bool EncoderSession_process(EncoderSession *e, const FLAC__int32 * const buffer[], unsigned samples);
138
129
static FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e);
139
130
static FLAC__bool canonicalize_until_specification(utils__SkipUntilSpecification *spec, const char *inbasefilename, unsigned sample_rate, FLAC__uint64 skip, FLAC__uint64 total_samples_in_input);
140
 
static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps);
141
 
#ifdef FLAC__HAS_OGG
142
 
static FLAC__StreamEncoderWriteStatus ogg_stream_encoder_write_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
143
 
static void ogg_stream_encoder_metadata_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
144
 
static void ogg_file_encoder_progress_callback(const OggFLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
145
 
#endif
146
 
static FLAC__StreamEncoderWriteStatus flac_stream_encoder_write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
147
 
static void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
148
 
static void flac_file_encoder_progress_callback(const FLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
149
 
static FLAC__bool parse_cuesheet_(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset);
 
131
static FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata);
 
132
static FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map);
 
133
static void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
 
134
static FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
 
135
static FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
 
136
static FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
 
137
static FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
 
138
static FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data);
 
139
static FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
 
140
static void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
 
141
static void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
 
142
static FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors);
150
143
static void print_stats(const EncoderSession *encoder_session);
 
144
static void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status);
151
145
static void print_error_with_state(const EncoderSession *e, const char *message);
152
146
static void print_verify_error(EncoderSession *e);
153
147
static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
156
150
static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
157
151
static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
158
152
static FLAC__bool fskip_ahead(FILE *f, FLAC__uint64 offset);
 
153
static unsigned count_channel_mask_bits(FLAC__uint32 mask);
 
154
static FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels);
159
155
 
160
156
/*
161
157
 * public routines
162
158
 */
163
 
int
164
 
flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const char *outfilename,
165
 
        const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
 
159
int flac__encode_aif(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options, FLAC__bool is_aifc)
166
160
{
167
161
        EncoderSession encoder_session;
168
162
        FLAC__uint16 x;
169
163
        FLAC__uint32 xx;
170
 
        unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
 
164
        unsigned int channels= 0U, bps= 0U, shift= 0U, sample_rate= 0U, sample_frames= 0U;
 
165
        size_t channel_map[FLAC__MAX_CHANNELS];
171
166
        FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
172
167
        int info_align_carry= -1, info_align_zero= -1;
 
168
        FLAC__bool is_big_endian_pcm = true;
173
169
 
174
170
        (void)infilesize; /* silence compiler warning about unused parameter */
175
171
        (void)lookahead; /* silence compiler warning about unused parameter */
178
174
        if(!
179
175
                EncoderSession_construct(
180
176
                        &encoder_session,
181
 
#ifdef FLAC__HAS_OGG
 
177
#if FLAC__HAS_OGG
182
178
                        options.common.use_ogg,
183
179
#else
184
180
                        /*use_ogg=*/false,
185
181
#endif
186
182
                        options.common.verify,
 
183
                        options.common.treat_warnings_as_errors,
 
184
                        options.common.continue_through_decode_errors,
187
185
                        infile,
188
186
                        infilename,
189
187
                        outfilename
191
189
        )
192
190
                return 1;
193
191
 
 
192
        /* initialize default channel map that preserves channel order */
 
193
        {
 
194
                size_t i;
 
195
                for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
 
196
                        channel_map[i] = i;
 
197
        }
 
198
 
194
199
        /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
195
200
 
196
201
        while(1) {
197
202
                size_t c= 0U;
198
 
                char chunk_id[4];
 
203
                char chunk_id[5] = { '\0', '\0', '\0', '\0', '\0' }; /* one extra byte for terminating NUL so we can also treat it like a C string */
199
204
 
200
205
                /* chunk identifier; really conservative about behavior of fread() and feof() */
201
206
                if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
205
210
                        return EncoderSession_finish_error(&encoder_session);
206
211
                }
207
212
 
208
 
                if(got_comm_chunk==false && !strncmp(chunk_id, "COMM", 4)) { /* common chunk */
 
213
                if(got_comm_chunk==false && !memcmp(chunk_id, "COMM", 4)) { /* common chunk */
209
214
                        unsigned long skip;
 
215
                        const FLAC__uint32 minimum_comm_size = (is_aifc? 22 : 18);
210
216
 
211
217
                        /* COMM chunk size */
212
218
                        if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
213
219
                                return EncoderSession_finish_error(&encoder_session);
214
 
                        else if(xx<18U) {
215
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
 
220
                        else if(xx<minimum_comm_size) {
 
221
                                flac__utils_printf(stderr, 1, "%s: ERROR: non-standard %s 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx);
216
222
                                return EncoderSession_finish_error(&encoder_session);
217
223
                        }
218
 
                        else if(xx!=18U) {
219
 
                                flac__utils_printf(stderr, 1, "%s: WARNING: non-standard 'COMM' chunk has length = %u\n", encoder_session.inbasefilename, (unsigned int)xx);
 
224
                        else if(!is_aifc && xx!=minimum_comm_size) {
 
225
                                flac__utils_printf(stderr, 1, "%s: WARNING: non-standard %s 'COMM' chunk has length = %u, expected %u\n", encoder_session.inbasefilename, is_aifc? "AIFF-C" : "AIFF", (unsigned int)xx, minimum_comm_size);
 
226
                                if(encoder_session.treat_warnings_as_errors)
 
227
                                        return EncoderSession_finish_error(&encoder_session);
220
228
                        }
221
 
                        skip= (xx-18U)+(xx & 1U);
 
229
                        skip= (xx-minimum_comm_size)+(xx & 1U);
222
230
 
223
231
                        /* number of channels */
224
232
                        if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
227
235
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned int)x);
228
236
                                return EncoderSession_finish_error(&encoder_session);
229
237
                        }
 
238
                        else if(x>2U && !options.common.channel_map_none) {
 
239
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u for AIFF\n", encoder_session.inbasefilename, (unsigned int)x);
 
240
                                return EncoderSession_finish_error(&encoder_session);
 
241
                        }
230
242
                        else if(options.common.sector_align && x!=2U) {
231
243
                                flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
232
244
                                return EncoderSession_finish_error(&encoder_session);
241
253
                        /* bits per sample */
242
254
                        if(!read_big_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
243
255
                                return EncoderSession_finish_error(&encoder_session);
244
 
                        else if(x!=8U && x!=16U && x!=24U) {
245
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits per sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
 
256
                        else if(x<4U || x>24U) {
 
257
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, (unsigned int)x);
246
258
                                return EncoderSession_finish_error(&encoder_session);
247
259
                        }
248
260
                        else if(options.common.sector_align && x!=16U) {
249
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
 
261
                                flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits-per-sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned int)x);
250
262
                                return EncoderSession_finish_error(&encoder_session);
251
263
                        }
252
264
                        bps= x;
 
265
                        shift= (bps%8)? 8-(bps%8) : 0; /* SSND data is always byte-aligned, left-justified but format_input() will double-check */
 
266
                        bps+= shift;
253
267
 
254
268
                        /* sample rate */
255
269
                        if(!read_sane_extended(infile, &xx, false, encoder_session.inbasefilename))
264
278
                        }
265
279
                        sample_rate= xx;
266
280
 
 
281
                        /* check compression type for AIFF-C */
 
282
                        if(is_aifc) {
 
283
                                if(!read_big_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
 
284
                                        return EncoderSession_finish_error(&encoder_session);
 
285
                                if(xx == 0x736F7774) /* "sowt" */
 
286
                                        is_big_endian_pcm = false;
 
287
                                else if(xx == 0x4E4F4E45) /* "NONE" */
 
288
                                        ; /* nothing to do, we already default to big-endian */
 
289
                                else {
 
290
                                        flac__utils_printf(stderr, 1, "%s: ERROR: can't handle AIFF-C compression type \"%c%c%c%c\"\n", encoder_session.inbasefilename, (char)(xx>>24), (char)((xx>>16)&8), (char)((xx>>8)&8), (char)(xx&8));
 
291
                                        return EncoderSession_finish_error(&encoder_session);
 
292
                                }
 
293
                        }
 
294
 
 
295
                        /* set channel mapping */
 
296
                        /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
 
297
                        /* front left, front right, center, LFE, back left, back right, surround left, surround right */
 
298
                        /* specs say the channel ordering is:
 
299
                         *                             1     2   3   4   5   6
 
300
                         * ___________________________________________________
 
301
                         * 2         stereo            l     r
 
302
                         * 3                           l     r   c
 
303
                         * 4                           l     c   r   S
 
304
                         * quad (ambiguous with 4ch)  Fl    Fr   Bl  Br
 
305
                         * 5                          Fl     Fr  Fc  Sl  Sr
 
306
                         * 6                           l     lc  c   r   rc  S
 
307
                         * l:left r:right c:center Fl:front-left Fr:front-right Bl:back-left Br:back-right Lc:left-center Rc:right-center S:surround
 
308
                         * so we only have unambiguous mappings for 2, 3, and 5 channels
 
309
                         */
 
310
                        if(
 
311
                                options.common.channel_map_none ||
 
312
                                channels == 1 || /* 1 channel: (mono) */
 
313
                                channels == 2 || /* 2 channels: left, right */
 
314
                                channels == 3 || /* 3 channels: left, right, center */
 
315
                                channels == 5    /* 5 channels: front left, front right, center, surround left, surround right */
 
316
                        ) {
 
317
                                /* keep default channel order */
 
318
                        }
 
319
                        else {
 
320
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u for AIFF\n", encoder_session.inbasefilename, channels);
 
321
                                return EncoderSession_finish_error(&encoder_session);
 
322
                        }
 
323
 
267
324
                        /* skip any extra data in the COMM chunk */
268
325
                        if(!fskip_ahead(infile, skip)) {
269
326
                                flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra COMM data\n", encoder_session.inbasefilename);
281
338
 
282
339
                        got_comm_chunk= true;
283
340
                }
284
 
                else if(got_ssnd_chunk==false && !strncmp(chunk_id, "SSND", 4)) { /* sound data chunk */
 
341
                else if(got_ssnd_chunk==false && !memcmp(chunk_id, "SSND", 4)) { /* sound data chunk */
285
342
                        unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
286
343
                        size_t bytes_per_frame= channels*(bps>>3);
287
344
                        FLAC__uint64 total_samples_in_input, trim = 0;
365
422
                        /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
366
423
                        encoder_session.unencoded_size= encoder_session.total_samples_to_encode*bytes_per_frame+54;
367
424
 
368
 
                        if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
 
425
                        if(!EncoderSession_init_encoder(&encoder_session, options.common, /*channel_mask=*/0, channels, bps-shift, sample_rate, /*flac_decoder_data=*/0))
369
426
                                return EncoderSession_finish_error(&encoder_session);
370
427
 
371
428
                        /* first do any samples in the reservoir */
398
455
                                        }
399
456
                                        else if(feof(infile)) {
400
457
                                                flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned int)encoder_session.total_samples_to_encode, (unsigned int)encoder_session.samples_written);
 
458
                                                if(encoder_session.treat_warnings_as_errors)
 
459
                                                        return EncoderSession_finish_error(&encoder_session);
401
460
                                                data_bytes= 0;
402
461
                                        }
403
462
                                }
408
467
                                        }
409
468
                                        else {
410
469
                                                unsigned int frames= bytes_read/bytes_per_frame;
411
 
                                                format_input(input_, frames, true, false, channels, bps);
 
470
                                                if(!format_input(input_, frames, is_big_endian_pcm, /*is_unsigned_samples=*/false, channels, bps, shift, channel_map))
 
471
                                                        return EncoderSession_finish_error(&encoder_session);
412
472
 
413
473
                                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, frames)) {
414
474
                                                        print_error_with_state(&encoder_session, "ERROR during encoding");
438
498
 
439
499
                                                info_align_zero= pad_frames;
440
500
                                                for(i= 0U; i<channels; ++i)
441
 
                                                        memset(input_[i], 0, pad_frames*(bps>>3));
 
501
                                                        memset(input_[i], 0, sizeof(input_[0][0])*pad_frames);
442
502
 
443
503
                                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 *const *)input_, pad_frames)) {
444
504
                                                        print_error_with_state(&encoder_session, "ERROR during encoding");
457
517
                                                }
458
518
                                                else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame) {
459
519
                                                        flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned int)bytes_read, (unsigned int)encoder_session.total_samples_to_encode, (unsigned int)encoder_session.samples_written);
 
520
                                                        if(encoder_session.treat_warnings_as_errors)
 
521
                                                                return EncoderSession_finish_error(&encoder_session);
460
522
                                                }
461
523
                                                else {
462
524
                                                        info_align_carry= *options.common.align_reservoir_samples;
463
 
                                                        format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, true, false, channels, bps);
 
525
                                                        if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, is_big_endian_pcm, /*is_unsigned_samples=*/false, channels, bps, shift, channel_map))
 
526
                                                                return EncoderSession_finish_error(&encoder_session);
464
527
                                                }
465
528
                                        }
466
529
                                }
478
541
                        got_ssnd_chunk= true;
479
542
                }
480
543
                else { /* other chunk */
481
 
                        if(!strncmp(chunk_id, "COMM", 4)) {
 
544
                        if(!memcmp(chunk_id, "COMM", 4)) {
482
545
                                flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_session.inbasefilename);
 
546
                                if(encoder_session.treat_warnings_as_errors)
 
547
                                        return EncoderSession_finish_error(&encoder_session);
483
548
                        }
484
 
                        else if(!strncmp(chunk_id, "SSND", 4)) {
 
549
                        else if(!memcmp(chunk_id, "SSND", 4)) {
485
550
                                flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_session.inbasefilename);
 
551
                                if(encoder_session.treat_warnings_as_errors)
 
552
                                        return EncoderSession_finish_error(&encoder_session);
486
553
                        }
487
554
                        else {
488
555
                                flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_session.inbasefilename, chunk_id);
 
556
                                if(encoder_session.treat_warnings_as_errors)
 
557
                                        return EncoderSession_finish_error(&encoder_session);
489
558
                        }
490
559
 
491
560
                        /* chunk size */
511
580
        return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
512
581
}
513
582
 
514
 
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)
 
583
int flac__encode_wav(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
515
584
{
516
585
        EncoderSession encoder_session;
517
586
        FLAC__bool is_unsigned_samples = false;
518
 
        unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
 
587
        unsigned channels = 0, bps = 0, sample_rate = 0, shift = 0;
519
588
        size_t bytes_per_wide_sample, bytes_read;
520
 
        FLAC__uint16 x;
521
 
        FLAC__uint32 xx;
 
589
        size_t channel_map[FLAC__MAX_CHANNELS];
 
590
        FLAC__uint16 x, format; /* format is the wFormatTag word from the 'fmt ' chunk */
 
591
        FLAC__uint32 xx, channel_mask = 0;
522
592
        FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
523
593
        unsigned align_remainder = 0;
524
594
        int info_align_carry = -1, info_align_zero = -1;
530
600
        if(!
531
601
                EncoderSession_construct(
532
602
                        &encoder_session,
533
 
#ifdef FLAC__HAS_OGG
 
603
#if FLAC__HAS_OGG
534
604
                        options.common.use_ogg,
535
605
#else
536
606
                        /*use_ogg=*/false,
537
607
#endif
538
608
                        options.common.verify,
 
609
                        options.common.treat_warnings_as_errors,
 
610
                        options.common.continue_through_decode_errors,
539
611
                        infile,
540
612
                        infilename,
541
613
                        outfilename
543
615
        )
544
616
                return 1;
545
617
 
 
618
        /* initialize default channel map that preserves channel order */
 
619
        {
 
620
                size_t i;
 
621
                for(i = 0; i < sizeof(channel_map)/sizeof(channel_map[0]); i++)
 
622
                        channel_map[i] = i;
 
623
        }
 
624
 
546
625
        /*
547
626
         * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
548
627
         */
552
631
                if(feof(infile))
553
632
                        break;
554
633
                if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
555
 
                        unsigned block_align;
 
634
                        unsigned block_align, data_bytes;
 
635
 
 
636
                        /* see
 
637
                         *   http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
 
638
                         *   http://windowssdk.msdn.microsoft.com/en-us/library/ms713497.aspx
 
639
                         *   http://msdn.microsoft.com/library/default.asp?url=/library/en-us/audio_r/hh/Audio_r/aud-prop_d40f094e-44f9-4baa-8a15-03e4fb369501.xml.asp
 
640
                         *
 
641
                         * WAVEFORMAT is
 
642
                         * 4 byte: subchunk size
 
643
                         * 2 byte: format type: 1 for WAVE_FORMAT_PCM, 65534 for WAVE_FORMAT_EXTENSIBLE
 
644
                         * 2 byte: # channels
 
645
                         * 4 byte: sample rate (Hz)
 
646
                         * 4 byte: avg bytes per sec
 
647
                         * 2 byte: block align
 
648
                         * 2 byte: bits per sample (not necessarily all significant)
 
649
                         * WAVEFORMAT adds
 
650
                         * 2 byte: extension size in bytes (usually 0 for WAVEFORMATEX and 22 for WAVEFORMATEXTENSIBLE with PCM)
 
651
                         * WAVEFORMATEXTENSIBLE adds
 
652
                         * 2 byte: valid bits per sample
 
653
                         * 4 byte: channel mask
 
654
                         * 16 byte: subformat GUID, first 2 bytes have format type, 1 being PCM
 
655
                         *
 
656
                         * Current spec says WAVEFORMATEX with PCM must have bps == 8 or 16, or any multiple of 8 for WAVEFORMATEXTENSIBLE.
 
657
                         * Lots of old broken WAVEs/apps have don't follow it, e.g. 20 bps but a block align of 3/6 for mono/stereo.
 
658
                         *
 
659
                         * Block align for WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE is also supposed to be channels*bps/8
 
660
                         *
 
661
                         * If the channel mask has more set bits than # of channels, the extra MSBs are ignored.
 
662
                         * If the channel mask has less set bits than # of channels, the extra channels are unassigned to any speaker.
 
663
                         *
 
664
                         * Data is supposed to be unsigned for bps <= 8 else signed.
 
665
                         */
556
666
 
557
667
                        /* fmt sub-chunk size */
558
668
                        if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
559
669
                                return EncoderSession_finish_error(&encoder_session);
560
 
                        if(xx < 16) {
561
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
562
 
                                return EncoderSession_finish_error(&encoder_session);
563
 
                        }
564
 
                        else if(xx != 16 && xx != 18) {
565
 
                                flac__utils_printf(stderr, 1, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, (unsigned)xx);
566
 
                        }
567
670
                        data_bytes = xx;
568
 
                        /* compression code */
569
 
                        if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
570
 
                                return EncoderSession_finish_error(&encoder_session);
571
 
                        if(x != 1) {
572
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported compression type %u\n", encoder_session.inbasefilename, (unsigned)x);
 
671
                        if(data_bytes < 16) {
 
672
                                flac__utils_printf(stderr, 1, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_session.inbasefilename, data_bytes);
 
673
                                return EncoderSession_finish_error(&encoder_session);
 
674
                        }
 
675
                        /* format code */
 
676
                        if(!read_little_endian_uint16(infile, &format, false, encoder_session.inbasefilename))
 
677
                                return EncoderSession_finish_error(&encoder_session);
 
678
                        if(format != 1 /*WAVE_FORMAT_PCM*/ && format != 65534 /*WAVE_FORMAT_EXTENSIBLE*/) {
 
679
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported format type %u\n", encoder_session.inbasefilename, (unsigned)format);
573
680
                                return EncoderSession_finish_error(&encoder_session);
574
681
                        }
575
682
                        /* number of channels */
576
683
                        if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
577
684
                                return EncoderSession_finish_error(&encoder_session);
578
 
                        if(x == 0 || x > FLAC__MAX_CHANNELS) {
579
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number channels %u\n", encoder_session.inbasefilename, (unsigned)x);
580
 
                                return EncoderSession_finish_error(&encoder_session);
581
 
                        }
582
 
                        else if(options.common.sector_align && x != 2) {
583
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
584
 
                                return EncoderSession_finish_error(&encoder_session);
585
 
                        }
586
 
                        channels = x;
 
685
                        channels = (unsigned)x;
 
686
                        if(channels == 0 || channels > FLAC__MAX_CHANNELS) {
 
687
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported number of channels %u\n", encoder_session.inbasefilename, channels);
 
688
                                return EncoderSession_finish_error(&encoder_session);
 
689
                        }
 
690
                        else if(options.common.sector_align && channels != 2) {
 
691
                                flac__utils_printf(stderr, 1, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_session.inbasefilename, channels);
 
692
                                return EncoderSession_finish_error(&encoder_session);
 
693
                        }
587
694
                        /* sample rate */
588
695
                        if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
589
696
                                return EncoderSession_finish_error(&encoder_session);
590
 
                        if(!FLAC__format_sample_rate_is_valid(xx)) {
591
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, (unsigned)xx);
592
 
                                return EncoderSession_finish_error(&encoder_session);
593
 
                        }
594
 
                        else if(options.common.sector_align && xx != 44100) {
595
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, (unsigned)xx);
596
 
                                return EncoderSession_finish_error(&encoder_session);
597
 
                        }
598
697
                        sample_rate = xx;
 
698
                        if(!FLAC__format_sample_rate_is_valid(sample_rate)) {
 
699
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported sample rate %u\n", encoder_session.inbasefilename, sample_rate);
 
700
                                return EncoderSession_finish_error(&encoder_session);
 
701
                        }
 
702
                        else if(options.common.sector_align && sample_rate != 44100) {
 
703
                                flac__utils_printf(stderr, 1, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_session.inbasefilename, sample_rate);
 
704
                                return EncoderSession_finish_error(&encoder_session);
 
705
                        }
599
706
                        /* avg bytes per second (ignored) */
600
707
                        if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
601
708
                                return EncoderSession_finish_error(&encoder_session);
602
709
                        /* block align */
603
710
                        if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
604
711
                                return EncoderSession_finish_error(&encoder_session);
605
 
                        block_align = x;
 
712
                        block_align = (unsigned)x;
606
713
                        /* bits per sample */
607
714
                        if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
608
715
                                return EncoderSession_finish_error(&encoder_session);
609
 
                        if(x != 8 && x != 16 && x != 24) {
610
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, (unsigned)x);
611
 
                                return EncoderSession_finish_error(&encoder_session);
612
 
                        }
613
 
                        else if(options.common.sector_align && x != 16) {
614
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, (unsigned)x);
615
 
                                return EncoderSession_finish_error(&encoder_session);
616
 
                        }
617
 
                        bps = x;
618
 
                        if(bps * channels != block_align * 8) {
619
 
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported block alignment (%u), for bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, block_align, bps, channels);
620
 
                                return EncoderSession_finish_error(&encoder_session);
621
 
                        }
622
 
                        is_unsigned_samples = (x == 8);
 
716
                        bps = (unsigned)x;
 
717
                        is_unsigned_samples = (bps <= 8);
 
718
                        if(format == 1) {
 
719
                                if(bps != 8 && bps != 16) {
 
720
                                        if(bps == 24 || bps == 32) {
 
721
                                                /* let these slide with a warning since they're unambiguous */
 
722
                                                flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file has format type %u but bits-per-sample=%u\n", encoder_session.inbasefilename, (unsigned)format, bps);
 
723
                                                if(encoder_session.treat_warnings_as_errors)
 
724
                                                        return EncoderSession_finish_error(&encoder_session);
 
725
                                        }
 
726
                                        else {
 
727
                                                /* @@@ we could add an option to specify left- or right-justified blocks so we knew how to set 'shift' */
 
728
                                                flac__utils_printf(stderr, 1, "%s: ERROR: legacy WAVE file has format type %u but bits-per-sample=%u\n", encoder_session.inbasefilename, (unsigned)format, bps);
 
729
                                                return EncoderSession_finish_error(&encoder_session);
 
730
                                        }
 
731
                                }
 
732
#if 0 /* @@@ reinstate once we can get an answer about whether the samples are left- or right-justified */
 
733
                                if((bps+7)/8 * channels == block_align) {
 
734
                                        if(bps % 8) {
 
735
                                                /* assume legacy file is byte aligned with some LSBs zero; this is double-checked in format_input() */
 
736
                                                flac__utils_printf(stderr, 1, "%s: WARNING: legacy WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, (unsigned)format, block_align, bps, channels);
 
737
                                                if(encoder_session.treat_warnings_as_errors)
 
738
                                                        return EncoderSession_finish_error(&encoder_session);
 
739
                                                shift = 8 - (bps % 8);
 
740
                                                bps += shift;
 
741
                                        }
 
742
                                        else
 
743
                                                shift = 0;
 
744
                                }
 
745
                                else {
 
746
                                        flac__utils_printf(stderr, 1, "%s: ERROR: illegal WAVE file (format type %d) has block alignment=%u, bits-per-sample=%u, channels=%u\n", encoder_session.inbasefilename, (unsigned)format, block_align, bps, channels);
 
747
                                        return EncoderSession_finish_error(&encoder_session);
 
748
                                }
 
749
#else
 
750
                                shift = 0;
 
751
#endif
 
752
                                if(channels > 2 && !options.common.channel_map_none) {
 
753
                                        flac__utils_printf(stderr, 1, "%s: ERROR: WAVE has >2 channels but is not WAVE_FORMAT_EXTENSIBLE; cannot assign channels\n", encoder_session.inbasefilename);
 
754
                                        return EncoderSession_finish_error(&encoder_session);
 
755
                                }
 
756
                                FLAC__ASSERT(data_bytes >= 16);
 
757
                                data_bytes -= 16;
 
758
                        }
 
759
                        else {
 
760
                                if(data_bytes < 40) {
 
761
                                        flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with size %u\n", encoder_session.inbasefilename, data_bytes);
 
762
                                        return EncoderSession_finish_error(&encoder_session);
 
763
                                }
 
764
                                /* cbSize */
 
765
                                if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
 
766
                                        return EncoderSession_finish_error(&encoder_session);
 
767
                                if(x < 22) {
 
768
                                        flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with cbSize %u\n", encoder_session.inbasefilename, (unsigned)x);
 
769
                                        return EncoderSession_finish_error(&encoder_session);
 
770
                                }
 
771
                                /* valid bps */
 
772
                                if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
 
773
                                        return EncoderSession_finish_error(&encoder_session);
 
774
                                if((unsigned)x > bps) {
 
775
                                        flac__utils_printf(stderr, 1, "%s: ERROR: invalid WAVEFORMATEXTENSIBLE chunk with wValidBitsPerSample (%u) > wBitsPerSample (%u)\n", encoder_session.inbasefilename, (unsigned)x, bps);
 
776
                                        return EncoderSession_finish_error(&encoder_session);
 
777
                                }
 
778
                                shift = bps - (unsigned)x;
 
779
                                /* channel mask */
 
780
                                if(!read_little_endian_uint32(infile, &channel_mask, false, encoder_session.inbasefilename))
 
781
                                        return EncoderSession_finish_error(&encoder_session);
 
782
                                /* for mono/stereo and unassigned channels, we fake the mask */
 
783
                                if(channel_mask == 0) {
 
784
                                        if(channels == 1)
 
785
                                                channel_mask = 0x0001;
 
786
                                        else if(channels == 2)
 
787
                                                channel_mask = 0x0003;
 
788
                                }
 
789
                                /* set channel mapping */
 
790
                                /* FLAC order follows SMPTE and WAVEFORMATEXTENSIBLE but with fewer channels, which are: */
 
791
                                /* front left, front right, center, LFE, back left, back right, surround left, surround right */
 
792
                                /* the default mapping is sufficient for 1-6 channels and 7-8 are currently unspecified anyway */
 
793
#if 0
 
794
                                /* @@@ example for dolby/vorbis order, for reference later in case it becomes important */
 
795
                                if(
 
796
                                        options.common.channel_map_none ||
 
797
                                        channel_mask == 0x0001 || /* 1 channel: (mono) */
 
798
                                        channel_mask == 0x0003 || /* 2 channels: front left, front right */
 
799
                                        channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
 
800
                                        channel_mask == 0x0603    /* 4 channels: front left, front right, side left, side right */
 
801
                                ) {
 
802
                                        /* keep default channel order */
 
803
                                }
 
804
                                else if(
 
805
                                        channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
 
806
                                        channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
 
807
                                        channel_mask == 0x0607    /* 5 channels: front left, front right, front center, side left, side right */
 
808
                                ) {
 
809
                                        /* to dolby order: front left, center, front right [, surround left, surround right ] */
 
810
                                        channel_map[1] = 2;
 
811
                                        channel_map[2] = 1;
 
812
                                }
 
813
                                else if(
 
814
                                        channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
 
815
                                        channel_mask == 0x060f    /* 6 channels: front left, front right, front center, LFE, side left, side right */
 
816
                                ) {
 
817
                                        /* to dolby order: front left, center, front right, surround left, surround right, LFE */
 
818
                                        channel_map[1] = 2;
 
819
                                        channel_map[2] = 1;
 
820
                                        channel_map[3] = 5;
 
821
                                        channel_map[4] = 3;
 
822
                                        channel_map[5] = 4;
 
823
                                }
 
824
#else
 
825
                                if(
 
826
                                        options.common.channel_map_none ||
 
827
                                        channel_mask == 0x0001 || /* 1 channel: (mono) */
 
828
                                        channel_mask == 0x0003 || /* 2 channels: front left, front right */
 
829
                                        channel_mask == 0x0007 || /* 3 channels: front left, front right, front center */
 
830
                                        channel_mask == 0x0033 || /* 4 channels: front left, front right, back left, back right */
 
831
                                        channel_mask == 0x0603 || /* 4 channels: front left, front right, side left, side right */
 
832
                                        channel_mask == 0x0037 || /* 5 channels: front left, front right, front center, back left, back right */
 
833
                                        channel_mask == 0x0607 || /* 5 channels: front left, front right, front center, side left, side right */
 
834
                                        channel_mask == 0x003f || /* 6 channels: front left, front right, front center, LFE, back left, back right */
 
835
                                        channel_mask == 0x060f    /* 6 channels: front left, front right, front center, LFE, side left, side right */
 
836
                                ) {
 
837
                                        /* keep default channel order */
 
838
                                }
 
839
#endif
 
840
                                else {
 
841
                                        flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk with unsupported channel mask=0x%04X\n", encoder_session.inbasefilename, (unsigned)channel_mask);
 
842
                                        return EncoderSession_finish_error(&encoder_session);
 
843
                                }
 
844
                                if(!options.common.channel_map_none) {
 
845
                                        if(count_channel_mask_bits(channel_mask) < channels) {
 
846
                                                flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has unassigned channels (#channels=%u)\n", encoder_session.inbasefilename, (unsigned)channel_mask, channels);
 
847
                                                return EncoderSession_finish_error(&encoder_session);
 
848
                                        }
 
849
#if 0
 
850
                                        /* supporting this is too difficult with channel mapping; e.g. what if mask is 0x003f but #channels=4?
 
851
                                         * there would be holes in the order that would have to be filled in, or the mask would have to be
 
852
                                         * limited and the logic above rerun to see if it still fits into the FLAC mapping.
 
853
                                         */
 
854
                                        else if(count_channel_mask_bits(channel_mask) > channels)
 
855
                                                channel_mask = limit_channel_mask(channel_mask, channels);
 
856
#else
 
857
                                        else if(count_channel_mask_bits(channel_mask) > channels) {
 
858
                                                flac__utils_printf(stderr, 1, "%s: ERROR: WAVEFORMATEXTENSIBLE chunk: channel mask 0x%04X has extra bits for non-existant channels (#channels=%u)\n", encoder_session.inbasefilename, (unsigned)channel_mask, channels);
 
859
                                                return EncoderSession_finish_error(&encoder_session);
 
860
                                        }
 
861
#endif
 
862
                                }
 
863
                                /* first part of GUID */
 
864
                                if(!read_little_endian_uint16(infile, &x, false, encoder_session.inbasefilename))
 
865
                                        return EncoderSession_finish_error(&encoder_session);
 
866
                                if(x != 1) {
 
867
                                        flac__utils_printf(stderr, 1, "%s: ERROR: unsupported WAVEFORMATEXTENSIBLE chunk with non-PCM format %u\n", encoder_session.inbasefilename, (unsigned)x);
 
868
                                        return EncoderSession_finish_error(&encoder_session);
 
869
                                }
 
870
                                data_bytes -= 26;
 
871
                        }
 
872
 
 
873
                        if(bps-shift < 4 || bps-shift > 24) {
 
874
                                flac__utils_printf(stderr, 1, "%s: ERROR: unsupported bits-per-sample %u\n", encoder_session.inbasefilename, bps-shift);
 
875
                                return EncoderSession_finish_error(&encoder_session);
 
876
                        }
 
877
                        else if(options.common.sector_align && bps-shift != 16) {
 
878
                                flac__utils_printf(stderr, 1, "%s: ERROR: file has %u bits-per-sample, must be 16 for --sector-align\n", encoder_session.inbasefilename, bps-shift);
 
879
                                return EncoderSession_finish_error(&encoder_session);
 
880
                        }
623
881
 
624
882
                        /* skip any extra data in the fmt sub-chunk */
625
 
                        data_bytes -= 16;
626
 
                        if(data_bytes > 0) {
627
 
                                unsigned left, need;
628
 
                                for(left = data_bytes; left > 0; ) {
629
 
                                        need = min(left, CHUNK_OF_SAMPLES);
630
 
                                        if(fread(ucbuffer_, 1U, need, infile) < need) {
631
 
                                                flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping samples\n", encoder_session.inbasefilename);
632
 
                                                return EncoderSession_finish_error(&encoder_session);
633
 
                                        }
634
 
                                        left -= need;
635
 
                                }
 
883
                        if(!fskip_ahead(infile, data_bytes)) {
 
884
                                flac__utils_printf(stderr, 1, "%s: ERROR during read while skipping extra 'fmt' data\n", encoder_session.inbasefilename);
 
885
                                return EncoderSession_finish_error(&encoder_session);
636
886
                        }
637
887
 
638
888
                        /*
649
899
                else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
650
900
                        FLAC__uint64 total_samples_in_input, trim = 0;
651
901
                        FLAC__bool pad = false;
 
902
                        unsigned data_bytes;
652
903
 
653
904
                        /* data size */
654
905
                        if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
655
906
                                return EncoderSession_finish_error(&encoder_session);
656
907
                        data_bytes = xx;
 
908
                        if(0 == data_bytes) {
 
909
                                flac__utils_printf(stderr, 1, "%s: ERROR: 'data' subchunk has size of 0\n", encoder_session.inbasefilename);
 
910
                                return EncoderSession_finish_error(&encoder_session);
 
911
                        }
657
912
                        pad = (data_bytes & 1U) ? true : false;
658
913
 
659
914
                        bytes_per_wide_sample = channels * (bps >> 3);
698
953
                        /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
699
954
                        encoder_session.unencoded_size = encoder_session.total_samples_to_encode * bytes_per_wide_sample + 44;
700
955
 
701
 
                        if(!EncoderSession_init_encoder(&encoder_session, options.common, channels, bps, sample_rate))
 
956
                        if(!EncoderSession_init_encoder(&encoder_session, options.common, channel_mask, channels, bps-shift, sample_rate, /*flac_decoder_data=*/0))
702
957
                                return EncoderSession_finish_error(&encoder_session);
703
958
 
704
959
                        /*
736
991
                                        }
737
992
                                        else if(feof(infile)) {
738
993
                                                flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
 
994
                                                if(encoder_session.treat_warnings_as_errors)
 
995
                                                        return EncoderSession_finish_error(&encoder_session);
739
996
                                                data_bytes = 0;
740
997
                                        }
741
998
                                }
746
1003
                                        }
747
1004
                                        else {
748
1005
                                                unsigned wide_samples = bytes_read / bytes_per_wide_sample;
749
 
                                                format_input(input_, wide_samples, false, is_unsigned_samples, channels, bps);
 
1006
                                                if(!format_input(input_, wide_samples, /*is_big_endian=*/false, is_unsigned_samples, channels, bps, shift, channel_map))
 
1007
                                                        return EncoderSession_finish_error(&encoder_session);
750
1008
 
751
1009
                                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
752
1010
                                                        print_error_with_state(&encoder_session, "ERROR during encoding");
775
1033
                                                unsigned channel;
776
1034
 
777
1035
                                                info_align_zero = wide_samples;
778
 
                                                data_bytes = wide_samples * (bps >> 3);
779
1036
                                                for(channel = 0; channel < channels; channel++)
780
 
                                                        memset(input_[channel], 0, data_bytes);
 
1037
                                                        memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
781
1038
 
782
1039
                                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
783
1040
                                                        print_error_with_state(&encoder_session, "ERROR during encoding");
795
1052
                                                }
796
1053
                                                else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
797
1054
                                                        flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
798
 
                                                        data_bytes = 0;
 
1055
                                                        if(encoder_session.treat_warnings_as_errors)
 
1056
                                                                return EncoderSession_finish_error(&encoder_session);
799
1057
                                                }
800
1058
                                                else {
801
1059
                                                        info_align_carry = *options.common.align_reservoir_samples;
802
 
                                                        format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, is_unsigned_samples, channels, bps);
 
1060
                                                        if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, /*is_big_endian=*/false, is_unsigned_samples, channels, bps, shift, channel_map))
 
1061
                                                                return EncoderSession_finish_error(&encoder_session);
803
1062
                                                }
804
1063
                                        }
805
1064
                                }
819
1078
                else {
820
1079
                        if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
821
1080
                                flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_session.inbasefilename);
 
1081
                                if(encoder_session.treat_warnings_as_errors)
 
1082
                                        return EncoderSession_finish_error(&encoder_session);
822
1083
                        }
823
1084
                        else if(xx == 0x61746164) { /* "data" */
824
1085
                                if(got_data_chunk) {
825
1086
                                        flac__utils_printf(stderr, 1, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_session.inbasefilename);
 
1087
                                        if(encoder_session.treat_warnings_as_errors)
 
1088
                                                return EncoderSession_finish_error(&encoder_session);
826
1089
                                }
827
1090
                                else if(!got_fmt_chunk) {
828
1091
                                        flac__utils_printf(stderr, 1, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_session.inbasefilename);
834
1097
                        }
835
1098
                        else {
836
1099
                                flac__utils_printf(stderr, 1, "%s: WARNING: skipping unknown sub-chunk '%c%c%c%c'\n", encoder_session.inbasefilename, (char)(xx&255), (char)((xx>>8)&255), (char)((xx>>16)&255), (char)(xx>>24));
 
1100
                                if(encoder_session.treat_warnings_as_errors)
 
1101
                                        return EncoderSession_finish_error(&encoder_session);
837
1102
                        }
838
1103
                        /* sub-chunk size */
839
1104
                        if(!read_little_endian_uint32(infile, &xx, false, encoder_session.inbasefilename))
853
1118
        return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
854
1119
}
855
1120
 
856
 
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)
 
1121
int flac__encode_raw(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, raw_encode_options_t options)
857
1122
{
858
1123
        EncoderSession encoder_session;
859
1124
        size_t bytes_read;
860
1125
        const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
861
1126
        unsigned align_remainder = 0;
862
1127
        int info_align_carry = -1, info_align_zero = -1;
863
 
        FLAC__uint64 total_samples_in_input = 0;;
 
1128
        FLAC__uint64 total_samples_in_input = 0;
864
1129
 
865
1130
        FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
866
1131
        FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
872
1137
        if(!
873
1138
                EncoderSession_construct(
874
1139
                        &encoder_session,
875
 
#ifdef FLAC__HAS_OGG
 
1140
#if FLAC__HAS_OGG
876
1141
                        options.common.use_ogg,
877
1142
#else
878
1143
                        /*use_ogg=*/false,
879
1144
#endif
880
1145
                        options.common.verify,
 
1146
                        options.common.treat_warnings_as_errors,
 
1147
                        options.common.continue_through_decode_errors,
881
1148
                        infile,
882
1149
                        infilename,
883
1150
                        outfilename
899
1166
        else {
900
1167
                /* *options.common.align_reservoir_samples will be 0 unless --sector-align is used */
901
1168
                FLAC__ASSERT(options.common.sector_align || *options.common.align_reservoir_samples == 0);
902
 
                total_samples_in_input = (unsigned)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
 
1169
                total_samples_in_input = (FLAC__uint64)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
903
1170
        }
904
1171
 
905
1172
        /*
911
1178
        encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
912
1179
        FLAC__ASSERT(!options.common.sector_align || encoder_session.until == 0);
913
1180
 
 
1181
        infilesize -= (off_t)encoder_session.skip * bytes_per_wide_sample;
914
1182
        encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
915
1183
        if(encoder_session.until > 0) {
916
1184
                const FLAC__uint64 trim = total_samples_in_input - encoder_session.until;
917
1185
                FLAC__ASSERT(total_samples_in_input > 0);
918
1186
                FLAC__ASSERT(!options.common.sector_align);
 
1187
                infilesize -= (off_t)trim * bytes_per_wide_sample;
919
1188
                encoder_session.total_samples_to_encode -= trim;
920
1189
        }
921
1190
        if(infilesize >= 0 && options.common.sector_align) {
947
1216
                }
948
1217
        }
949
1218
 
950
 
        if(!EncoderSession_init_encoder(&encoder_session, options.common, options.channels, options.bps, options.sample_rate))
 
1219
        if(!EncoderSession_init_encoder(&encoder_session, options.common, /*channel_mask=*/0, options.channels, options.bps, options.sample_rate, /*flac_decoder_data=*/0))
951
1220
                return EncoderSession_finish_error(&encoder_session);
952
1221
 
953
1222
        /*
970
1239
                }
971
1240
                else {
972
1241
                        *options.common.align_reservoir_samples = align_remainder;
973
 
                        infilesize -= (long)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
 
1242
                        infilesize -= (off_t)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
974
1243
                        FLAC__ASSERT(infilesize >= 0);
975
1244
                }
976
1245
        }
1005
1274
                        }
1006
1275
                        else {
1007
1276
                                unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1008
 
                                format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
 
1277
                                if(!format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0, /*channel_map=*/0))
 
1278
                                        return EncoderSession_finish_error(&encoder_session);
1009
1279
 
1010
1280
                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1011
1281
                                        print_error_with_state(&encoder_session, "ERROR during encoding");
1015
1285
                }
1016
1286
        }
1017
1287
        else {
1018
 
                const FLAC__uint64 max_input_bytes = encoder_session.total_samples_to_encode * bytes_per_wide_sample;
 
1288
                const FLAC__uint64 max_input_bytes = infilesize;
1019
1289
                FLAC__uint64 total_input_bytes_read = 0;
1020
1290
                while(total_input_bytes_read < max_input_bytes) {
1021
1291
                        {
1022
1292
                                size_t wanted = (CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1023
 
                                wanted = min(wanted, (size_t)(max_input_bytes - total_input_bytes_read));
 
1293
                                wanted = (size_t) min((FLAC__uint64)wanted, max_input_bytes - total_input_bytes_read);
1024
1294
 
1025
1295
                                if(lookahead_length > 0) {
1026
1296
                                        FLAC__ASSERT(lookahead_length <= wanted);
1047
1317
                                }
1048
1318
                                else if(feof(infile)) {
1049
1319
                                        flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
 
1320
                                        if(encoder_session.treat_warnings_as_errors)
 
1321
                                                return EncoderSession_finish_error(&encoder_session);
1050
1322
                                        total_input_bytes_read = max_input_bytes;
1051
1323
                                }
1052
1324
                        }
1057
1329
                                }
1058
1330
                                else {
1059
1331
                                        unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1060
 
                                        format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps);
 
1332
                                        if(!format_input(input_, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0, /*channel_map=*/0))
 
1333
                                                return EncoderSession_finish_error(&encoder_session);
1061
1334
 
1062
1335
                                        if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1063
1336
                                                print_error_with_state(&encoder_session, "ERROR during encoding");
1076
1349
                if(options.common.is_last_file) {
1077
1350
                        unsigned wide_samples = 588 - align_remainder;
1078
1351
                        if(wide_samples < 588) {
1079
 
                                unsigned channel, data_bytes;
 
1352
                                unsigned channel;
1080
1353
 
1081
1354
                                info_align_zero = wide_samples;
1082
 
                                data_bytes = wide_samples * (options.bps >> 3);
1083
1355
                                for(channel = 0; channel < options.channels; channel++)
1084
 
                                        memset(input_[channel], 0, data_bytes);
 
1356
                                        memset(input_[channel], 0, sizeof(input_[0][0]) * wide_samples);
1085
1357
 
1086
1358
                                if(!EncoderSession_process(&encoder_session, (const FLAC__int32 * const *)input_, wide_samples)) {
1087
1359
                                        print_error_with_state(&encoder_session, "ERROR during encoding");
1099
1371
                                }
1100
1372
                                else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1101
1373
                                        flac__utils_printf(stderr, 1, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_session.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_session.total_samples_to_encode, (unsigned)encoder_session.samples_written);
 
1374
                                        if(encoder_session.treat_warnings_as_errors)
 
1375
                                                return EncoderSession_finish_error(&encoder_session);
1102
1376
                                }
1103
1377
                                else {
1104
1378
                                        info_align_carry = *options.common.align_reservoir_samples;
1105
 
                                        format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, options.is_unsigned_samples, options.channels, options.bps);
 
1379
                                        if(!format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, /*shift=*/0, /*channel_map=*/0))
 
1380
                                                return EncoderSession_finish_error(&encoder_session);
1106
1381
                                }
1107
1382
                        }
1108
1383
                }
1111
1386
        return EncoderSession_finish_ok(&encoder_session, info_align_carry, info_align_zero);
1112
1387
}
1113
1388
 
1114
 
FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FILE *infile, const char *infilename, const char *outfilename)
 
1389
int flac__encode_flac(FILE *infile, off_t infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, flac_encode_options_t options, FLAC__bool input_is_ogg)
 
1390
{
 
1391
        EncoderSession encoder_session;
 
1392
        FLAC__StreamDecoder *decoder = 0;
 
1393
        FLACDecoderData decoder_data;
 
1394
        size_t i;
 
1395
        int retval;
 
1396
 
 
1397
        if(!
 
1398
                EncoderSession_construct(
 
1399
                        &encoder_session,
 
1400
#if FLAC__HAS_OGG
 
1401
                        options.common.use_ogg,
 
1402
#else
 
1403
                        /*use_ogg=*/false,
 
1404
#endif
 
1405
                        options.common.verify,
 
1406
                        options.common.treat_warnings_as_errors,
 
1407
                        options.common.continue_through_decode_errors,
 
1408
                        infile,
 
1409
                        infilename,
 
1410
                        outfilename
 
1411
                )
 
1412
        )
 
1413
                return 1;
 
1414
 
 
1415
        decoder_data.encoder_session = &encoder_session;
 
1416
        decoder_data.filesize = (infilesize == (off_t)(-1)? 0 : infilesize);
 
1417
        decoder_data.lookahead = lookahead;
 
1418
        decoder_data.lookahead_length = lookahead_length;
 
1419
        decoder_data.num_metadata_blocks = 0;
 
1420
        decoder_data.samples_left_to_process = 0;
 
1421
        decoder_data.fatal_error = false;
 
1422
 
 
1423
        /*
 
1424
         * set up FLAC decoder for the input
 
1425
         */
 
1426
        if (0 == (decoder = FLAC__stream_decoder_new())) {
 
1427
                flac__utils_printf(stderr, 1, "%s: ERROR: creating decoder for FLAC input\n", encoder_session.inbasefilename);
 
1428
                return EncoderSession_finish_error(&encoder_session);
 
1429
        }
 
1430
        if (!(
 
1431
                FLAC__stream_decoder_set_md5_checking(decoder, false) &&
 
1432
                FLAC__stream_decoder_set_metadata_respond_all(decoder)
 
1433
        )) {
 
1434
                flac__utils_printf(stderr, 1, "%s: ERROR: setting up decoder for FLAC input\n", encoder_session.inbasefilename);
 
1435
                goto fubar1; /*@@@ yuck */
 
1436
        }
 
1437
 
 
1438
        if (input_is_ogg) {
 
1439
                if (FLAC__stream_decoder_init_ogg_stream(decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/&decoder_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
 
1440
                        flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for Ogg FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
 
1441
                        goto fubar1; /*@@@ yuck */
 
1442
                }
 
1443
        }
 
1444
        else if (FLAC__stream_decoder_init_stream(decoder, flac_decoder_read_callback, flac_decoder_seek_callback, flac_decoder_tell_callback, flac_decoder_length_callback, flac_decoder_eof_callback, flac_decoder_write_callback, flac_decoder_metadata_callback, flac_decoder_error_callback, /*client_data=*/&decoder_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
 
1445
                flac__utils_printf(stderr, 1, "%s: ERROR: initializing decoder for FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
 
1446
                goto fubar1; /*@@@ yuck */
 
1447
        }
 
1448
 
 
1449
        if (!FLAC__stream_decoder_process_until_end_of_metadata(decoder) || decoder_data.fatal_error) {
 
1450
                if (decoder_data.fatal_error)
 
1451
                        flac__utils_printf(stderr, 1, "%s: ERROR: out of memory or too many metadata blocks while reading metadata in FLAC input\n", encoder_session.inbasefilename);
 
1452
                else
 
1453
                        flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
 
1454
                goto fubar1; /*@@@ yuck */
 
1455
        }
 
1456
 
 
1457
        if (decoder_data.num_metadata_blocks == 0) {
 
1458
                flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, got no metadata blocks\n", encoder_session.inbasefilename);
 
1459
                goto fubar2; /*@@@ yuck */
 
1460
        }
 
1461
        else if (decoder_data.metadata_blocks[0]->type != FLAC__METADATA_TYPE_STREAMINFO) {
 
1462
                flac__utils_printf(stderr, 1, "%s: ERROR: reading metadata in FLAC input, first metadata block is not STREAMINFO\n", encoder_session.inbasefilename);
 
1463
                goto fubar2; /*@@@ yuck */
 
1464
        }
 
1465
        else if (decoder_data.metadata_blocks[0]->data.stream_info.total_samples == 0) {
 
1466
                flac__utils_printf(stderr, 1, "%s: ERROR: FLAC input has STREAMINFO with unknown total samples which is not supported\n", encoder_session.inbasefilename);
 
1467
                goto fubar2; /*@@@ yuck */
 
1468
        }
 
1469
 
 
1470
        /*
 
1471
         * now that we have the STREAMINFO and know the sample rate,
 
1472
         * canonicalize the --skip string to a number of samples:
 
1473
         */
 
1474
        flac__utils_canonicalize_skip_until_specification(&options.common.skip_specification, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate);
 
1475
        FLAC__ASSERT(options.common.skip_specification.value.samples >= 0);
 
1476
        encoder_session.skip = (FLAC__uint64)options.common.skip_specification.value.samples;
 
1477
        FLAC__ASSERT(!options.common.sector_align); /* --sector-align with FLAC input is not supported */
 
1478
 
 
1479
        {
 
1480
                FLAC__uint64 total_samples_in_input, trim = 0;
 
1481
 
 
1482
                total_samples_in_input = decoder_data.metadata_blocks[0]->data.stream_info.total_samples;
 
1483
 
 
1484
                /*
 
1485
                 * now that we know the input size, canonicalize the
 
1486
                 * --until string to an absolute sample number:
 
1487
                 */
 
1488
                if(!canonicalize_until_specification(&options.common.until_specification, encoder_session.inbasefilename, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate, encoder_session.skip, total_samples_in_input))
 
1489
                        goto fubar2; /*@@@ yuck */
 
1490
                encoder_session.until = (FLAC__uint64)options.common.until_specification.value.samples;
 
1491
 
 
1492
                encoder_session.total_samples_to_encode = total_samples_in_input - encoder_session.skip;
 
1493
                if(encoder_session.until > 0) {
 
1494
                        trim = total_samples_in_input - encoder_session.until;
 
1495
                        FLAC__ASSERT(total_samples_in_input > 0);
 
1496
                        encoder_session.total_samples_to_encode -= trim;
 
1497
                }
 
1498
 
 
1499
                encoder_session.unencoded_size = decoder_data.filesize;
 
1500
 
 
1501
                /* (channel mask will get copied over from the source VORBIS_COMMENT if it exists) */
 
1502
                if(!EncoderSession_init_encoder(&encoder_session, options.common, /*channel_mask=*/0, decoder_data.metadata_blocks[0]->data.stream_info.channels, decoder_data.metadata_blocks[0]->data.stream_info.bits_per_sample, decoder_data.metadata_blocks[0]->data.stream_info.sample_rate, &decoder_data))
 
1503
                        goto fubar2; /*@@@ yuck */
 
1504
 
 
1505
                /*
 
1506
                 * have to wait until the FLAC encoder is set up for writing
 
1507
                 * before any seeking in the input FLAC file, because the seek
 
1508
                 * itself will usually call the decoder's write callback, and
 
1509
                 * our decoder's write callback passes samples to our FLAC
 
1510
                 * encoder
 
1511
                 */
 
1512
                decoder_data.samples_left_to_process = encoder_session.total_samples_to_encode;
 
1513
                if(encoder_session.skip > 0) {
 
1514
                        if(!FLAC__stream_decoder_seek_absolute(decoder, encoder_session.skip)) {
 
1515
                                flac__utils_printf(stderr, 1, "%s: ERROR while skipping samples, FLAC decoder state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
 
1516
                                goto fubar2; /*@@@ yuck */
 
1517
                        }
 
1518
                }
 
1519
 
 
1520
                /*
 
1521
                 * now do samples from the file
 
1522
                 */
 
1523
                while(!decoder_data.fatal_error && decoder_data.samples_left_to_process > 0) {
 
1524
                        /* We can also hit the end of stream without samples_left_to_process
 
1525
                         * going to 0 if there are errors and continue_through_decode_errors
 
1526
                         * is on, so we want to break in that case too:
 
1527
                         */
 
1528
                        if(encoder_session.continue_through_decode_errors && FLAC__stream_decoder_get_state(decoder) == FLAC__STREAM_DECODER_END_OF_STREAM)
 
1529
                                break;
 
1530
                        if(!FLAC__stream_decoder_process_single(decoder)) {
 
1531
                                flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
 
1532
                                goto fubar2; /*@@@ yuck */
 
1533
                        }
 
1534
                }
 
1535
                if(decoder_data.fatal_error) {
 
1536
                        flac__utils_printf(stderr, 1, "%s: ERROR: while decoding FLAC input, state = %s\n", encoder_session.inbasefilename, FLAC__stream_decoder_get_resolved_state_string(decoder));
 
1537
                        goto fubar2; /*@@@ yuck */
 
1538
                }
 
1539
        }
 
1540
 
 
1541
        FLAC__stream_decoder_delete(decoder);
 
1542
        retval = EncoderSession_finish_ok(&encoder_session, -1, -1);
 
1543
        /* have to wail until encoder is completely finished before deleting because of the final step of writing the seekpoint offsets */
 
1544
        for(i = 0; i < decoder_data.num_metadata_blocks; i++)
 
1545
                FLAC__metadata_object_delete(decoder_data.metadata_blocks[i]);
 
1546
        return retval;
 
1547
 
 
1548
fubar2:
 
1549
        for(i = 0; i < decoder_data.num_metadata_blocks; i++)
 
1550
                FLAC__metadata_object_delete(decoder_data.metadata_blocks[i]);
 
1551
fubar1:
 
1552
        FLAC__stream_decoder_delete(decoder);
 
1553
        return EncoderSession_finish_error(&encoder_session);
 
1554
}
 
1555
 
 
1556
FLAC__bool EncoderSession_construct(EncoderSession *e, FLAC__bool use_ogg, FLAC__bool verify, FLAC__bool treat_warnings_as_errors, FLAC__bool continue_through_decode_errors, FILE *infile, const char *infilename, const char *outfilename)
1115
1557
{
1116
1558
        unsigned i;
1117
1559
        FLAC__uint32 test = 1;
1130
1572
         * initialize instance
1131
1573
         */
1132
1574
 
1133
 
#ifdef FLAC__HAS_OGG
 
1575
#if FLAC__HAS_OGG
1134
1576
        e->use_ogg = use_ogg;
1135
1577
#else
1136
1578
        (void)use_ogg;
1137
1579
#endif
1138
1580
        e->verify = verify;
 
1581
        e->treat_warnings_as_errors = treat_warnings_as_errors;
 
1582
        e->continue_through_decode_errors = continue_through_decode_errors;
1139
1583
 
1140
1584
        e->is_stdout = (0 == strcmp(outfilename, "-"));
 
1585
        e->outputfile_opened = false;
1141
1586
 
1142
1587
        e->inbasefilename = grabbag__file_get_basename(infilename);
1143
1588
        e->outfilename = outfilename;
1147
1592
        e->total_samples_to_encode = 0;
1148
1593
        e->bytes_written = 0;
1149
1594
        e->samples_written = 0;
1150
 
        e->blocksize = 0;
1151
1595
        e->stats_mask = 0;
1152
1596
 
1153
 
        e->encoder.flac.stream = 0;
1154
 
        e->encoder.flac.file = 0;
1155
 
#ifdef FLAC__HAS_OGG
1156
 
        e->encoder.ogg.stream = 0;
1157
 
        e->encoder.ogg.file = 0;
1158
 
#endif
 
1597
        e->encoder = 0;
1159
1598
 
1160
1599
        e->fin = infile;
1161
 
        e->fout = 0;
1162
1600
        e->seek_table_template = 0;
1163
1601
 
1164
 
        if(e->is_stdout) {
1165
 
                e->fout = grabbag__file_get_binary_stdout();
1166
 
        }
1167
 
 
1168
1602
        if(0 == (e->seek_table_template = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE))) {
1169
1603
                flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for seek table\n", e->inbasefilename);
1170
1604
                return false;
1171
1605
        }
1172
1606
 
1173
 
#ifdef FLAC__HAS_OGG
1174
 
        if(e->use_ogg) {
1175
 
                if(e->is_stdout) {
1176
 
                        e->encoder.ogg.stream = OggFLAC__stream_encoder_new();
1177
 
                        if(0 == e->encoder.ogg.stream) {
1178
 
                                flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1179
 
                                EncoderSession_destroy(e);
1180
 
                                return false;
1181
 
                        }
1182
 
                }
1183
 
                else {
1184
 
                        e->encoder.ogg.file = OggFLAC__file_encoder_new();
1185
 
                        if(0 == e->encoder.ogg.file) {
1186
 
                                flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1187
 
                                EncoderSession_destroy(e);
1188
 
                                return false;
1189
 
                        }
1190
 
                }
1191
 
        }
1192
 
        else
1193
 
#endif
1194
 
        if(e->is_stdout) {
1195
 
                e->encoder.flac.stream = FLAC__stream_encoder_new();
1196
 
                if(0 == e->encoder.flac.stream) {
1197
 
                        flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1198
 
                        EncoderSession_destroy(e);
1199
 
                        return false;
1200
 
                }
1201
 
        }
1202
 
        else {
1203
 
                e->encoder.flac.file = FLAC__file_encoder_new();
1204
 
                if(0 == e->encoder.flac.file) {
1205
 
                        flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
1206
 
                        EncoderSession_destroy(e);
1207
 
                        return false;
1208
 
                }
 
1607
        e->encoder = FLAC__stream_encoder_new();
 
1608
        if(0 == e->encoder) {
 
1609
                flac__utils_printf(stderr, 1, "%s: ERROR creating the encoder instance\n", e->inbasefilename);
 
1610
                EncoderSession_destroy(e);
 
1611
                return false;
1209
1612
        }
1210
1613
 
1211
1614
        return true;
1215
1618
{
1216
1619
        if(e->fin != stdin)
1217
1620
                fclose(e->fin);
1218
 
        if(0 != e->fout && e->fout != stdout)
1219
 
                fclose(e->fout);
1220
1621
 
1221
 
#ifdef FLAC__HAS_OGG
1222
 
        if(e->use_ogg) {
1223
 
                if(e->is_stdout) {
1224
 
                        if(0 != e->encoder.ogg.stream) {
1225
 
                                OggFLAC__stream_encoder_delete(e->encoder.ogg.stream);
1226
 
                                e->encoder.ogg.stream = 0;
1227
 
                        }
1228
 
                }
1229
 
                else {
1230
 
                        if(0 != e->encoder.ogg.file) {
1231
 
                                OggFLAC__file_encoder_delete(e->encoder.ogg.file);
1232
 
                                e->encoder.ogg.file = 0;
1233
 
                        }
1234
 
                }
1235
 
        }
1236
 
        else
1237
 
#endif
1238
 
        if(e->is_stdout) {
1239
 
                if(0 != e->encoder.flac.stream) {
1240
 
                        FLAC__stream_encoder_delete(e->encoder.flac.stream);
1241
 
                        e->encoder.flac.stream = 0;
1242
 
                }
1243
 
        }
1244
 
        else {
1245
 
                if(0 != e->encoder.flac.file) {
1246
 
                        FLAC__file_encoder_delete(e->encoder.flac.file);
1247
 
                        e->encoder.flac.file = 0;
1248
 
                }
 
1622
        if(0 != e->encoder) {
 
1623
                FLAC__stream_encoder_delete(e->encoder);
 
1624
                e->encoder = 0;
1249
1625
        }
1250
1626
 
1251
1627
        if(0 != e->seek_table_template) {
1258
1634
{
1259
1635
        FLAC__StreamEncoderState fse_state = FLAC__STREAM_ENCODER_OK;
1260
1636
        int ret = 0;
1261
 
 
1262
 
#ifdef FLAC__HAS_OGG
1263
 
        if(e->use_ogg) {
1264
 
                if(e->is_stdout) {
1265
 
                        if(e->encoder.ogg.stream) {
1266
 
                                fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1267
 
                                OggFLAC__stream_encoder_finish(e->encoder.ogg.stream);
1268
 
                        }
1269
 
                }
1270
 
                else {
1271
 
                        if(e->encoder.ogg.file) {
1272
 
                                fse_state = OggFLAC__file_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.file);
1273
 
                                OggFLAC__file_encoder_finish(e->encoder.ogg.file);
1274
 
                        }
1275
 
                }
1276
 
        }
1277
 
        else
1278
 
#endif
1279
 
        if(e->is_stdout) {
1280
 
                if(e->encoder.flac.stream) {
1281
 
                        fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1282
 
                        FLAC__stream_encoder_finish(e->encoder.flac.stream);
1283
 
                }
1284
 
        }
1285
 
        else {
1286
 
                if(e->encoder.flac.file) {
1287
 
                        fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1288
 
                        FLAC__file_encoder_finish(e->encoder.flac.file);
1289
 
                }
1290
 
        }
1291
 
 
1292
 
        if(e->total_samples_to_encode > 0) {
 
1637
        FLAC__bool verify_error = false;
 
1638
 
 
1639
        if(e->encoder) {
 
1640
                fse_state = FLAC__stream_encoder_get_state(e->encoder);
 
1641
                ret = FLAC__stream_encoder_finish(e->encoder)? 0 : 1;
 
1642
                verify_error =
 
1643
                        fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA ||
 
1644
                        FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA
 
1645
                ;
 
1646
        }
 
1647
        /* all errors except verify errors should interrupt the stats */
 
1648
        if(ret && !verify_error)
 
1649
                print_error_with_state(e, "ERROR during encoding");
 
1650
        else if(e->total_samples_to_encode > 0) {
1293
1651
                print_stats(e);
1294
1652
                flac__utils_printf(stderr, 2, "\n");
1295
1653
        }
1296
1654
 
1297
 
        if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
 
1655
        if(verify_error) {
1298
1656
                print_verify_error(e);
1299
1657
                ret = 1;
1300
1658
        }
1314
1672
 
1315
1673
int EncoderSession_finish_error(EncoderSession *e)
1316
1674
{
1317
 
        FLAC__StreamEncoderState fse_state;
 
1675
        FLAC__ASSERT(e->encoder);
1318
1676
 
1319
1677
        if(e->total_samples_to_encode > 0)
1320
1678
                flac__utils_printf(stderr, 2, "\n");
1321
1679
 
1322
 
#ifdef FLAC__HAS_OGG
1323
 
        if(e->use_ogg) {
1324
 
                if(e->is_stdout) {
1325
 
                        fse_state = OggFLAC__stream_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.stream);
1326
 
                }
1327
 
                else {
1328
 
                        fse_state = OggFLAC__file_encoder_get_FLAC_stream_encoder_state(e->encoder.ogg.file);
1329
 
                }
1330
 
        }
1331
 
        else
1332
 
#endif
1333
 
        if(e->is_stdout) {
1334
 
                fse_state = FLAC__stream_encoder_get_state(e->encoder.flac.stream);
1335
 
        }
1336
 
        else {
1337
 
                fse_state = FLAC__file_encoder_get_stream_encoder_state(e->encoder.flac.file);
1338
 
        }
1339
 
 
1340
 
        if(fse_state == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
 
1680
        if(FLAC__stream_encoder_get_state(e->encoder) == FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1341
1681
                print_verify_error(e);
1342
 
        else
 
1682
        else if(e->outputfile_opened)
 
1683
                /* only want to delete the file if we opened it; otherwise it could be an existing file and our overwrite failed */
1343
1684
                unlink(e->outfilename);
1344
1685
 
1345
1686
        EncoderSession_destroy(e);
1347
1688
        return 1;
1348
1689
}
1349
1690
 
1350
 
FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate)
 
1691
FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t options, FLAC__uint32 channel_mask, unsigned channels, unsigned bps, unsigned sample_rate, FLACDecoderData *flac_decoder_data)
1351
1692
{
1352
 
        unsigned num_metadata;
 
1693
        unsigned num_metadata, i;
1353
1694
        FLAC__StreamMetadata padding, *cuesheet = 0;
1354
 
        FLAC__StreamMetadata *metadata[4];
 
1695
        FLAC__StreamMetadata *static_metadata[4+64]; /* MAGIC +64 is for pictures metadata in options.pictures */
 
1696
        FLAC__StreamMetadata **metadata = static_metadata;
 
1697
        FLAC__StreamEncoderInitStatus init_status;
1355
1698
        const FLAC__bool is_cdda = (channels == 1 || channels == 2) && (bps == 16) && (sample_rate == 44100);
 
1699
        char apodizations[2000];
 
1700
 
 
1701
        FLAC__ASSERT(sizeof(options.pictures)/sizeof(options.pictures[0]) <= 64);
1356
1702
 
1357
1703
        e->replay_gain = options.replay_gain;
1358
1704
        e->channels = channels;
1359
1705
        e->bits_per_sample = bps;
1360
1706
        e->sample_rate = sample_rate;
1361
1707
 
 
1708
        apodizations[0] = '\0';
 
1709
 
1362
1710
        if(e->replay_gain) {
1363
1711
                if(channels != 1 && channels != 2) {
1364
1712
                        flac__utils_printf(stderr, 1, "%s: ERROR, number of channels (%u) must be 1 or 2 for --replay-gain\n", e->inbasefilename, channels);
1376
1724
                }
1377
1725
        }
1378
1726
 
1379
 
        if(channels != 2)
1380
 
                options.do_mid_side = options.loose_mid_side = false;
1381
 
 
1382
 
        if(!parse_cuesheet_(&cuesheet, options.cuesheet_filename, e->inbasefilename, is_cdda, e->total_samples_to_encode))
 
1727
        if(!parse_cuesheet(&cuesheet, options.cuesheet_filename, e->inbasefilename, is_cdda, e->total_samples_to_encode, e->treat_warnings_as_errors))
1383
1728
                return false;
1384
1729
 
1385
1730
        if(!convert_to_seek_table_template(options.requested_seek_points, options.num_requested_seek_points, options.cued_seekpoints? cuesheet : 0, e)) {
1389
1734
                return false;
1390
1735
        }
1391
1736
 
1392
 
        num_metadata = 0;
1393
 
        if(e->seek_table_template->data.seek_table.num_points > 0) {
1394
 
                e->seek_table_template->is_last = false; /* the encoder will set this for us */
1395
 
                metadata[num_metadata++] = e->seek_table_template;
1396
 
        }
1397
 
        if(0 != cuesheet)
1398
 
                metadata[num_metadata++] = cuesheet;
1399
 
        metadata[num_metadata++] = options.vorbis_comment;
1400
 
        if(options.padding > 0) {
1401
 
                padding.is_last = false; /* the encoder will set this for us */
1402
 
                padding.type = FLAC__METADATA_TYPE_PADDING;
1403
 
                padding.length = (unsigned)options.padding;
1404
 
                metadata[num_metadata++] = &padding;
1405
 
        }
1406
 
 
1407
 
        e->blocksize = options.blocksize;
1408
 
        e->stats_mask = (options.do_exhaustive_model_search || options.do_qlp_coeff_prec_search)? 0x0f : 0x3f;
1409
 
 
1410
 
#ifdef FLAC__HAS_OGG
 
1737
        if(flac_decoder_data) {
 
1738
                /*
 
1739
                 * we're encoding from FLAC so we will use the FLAC file's
 
1740
                 * metadata as the basis for the encoded file
 
1741
                 */
 
1742
                {
 
1743
                        /*
 
1744
                         * first handle pictures: simple append any --pictures
 
1745
                         * specified.
 
1746
                         */
 
1747
                        for(i = 0; i < options.num_pictures; i++) {
 
1748
                                FLAC__StreamMetadata *pic = FLAC__metadata_object_clone(options.pictures[i]);
 
1749
                                if(0 == pic) {
 
1750
                                        flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PICTURE block\n", e->inbasefilename);
 
1751
                                        if(0 != cuesheet)
 
1752
                                                FLAC__metadata_object_delete(cuesheet);
 
1753
                                        return false;
 
1754
                                }
 
1755
                                flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks++] = pic;
 
1756
                        }
 
1757
                }
 
1758
                {
 
1759
                        /*
 
1760
                         * next handle vorbis comment: if any tags were specified
 
1761
                         * or there is no existing vorbis comment, we create a
 
1762
                         * new vorbis comment (discarding any existing one); else
 
1763
                         * we keep the existing one.  also need to make sure to
 
1764
                         * propagate any channel mask tag.
 
1765
                         */
 
1766
                        /* @@@ change to append -T values from options.vorbis_comment if input has VC already? */
 
1767
                        size_t i, j;
 
1768
                        FLAC__bool vc_found = false;
 
1769
                        for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
 
1770
                                if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
 
1771
                                        vc_found = true;
 
1772
                                if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT && options.vorbis_comment->data.vorbis_comment.num_comments > 0) {
 
1773
                                        (void) flac__utils_get_channel_mask_tag(flac_decoder_data->metadata_blocks[i], &channel_mask);
 
1774
                                        flac__utils_printf(stderr, 1, "%s: WARNING, replacing tags from input FLAC file with those given on the command-line\n", e->inbasefilename);
 
1775
                                        if(e->treat_warnings_as_errors) {
 
1776
                                                if(0 != cuesheet)
 
1777
                                                        FLAC__metadata_object_delete(cuesheet);
 
1778
                                                return false;
 
1779
                                        }
 
1780
                                        FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
 
1781
                                        flac_decoder_data->metadata_blocks[i] = 0;
 
1782
                                }
 
1783
                                else
 
1784
                                        flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
 
1785
                        }
 
1786
                        flac_decoder_data->num_metadata_blocks = j;
 
1787
                        if((!vc_found || options.vorbis_comment->data.vorbis_comment.num_comments > 0) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
 
1788
                                /* prepend ours */
 
1789
                                FLAC__StreamMetadata *vc = FLAC__metadata_object_clone(options.vorbis_comment);
 
1790
                                if(0 == vc || (channel_mask && !flac__utils_set_channel_mask_tag(vc, channel_mask))) {
 
1791
                                        flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for VORBIS_COMMENT block\n", e->inbasefilename);
 
1792
                                        if(0 != cuesheet)
 
1793
                                                FLAC__metadata_object_delete(cuesheet);
 
1794
                                        return false;
 
1795
                                }
 
1796
                                for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
 
1797
                                        flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
 
1798
                                flac_decoder_data->metadata_blocks[1] = vc;
 
1799
                                flac_decoder_data->num_metadata_blocks++;
 
1800
                        }
 
1801
                }
 
1802
                {
 
1803
                        /*
 
1804
                         * next handle cuesheet: if --cuesheet was specified, use
 
1805
                         * it; else if file has existing CUESHEET and cuesheet's
 
1806
                         * lead-out offset is correct, keep it; else no CUESHEET
 
1807
                         */
 
1808
                        size_t i, j;
 
1809
                        for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
 
1810
                                FLAC__bool existing_cuesheet_is_bad = false;
 
1811
                                /* check if existing cuesheet matches the input audio */
 
1812
                                if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && 0 == cuesheet) {
 
1813
                                        const FLAC__StreamMetadata_CueSheet *cs = &flac_decoder_data->metadata_blocks[i]->data.cue_sheet;
 
1814
                                        if(e->total_samples_to_encode == 0) {
 
1815
                                                flac__utils_printf(stderr, 1, "%s: WARNING, cuesheet in input FLAC file cannot be kept if input size is not known, dropping it...\n", e->inbasefilename);
 
1816
                                                if(e->treat_warnings_as_errors) {
 
1817
                                                        if(0 != cuesheet)
 
1818
                                                                FLAC__metadata_object_delete(cuesheet);
 
1819
                                                        return false;
 
1820
                                                }
 
1821
                                                existing_cuesheet_is_bad = true;
 
1822
                                        }
 
1823
                                        else if(e->total_samples_to_encode != cs->tracks[cs->num_tracks-1].offset) {
 
1824
                                                flac__utils_printf(stderr, 1, "%s: WARNING, lead-out offset of cuesheet in input FLAC file does not match input length, dropping existing cuesheet...\n", e->inbasefilename);
 
1825
                                                if(e->treat_warnings_as_errors) {
 
1826
                                                        if(0 != cuesheet)
 
1827
                                                                FLAC__metadata_object_delete(cuesheet);
 
1828
                                                        return false;
 
1829
                                                }
 
1830
                                                existing_cuesheet_is_bad = true;
 
1831
                                        }
 
1832
                                }
 
1833
                                if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_CUESHEET && (existing_cuesheet_is_bad || 0 != cuesheet)) {
 
1834
                                        if(0 != cuesheet) {
 
1835
                                                flac__utils_printf(stderr, 1, "%s: WARNING, replacing cuesheet in input FLAC file with the one given on the command-line\n", e->inbasefilename);
 
1836
                                                if(e->treat_warnings_as_errors) {
 
1837
                                                        FLAC__metadata_object_delete(cuesheet);
 
1838
                                                        return false;
 
1839
                                                }
 
1840
                                        }
 
1841
                                        FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
 
1842
                                        flac_decoder_data->metadata_blocks[i] = 0;
 
1843
                                }
 
1844
                                else
 
1845
                                        flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
 
1846
                        }
 
1847
                        flac_decoder_data->num_metadata_blocks = j;
 
1848
                        if(0 != cuesheet && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
 
1849
                                /* prepend ours */
 
1850
                                FLAC__StreamMetadata *cs = FLAC__metadata_object_clone(cuesheet);
 
1851
                                if(0 == cs) {
 
1852
                                        flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for CUESHEET block\n", e->inbasefilename);
 
1853
                                        if(0 != cuesheet)
 
1854
                                                FLAC__metadata_object_delete(cuesheet);
 
1855
                                        return false;
 
1856
                                }
 
1857
                                for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
 
1858
                                        flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
 
1859
                                flac_decoder_data->metadata_blocks[1] = cs;
 
1860
                                flac_decoder_data->num_metadata_blocks++;
 
1861
                        }
 
1862
                }
 
1863
                {
 
1864
                        /*
 
1865
                         * next handle seektable: if -S- was specified, no
 
1866
                         * SEEKTABLE; else if -S was specified, use it/them;
 
1867
                         * else if file has existing SEEKTABLE and input size is
 
1868
                         * preserved (no --skip/--until/etc specified), keep it;
 
1869
                         * else use default seektable options
 
1870
                         *
 
1871
                         * note: meanings of num_requested_seek_points:
 
1872
                         *  -1 : no -S option given, default to some value
 
1873
                         *   0 : -S- given (no seektable)
 
1874
                         *  >0 : one or more -S options given
 
1875
                         */
 
1876
                        size_t i, j;
 
1877
                        FLAC__bool existing_seektable = false;
 
1878
                        for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
 
1879
                                if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE)
 
1880
                                        existing_seektable = true;
 
1881
                                if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_SEEKTABLE && (e->total_samples_to_encode != flac_decoder_data->metadata_blocks[0]->data.stream_info.total_samples || options.num_requested_seek_points >= 0)) {
 
1882
                                        if(options.num_requested_seek_points > 0) {
 
1883
                                                flac__utils_printf(stderr, 1, "%s: WARNING, replacing seektable in input FLAC file with the one given on the command-line\n", e->inbasefilename);
 
1884
                                                if(e->treat_warnings_as_errors) {
 
1885
                                                        if(0 != cuesheet)
 
1886
                                                                FLAC__metadata_object_delete(cuesheet);
 
1887
                                                        return false;
 
1888
                                                }
 
1889
                                        }
 
1890
                                        else if(options.num_requested_seek_points == 0)
 
1891
                                                ; /* no warning, silently delete existing SEEKTABLE since user specified --no-seektable (-S-) */
 
1892
                                        else {
 
1893
                                                flac__utils_printf(stderr, 1, "%s: WARNING, can't use existing seektable in input FLAC since the input size is changing or unknown, dropping existing SEEKTABLE block...\n", e->inbasefilename);
 
1894
                                                if(e->treat_warnings_as_errors) {
 
1895
                                                        if(0 != cuesheet)
 
1896
                                                                FLAC__metadata_object_delete(cuesheet);
 
1897
                                                        return false;
 
1898
                                                }
 
1899
                                        }
 
1900
                                        FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
 
1901
                                        flac_decoder_data->metadata_blocks[i] = 0;
 
1902
                                        existing_seektable = false;
 
1903
                                }
 
1904
                                else
 
1905
                                        flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
 
1906
                        }
 
1907
                        flac_decoder_data->num_metadata_blocks = j;
 
1908
                        if((options.num_requested_seek_points > 0 || (options.num_requested_seek_points < 0 && !existing_seektable)) && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
 
1909
                                /* prepend ours */
 
1910
                                FLAC__StreamMetadata *st = FLAC__metadata_object_clone(e->seek_table_template);
 
1911
                                if(0 == st) {
 
1912
                                        flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for SEEKTABLE block\n", e->inbasefilename);
 
1913
                                        if(0 != cuesheet)
 
1914
                                                FLAC__metadata_object_delete(cuesheet);
 
1915
                                        return false;
 
1916
                                }
 
1917
                                for(i = flac_decoder_data->num_metadata_blocks; i > 1; i--)
 
1918
                                        flac_decoder_data->metadata_blocks[i] = flac_decoder_data->metadata_blocks[i-1];
 
1919
                                flac_decoder_data->metadata_blocks[1] = st;
 
1920
                                flac_decoder_data->num_metadata_blocks++;
 
1921
                        }
 
1922
                }
 
1923
                {
 
1924
                        /*
 
1925
                         * finally handle padding: if --no-padding was specified,
 
1926
                         * then delete all padding; else if -P was specified,
 
1927
                         * use that instead of existing padding (if any); else
 
1928
                         * if existing file has padding, move all existing
 
1929
                         * padding blocks to one padding block at the end; else
 
1930
                         * use default padding.
 
1931
                         */
 
1932
                        int p = -1;
 
1933
                        size_t i, j;
 
1934
                        for(i = 0, j = 0; i < flac_decoder_data->num_metadata_blocks; i++) {
 
1935
                                if(flac_decoder_data->metadata_blocks[i]->type == FLAC__METADATA_TYPE_PADDING) {
 
1936
                                        if(p < 0)
 
1937
                                                p = 0;
 
1938
                                        p += flac_decoder_data->metadata_blocks[i]->length;
 
1939
                                        FLAC__metadata_object_delete(flac_decoder_data->metadata_blocks[i]);
 
1940
                                        flac_decoder_data->metadata_blocks[i] = 0;
 
1941
                                }
 
1942
                                else
 
1943
                                        flac_decoder_data->metadata_blocks[j++] = flac_decoder_data->metadata_blocks[i];
 
1944
                        }
 
1945
                        flac_decoder_data->num_metadata_blocks = j;
 
1946
                        if(options.padding > 0)
 
1947
                                p = options.padding;
 
1948
                        if(p < 0)
 
1949
                                p = e->total_samples_to_encode / e->sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8;
 
1950
                        if(options.padding != 0) {
 
1951
                                if(p > 0 && flac_decoder_data->num_metadata_blocks < sizeof(flac_decoder_data->metadata_blocks)/sizeof(flac_decoder_data->metadata_blocks[0])) {
 
1952
                                        flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
 
1953
                                        if(0 == flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]) {
 
1954
                                                flac__utils_printf(stderr, 1, "%s: ERROR allocating memory for PADDING block\n", e->inbasefilename);
 
1955
                                                if(0 != cuesheet)
 
1956
                                                        FLAC__metadata_object_delete(cuesheet);
 
1957
                                                return false;
 
1958
                                        }
 
1959
                                        flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->is_last = false; /* the encoder will set this for us */
 
1960
                                        flac_decoder_data->metadata_blocks[flac_decoder_data->num_metadata_blocks]->length = p;
 
1961
                                        flac_decoder_data->num_metadata_blocks++;
 
1962
                                }
 
1963
                        }
 
1964
                }
 
1965
                metadata = &flac_decoder_data->metadata_blocks[1]; /* don't include STREAMINFO */
 
1966
                num_metadata = flac_decoder_data->num_metadata_blocks - 1;
 
1967
        }
 
1968
        else {
 
1969
                /*
 
1970
                 * we're not encoding from FLAC so we will build the metadata
 
1971
                 * from scratch
 
1972
                 */
 
1973
                num_metadata = 0;
 
1974
                if(e->seek_table_template->data.seek_table.num_points > 0) {
 
1975
                        e->seek_table_template->is_last = false; /* the encoder will set this for us */
 
1976
                        metadata[num_metadata++] = e->seek_table_template;
 
1977
                }
 
1978
                if(0 != cuesheet)
 
1979
                        metadata[num_metadata++] = cuesheet;
 
1980
                if(channel_mask) {
 
1981
                        if(!flac__utils_set_channel_mask_tag(options.vorbis_comment, channel_mask)) {
 
1982
                                flac__utils_printf(stderr, 1, "%s: ERROR adding channel mask tag\n", e->inbasefilename);
 
1983
                                if(0 != cuesheet)
 
1984
                                        FLAC__metadata_object_delete(cuesheet);
 
1985
                                return false;
 
1986
                        }
 
1987
                }
 
1988
                metadata[num_metadata++] = options.vorbis_comment;
 
1989
                for(i = 0; i < options.num_pictures; i++)
 
1990
                        metadata[num_metadata++] = options.pictures[i];
 
1991
                if(options.padding != 0) {
 
1992
                        padding.is_last = false; /* the encoder will set this for us */
 
1993
                        padding.type = FLAC__METADATA_TYPE_PADDING;
 
1994
                        padding.length = (unsigned)(options.padding>0? options.padding : (e->total_samples_to_encode / e->sample_rate < 20*60? FLAC_ENCODE__DEFAULT_PADDING : FLAC_ENCODE__DEFAULT_PADDING*8));
 
1995
                        metadata[num_metadata++] = &padding;
 
1996
                }
 
1997
        }
 
1998
 
 
1999
        /* check for a few things that have not already been checked.  the
 
2000
         * FLAC__stream_encoder_init*() will check it but only return
 
2001
         * FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA so we check some
 
2002
         * up front to give a better error message.
 
2003
         */
 
2004
        if(!verify_metadata(e, metadata, num_metadata)) {
 
2005
                if(0 != cuesheet)
 
2006
                        FLAC__metadata_object_delete(cuesheet);
 
2007
                return false;
 
2008
        }
 
2009
 
 
2010
        FLAC__stream_encoder_set_verify(e->encoder, options.verify);
 
2011
        FLAC__stream_encoder_set_streamable_subset(e->encoder, !options.lax);
 
2012
        FLAC__stream_encoder_set_channels(e->encoder, channels);
 
2013
        FLAC__stream_encoder_set_bits_per_sample(e->encoder, bps);
 
2014
        FLAC__stream_encoder_set_sample_rate(e->encoder, sample_rate);
 
2015
        for(i = 0; i < options.num_compression_settings; i++) {
 
2016
                switch(options.compression_settings[i].type) {
 
2017
                        case CST_BLOCKSIZE:
 
2018
                                FLAC__stream_encoder_set_blocksize(e->encoder, options.compression_settings[i].value.t_unsigned);
 
2019
                                break;
 
2020
                        case CST_COMPRESSION_LEVEL:
 
2021
                                FLAC__stream_encoder_set_compression_level(e->encoder, options.compression_settings[i].value.t_unsigned);
 
2022
                                apodizations[0] = '\0';
 
2023
                                break;
 
2024
                        case CST_DO_MID_SIDE:
 
2025
                                FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder, options.compression_settings[i].value.t_bool);
 
2026
                                break;
 
2027
                        case CST_LOOSE_MID_SIDE:
 
2028
                                FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder, options.compression_settings[i].value.t_bool);
 
2029
                                break;
 
2030
                        case CST_APODIZATION:
 
2031
                                if(strlen(apodizations)+strlen(options.compression_settings[i].value.t_string)+2 >= sizeof(apodizations)) {
 
2032
                                        flac__utils_printf(stderr, 1, "%s: ERROR: too many apodization functions requested\n", e->inbasefilename);
 
2033
                                        if(0 != cuesheet)
 
2034
                                                FLAC__metadata_object_delete(cuesheet);
 
2035
                                        return false;
 
2036
                                }
 
2037
                                else {
 
2038
                                        strcat(apodizations, options.compression_settings[i].value.t_string);
 
2039
                                        strcat(apodizations, ";");
 
2040
                                }
 
2041
                                break;
 
2042
                        case CST_MAX_LPC_ORDER:
 
2043
                                FLAC__stream_encoder_set_max_lpc_order(e->encoder, options.compression_settings[i].value.t_unsigned);
 
2044
                                break;
 
2045
                        case CST_QLP_COEFF_PRECISION:
 
2046
                                FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder, options.compression_settings[i].value.t_unsigned);
 
2047
                                break;
 
2048
                        case CST_DO_QLP_COEFF_PREC_SEARCH:
 
2049
                                FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder, options.compression_settings[i].value.t_bool);
 
2050
                                break;
 
2051
                        case CST_DO_ESCAPE_CODING:
 
2052
                                FLAC__stream_encoder_set_do_escape_coding(e->encoder, options.compression_settings[i].value.t_bool);
 
2053
                                break;
 
2054
                        case CST_DO_EXHAUSTIVE_MODEL_SEARCH:
 
2055
                                FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder, options.compression_settings[i].value.t_bool);
 
2056
                                break;
 
2057
                        case CST_MIN_RESIDUAL_PARTITION_ORDER:
 
2058
                                FLAC__stream_encoder_set_min_residual_partition_order(e->encoder, options.compression_settings[i].value.t_unsigned);
 
2059
                                break;
 
2060
                        case CST_MAX_RESIDUAL_PARTITION_ORDER:
 
2061
                                FLAC__stream_encoder_set_max_residual_partition_order(e->encoder, options.compression_settings[i].value.t_unsigned);
 
2062
                                break;
 
2063
                        case CST_RICE_PARAMETER_SEARCH_DIST:
 
2064
                                FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder, options.compression_settings[i].value.t_unsigned);
 
2065
                                break;
 
2066
                }
 
2067
        }
 
2068
        if(*apodizations)
 
2069
                FLAC__stream_encoder_set_apodization(e->encoder, apodizations);
 
2070
        FLAC__stream_encoder_set_total_samples_estimate(e->encoder, e->total_samples_to_encode);
 
2071
        FLAC__stream_encoder_set_metadata(e->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
 
2072
 
 
2073
        FLAC__stream_encoder_disable_constant_subframes(e->encoder, options.debug.disable_constant_subframes);
 
2074
        FLAC__stream_encoder_disable_fixed_subframes(e->encoder, options.debug.disable_fixed_subframes);
 
2075
        FLAC__stream_encoder_disable_verbatim_subframes(e->encoder, options.debug.disable_verbatim_subframes);
 
2076
 
 
2077
#if FLAC__HAS_OGG
1411
2078
        if(e->use_ogg) {
1412
 
                if(e->is_stdout) {
1413
 
                        OggFLAC__stream_encoder_set_serial_number(e->encoder.ogg.stream, options.serial_number);
1414
 
                        OggFLAC__stream_encoder_set_verify(e->encoder.ogg.stream, options.verify);
1415
 
                        OggFLAC__stream_encoder_set_streamable_subset(e->encoder.ogg.stream, !options.lax);
1416
 
                        OggFLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.ogg.stream, options.do_mid_side);
1417
 
                        OggFLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.ogg.stream, options.loose_mid_side);
1418
 
                        OggFLAC__stream_encoder_set_channels(e->encoder.ogg.stream, channels);
1419
 
                        OggFLAC__stream_encoder_set_bits_per_sample(e->encoder.ogg.stream, bps);
1420
 
                        OggFLAC__stream_encoder_set_sample_rate(e->encoder.ogg.stream, sample_rate);
1421
 
                        OggFLAC__stream_encoder_set_blocksize(e->encoder.ogg.stream, options.blocksize);
1422
 
                        OggFLAC__stream_encoder_set_max_lpc_order(e->encoder.ogg.stream, options.max_lpc_order);
1423
 
                        OggFLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.ogg.stream, options.qlp_coeff_precision);
1424
 
                        OggFLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg.stream, options.do_qlp_coeff_prec_search);
1425
 
                        OggFLAC__stream_encoder_set_do_escape_coding(e->encoder.ogg.stream, options.do_escape_coding);
1426
 
                        OggFLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.ogg.stream, options.do_exhaustive_model_search);
1427
 
                        OggFLAC__stream_encoder_set_min_residual_partition_order(e->encoder.ogg.stream, options.min_residual_partition_order);
1428
 
                        OggFLAC__stream_encoder_set_max_residual_partition_order(e->encoder.ogg.stream, options.max_residual_partition_order);
1429
 
                        OggFLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.ogg.stream, options.rice_parameter_search_dist);
1430
 
                        OggFLAC__stream_encoder_set_total_samples_estimate(e->encoder.ogg.stream, e->total_samples_to_encode);
1431
 
                        OggFLAC__stream_encoder_set_metadata(e->encoder.ogg.stream, (num_metadata > 0)? metadata : 0, num_metadata);
1432
 
                        OggFLAC__stream_encoder_set_write_callback(e->encoder.ogg.stream, ogg_stream_encoder_write_callback);
1433
 
                        OggFLAC__stream_encoder_set_metadata_callback(e->encoder.ogg.stream, ogg_stream_encoder_metadata_callback);
1434
 
                        OggFLAC__stream_encoder_set_client_data(e->encoder.ogg.stream, e);
1435
 
 
1436
 
                        OggFLAC__stream_encoder_disable_constant_subframes(e->encoder.ogg.stream, options.debug.disable_constant_subframes);
1437
 
                        OggFLAC__stream_encoder_disable_fixed_subframes(e->encoder.ogg.stream, options.debug.disable_fixed_subframes);
1438
 
                        OggFLAC__stream_encoder_disable_verbatim_subframes(e->encoder.ogg.stream, options.debug.disable_verbatim_subframes);
1439
 
 
1440
 
                        if(OggFLAC__stream_encoder_init(e->encoder.ogg.stream) != FLAC__STREAM_ENCODER_OK) {
1441
 
                                print_error_with_state(e, "ERROR initializing encoder");
1442
 
                                if(0 != cuesheet)
1443
 
                                        FLAC__metadata_object_delete(cuesheet);
1444
 
                                return false;
1445
 
                        }
1446
 
                }
1447
 
                else {
1448
 
                        OggFLAC__file_encoder_set_serial_number(e->encoder.ogg.file, options.serial_number);
1449
 
                        OggFLAC__file_encoder_set_filename(e->encoder.ogg.file, e->outfilename);
1450
 
                        OggFLAC__file_encoder_set_verify(e->encoder.ogg.file, options.verify);
1451
 
                        OggFLAC__file_encoder_set_streamable_subset(e->encoder.ogg.file, !options.lax);
1452
 
                        OggFLAC__file_encoder_set_do_mid_side_stereo(e->encoder.ogg.file, options.do_mid_side);
1453
 
                        OggFLAC__file_encoder_set_loose_mid_side_stereo(e->encoder.ogg.file, options.loose_mid_side);
1454
 
                        OggFLAC__file_encoder_set_channels(e->encoder.ogg.file, channels);
1455
 
                        OggFLAC__file_encoder_set_bits_per_sample(e->encoder.ogg.file, bps);
1456
 
                        OggFLAC__file_encoder_set_sample_rate(e->encoder.ogg.file, sample_rate);
1457
 
                        OggFLAC__file_encoder_set_blocksize(e->encoder.ogg.file, options.blocksize);
1458
 
                        OggFLAC__file_encoder_set_max_lpc_order(e->encoder.ogg.file, options.max_lpc_order);
1459
 
                        OggFLAC__file_encoder_set_qlp_coeff_precision(e->encoder.ogg.file, options.qlp_coeff_precision);
1460
 
                        OggFLAC__file_encoder_set_do_qlp_coeff_prec_search(e->encoder.ogg.file, options.do_qlp_coeff_prec_search);
1461
 
                        OggFLAC__file_encoder_set_do_escape_coding(e->encoder.ogg.file, options.do_escape_coding);
1462
 
                        OggFLAC__file_encoder_set_do_exhaustive_model_search(e->encoder.ogg.file, options.do_exhaustive_model_search);
1463
 
                        OggFLAC__file_encoder_set_min_residual_partition_order(e->encoder.ogg.file, options.min_residual_partition_order);
1464
 
                        OggFLAC__file_encoder_set_max_residual_partition_order(e->encoder.ogg.file, options.max_residual_partition_order);
1465
 
                        OggFLAC__file_encoder_set_rice_parameter_search_dist(e->encoder.ogg.file, options.rice_parameter_search_dist);
1466
 
                        OggFLAC__file_encoder_set_total_samples_estimate(e->encoder.ogg.file, e->total_samples_to_encode);
1467
 
                        OggFLAC__file_encoder_set_metadata(e->encoder.ogg.file, (num_metadata > 0)? metadata : 0, num_metadata);
1468
 
                        OggFLAC__file_encoder_set_progress_callback(e->encoder.ogg.file, ogg_file_encoder_progress_callback);
1469
 
                        OggFLAC__file_encoder_set_client_data(e->encoder.ogg.file, e);
1470
 
 
1471
 
                        OggFLAC__file_encoder_disable_constant_subframes(e->encoder.ogg.file, options.debug.disable_constant_subframes);
1472
 
                        OggFLAC__file_encoder_disable_fixed_subframes(e->encoder.ogg.file, options.debug.disable_fixed_subframes);
1473
 
                        OggFLAC__file_encoder_disable_verbatim_subframes(e->encoder.ogg.file, options.debug.disable_verbatim_subframes);
1474
 
 
1475
 
                        if(OggFLAC__file_encoder_init(e->encoder.ogg.file) != OggFLAC__FILE_ENCODER_OK) {
1476
 
                                print_error_with_state(e, "ERROR initializing encoder");
1477
 
                                if(0 != cuesheet)
1478
 
                                        FLAC__metadata_object_delete(cuesheet);
1479
 
                                return false;
1480
 
                        }
1481
 
                }
 
2079
                FLAC__stream_encoder_set_ogg_serial_number(e->encoder, options.serial_number);
 
2080
 
 
2081
                init_status = FLAC__stream_encoder_init_ogg_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
1482
2082
        }
1483
2083
        else
1484
2084
#endif
1485
 
        if(e->is_stdout) {
1486
 
                FLAC__stream_encoder_set_verify(e->encoder.flac.stream, options.verify);
1487
 
                FLAC__stream_encoder_set_streamable_subset(e->encoder.flac.stream, !options.lax);
1488
 
                FLAC__stream_encoder_set_do_mid_side_stereo(e->encoder.flac.stream, options.do_mid_side);
1489
 
                FLAC__stream_encoder_set_loose_mid_side_stereo(e->encoder.flac.stream, options.loose_mid_side);
1490
 
                FLAC__stream_encoder_set_channels(e->encoder.flac.stream, channels);
1491
 
                FLAC__stream_encoder_set_bits_per_sample(e->encoder.flac.stream, bps);
1492
 
                FLAC__stream_encoder_set_sample_rate(e->encoder.flac.stream, sample_rate);
1493
 
                FLAC__stream_encoder_set_blocksize(e->encoder.flac.stream, options.blocksize);
1494
 
                FLAC__stream_encoder_set_max_lpc_order(e->encoder.flac.stream, options.max_lpc_order);
1495
 
                FLAC__stream_encoder_set_qlp_coeff_precision(e->encoder.flac.stream, options.qlp_coeff_precision);
1496
 
                FLAC__stream_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.stream, options.do_qlp_coeff_prec_search);
1497
 
                FLAC__stream_encoder_set_do_escape_coding(e->encoder.flac.stream, options.do_escape_coding);
1498
 
                FLAC__stream_encoder_set_do_exhaustive_model_search(e->encoder.flac.stream, options.do_exhaustive_model_search);
1499
 
                FLAC__stream_encoder_set_min_residual_partition_order(e->encoder.flac.stream, options.min_residual_partition_order);
1500
 
                FLAC__stream_encoder_set_max_residual_partition_order(e->encoder.flac.stream, options.max_residual_partition_order);
1501
 
                FLAC__stream_encoder_set_rice_parameter_search_dist(e->encoder.flac.stream, options.rice_parameter_search_dist);
1502
 
                FLAC__stream_encoder_set_total_samples_estimate(e->encoder.flac.stream, e->total_samples_to_encode);
1503
 
                FLAC__stream_encoder_set_metadata(e->encoder.flac.stream, (num_metadata > 0)? metadata : 0, num_metadata);
1504
 
                FLAC__stream_encoder_set_write_callback(e->encoder.flac.stream, flac_stream_encoder_write_callback);
1505
 
                FLAC__stream_encoder_set_metadata_callback(e->encoder.flac.stream, flac_stream_encoder_metadata_callback);
1506
 
                FLAC__stream_encoder_set_client_data(e->encoder.flac.stream, e);
1507
 
 
1508
 
                FLAC__stream_encoder_disable_constant_subframes(e->encoder.flac.stream, options.debug.disable_constant_subframes);
1509
 
                FLAC__stream_encoder_disable_fixed_subframes(e->encoder.flac.stream, options.debug.disable_fixed_subframes);
1510
 
                FLAC__stream_encoder_disable_verbatim_subframes(e->encoder.flac.stream, options.debug.disable_verbatim_subframes);
1511
 
 
1512
 
                if(FLAC__stream_encoder_init(e->encoder.flac.stream) != FLAC__STREAM_ENCODER_OK) {
1513
 
                        print_error_with_state(e, "ERROR initializing encoder");
1514
 
                        if(0 != cuesheet)
1515
 
                                FLAC__metadata_object_delete(cuesheet);
1516
 
                        return false;
1517
 
                }
1518
 
        }
1519
 
        else {
1520
 
                FLAC__file_encoder_set_filename(e->encoder.flac.file, e->outfilename);
1521
 
                FLAC__file_encoder_set_verify(e->encoder.flac.file, options.verify);
1522
 
                FLAC__file_encoder_set_streamable_subset(e->encoder.flac.file, !options.lax);
1523
 
                FLAC__file_encoder_set_do_mid_side_stereo(e->encoder.flac.file, options.do_mid_side);
1524
 
                FLAC__file_encoder_set_loose_mid_side_stereo(e->encoder.flac.file, options.loose_mid_side);
1525
 
                FLAC__file_encoder_set_channels(e->encoder.flac.file, channels);
1526
 
                FLAC__file_encoder_set_bits_per_sample(e->encoder.flac.file, bps);
1527
 
                FLAC__file_encoder_set_sample_rate(e->encoder.flac.file, sample_rate);
1528
 
                FLAC__file_encoder_set_blocksize(e->encoder.flac.file, options.blocksize);
1529
 
                FLAC__file_encoder_set_max_lpc_order(e->encoder.flac.file, options.max_lpc_order);
1530
 
                FLAC__file_encoder_set_qlp_coeff_precision(e->encoder.flac.file, options.qlp_coeff_precision);
1531
 
                FLAC__file_encoder_set_do_qlp_coeff_prec_search(e->encoder.flac.file, options.do_qlp_coeff_prec_search);
1532
 
                FLAC__file_encoder_set_do_escape_coding(e->encoder.flac.file, options.do_escape_coding);
1533
 
                FLAC__file_encoder_set_do_exhaustive_model_search(e->encoder.flac.file, options.do_exhaustive_model_search);
1534
 
                FLAC__file_encoder_set_min_residual_partition_order(e->encoder.flac.file, options.min_residual_partition_order);
1535
 
                FLAC__file_encoder_set_max_residual_partition_order(e->encoder.flac.file, options.max_residual_partition_order);
1536
 
                FLAC__file_encoder_set_rice_parameter_search_dist(e->encoder.flac.file, options.rice_parameter_search_dist);
1537
 
                FLAC__file_encoder_set_total_samples_estimate(e->encoder.flac.file, e->total_samples_to_encode);
1538
 
                FLAC__file_encoder_set_metadata(e->encoder.flac.file, (num_metadata > 0)? metadata : 0, num_metadata);
1539
 
                FLAC__file_encoder_set_progress_callback(e->encoder.flac.file, flac_file_encoder_progress_callback);
1540
 
                FLAC__file_encoder_set_client_data(e->encoder.flac.file, e);
1541
 
 
1542
 
                FLAC__file_encoder_disable_constant_subframes(e->encoder.flac.file, options.debug.disable_constant_subframes);
1543
 
                FLAC__file_encoder_disable_fixed_subframes(e->encoder.flac.file, options.debug.disable_fixed_subframes);
1544
 
                FLAC__file_encoder_disable_verbatim_subframes(e->encoder.flac.file, options.debug.disable_verbatim_subframes);
1545
 
 
1546
 
                if(FLAC__file_encoder_init(e->encoder.flac.file) != FLAC__FILE_ENCODER_OK) {
1547
 
                        print_error_with_state(e, "ERROR initializing encoder");
1548
 
                        if(0 != cuesheet)
1549
 
                                FLAC__metadata_object_delete(cuesheet);
1550
 
                        return false;
1551
 
                }
1552
 
        }
 
2085
        {
 
2086
                init_status = FLAC__stream_encoder_init_file(e->encoder, e->is_stdout? 0 : e->outfilename, encoder_progress_callback, /*client_data=*/e);
 
2087
        }
 
2088
 
 
2089
        if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
 
2090
                print_error_with_init_status(e, "ERROR initializing encoder", init_status);
 
2091
                if(FLAC__stream_encoder_get_state(e->encoder) != FLAC__STREAM_ENCODER_IO_ERROR)
 
2092
                        e->outputfile_opened = true;
 
2093
                if(0 != cuesheet)
 
2094
                        FLAC__metadata_object_delete(cuesheet);
 
2095
                return false;
 
2096
        }
 
2097
        else
 
2098
                e->outputfile_opened = true;
 
2099
 
 
2100
        e->stats_mask =
 
2101
                (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) && FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x07 :
 
2102
                (FLAC__stream_encoder_get_do_exhaustive_model_search(e->encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(e->encoder))? 0x0f :
 
2103
                0x3f;
1553
2104
 
1554
2105
        if(0 != cuesheet)
1555
2106
                FLAC__metadata_object_delete(cuesheet);
1562
2113
        if(e->replay_gain) {
1563
2114
                if(!grabbag__replaygain_analyze(buffer, e->channels==2, e->bits_per_sample, samples)) {
1564
2115
                        flac__utils_printf(stderr, 1, "%s: WARNING, error while calculating ReplayGain\n", e->inbasefilename);
 
2116
                        if(e->treat_warnings_as_errors)
 
2117
                                return false;
1565
2118
                }
1566
2119
        }
1567
2120
 
1568
 
#ifdef FLAC__HAS_OGG
1569
 
        if(e->use_ogg) {
1570
 
                if(e->is_stdout) {
1571
 
                        return OggFLAC__stream_encoder_process(e->encoder.ogg.stream, buffer, samples);
1572
 
                }
1573
 
                else {
1574
 
                        return OggFLAC__file_encoder_process(e->encoder.ogg.file, buffer, samples);
1575
 
                }
1576
 
        }
1577
 
        else
1578
 
#endif
1579
 
        if(e->is_stdout) {
1580
 
                return FLAC__stream_encoder_process(e->encoder.flac.stream, buffer, samples);
1581
 
        }
1582
 
        else {
1583
 
                return FLAC__file_encoder_process(e->encoder.flac.file, buffer, samples);
1584
 
        }
 
2121
        return FLAC__stream_encoder_process(e->encoder, buffer, samples);
1585
2122
}
1586
2123
 
1587
2124
FLAC__bool convert_to_seek_table_template(const char *requested_seek_points, int num_requested_seek_points, FLAC__StreamMetadata *cuesheet, EncoderSession *e)
1621
2158
        if(has_real_points) {
1622
2159
                if(e->is_stdout) {
1623
2160
                        flac__utils_printf(stderr, 1, "%s: WARNING, cannot write back seekpoints when encoding to stdout\n", e->inbasefilename);
 
2161
                        if(e->treat_warnings_as_errors)
 
2162
                                return false;
1624
2163
                }
1625
2164
        }
1626
2165
 
1672
2211
        return true;
1673
2212
}
1674
2213
 
1675
 
void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps)
 
2214
FLAC__bool verify_metadata(const EncoderSession *e, FLAC__StreamMetadata **metadata, unsigned num_metadata)
 
2215
{
 
2216
        FLAC__bool metadata_picture_has_type1 = false;
 
2217
        FLAC__bool metadata_picture_has_type2 = false;
 
2218
        unsigned i;
 
2219
 
 
2220
        FLAC__ASSERT(0 != metadata);
 
2221
        for(i = 0; i < num_metadata; i++) {
 
2222
                const FLAC__StreamMetadata *m = metadata[i];
 
2223
                if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
 
2224
                        if(!FLAC__format_seektable_is_legal(&m->data.seek_table)) {
 
2225
                                flac__utils_printf(stderr, 1, "%s: ERROR: SEEKTABLE metadata block is invalid\n", e->inbasefilename);
 
2226
                                return false;
 
2227
                        }
 
2228
                }
 
2229
                else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
 
2230
                        if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0)) {
 
2231
                                flac__utils_printf(stderr, 1, "%s: ERROR: CUESHEET metadata block is invalid\n", e->inbasefilename);
 
2232
                                return false;
 
2233
                        }
 
2234
                }
 
2235
                else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
 
2236
                        const char *error = 0;
 
2237
                        if(!FLAC__format_picture_is_legal(&m->data.picture, &error)) {
 
2238
                                flac__utils_printf(stderr, 1, "%s: ERROR: PICTURE metadata block is invalid: %s\n", e->inbasefilename, error);
 
2239
                                return false;
 
2240
                        }
 
2241
                        if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
 
2242
                                if(metadata_picture_has_type1) {
 
2243
                                        flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 1 (32x32 icon) in the file\n", e->inbasefilename);
 
2244
                                        return false;
 
2245
                                }
 
2246
                                metadata_picture_has_type1 = true;
 
2247
                        }
 
2248
                        else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
 
2249
                                if(metadata_picture_has_type2) {
 
2250
                                        flac__utils_printf(stderr, 1, "%s: ERROR: there may only be one picture of type 2 (icon) in the file\n", e->inbasefilename);
 
2251
                                        return false;
 
2252
                                }
 
2253
                                metadata_picture_has_type2 = true;
 
2254
                        }
 
2255
                }
 
2256
        }
 
2257
 
 
2258
        return true;
 
2259
}
 
2260
 
 
2261
FLAC__bool format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned shift, size_t *channel_map)
1676
2262
{
1677
2263
        unsigned wide_sample, sample, channel, byte;
 
2264
        FLAC__int32 *out[FLAC__MAX_CHANNELS];
 
2265
 
 
2266
        if(0 == channel_map) {
 
2267
                for(channel = 0; channel < channels; channel++)
 
2268
                        out[channel] = dest[channel];
 
2269
        }
 
2270
        else {
 
2271
                for(channel = 0; channel < channels; channel++)
 
2272
                        out[channel] = dest[channel_map[channel]];
 
2273
        }
1678
2274
 
1679
2275
        if(bps == 8) {
1680
2276
                if(is_unsigned_samples) {
1681
2277
                        for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1682
2278
                                for(channel = 0; channel < channels; channel++, sample++)
1683
 
                                        dest[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
 
2279
                                        out[channel][wide_sample] = (FLAC__int32)ucbuffer_[sample] - 0x80;
1684
2280
                }
1685
2281
                else {
1686
2282
                        for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1687
2283
                                for(channel = 0; channel < channels; channel++, sample++)
1688
 
                                        dest[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
 
2284
                                        out[channel][wide_sample] = (FLAC__int32)scbuffer_[sample];
1689
2285
                }
1690
2286
        }
1691
2287
        else if(bps == 16) {
1701
2297
                if(is_unsigned_samples) {
1702
2298
                        for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1703
2299
                                for(channel = 0; channel < channels; channel++, sample++)
1704
 
                                        dest[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
 
2300
                                        out[channel][wide_sample] = (FLAC__int32)usbuffer_[sample] - 0x8000;
1705
2301
                }
1706
2302
                else {
1707
2303
                        for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1708
2304
                                for(channel = 0; channel < channels; channel++, sample++)
1709
 
                                        dest[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
 
2305
                                        out[channel][wide_sample] = (FLAC__int32)ssbuffer_[sample];
1710
2306
                }
1711
2307
        }
1712
2308
        else if(bps == 24) {
1722
2318
                if(is_unsigned_samples) {
1723
2319
                        for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1724
2320
                                for(channel = 0; channel < channels; channel++, sample++) {
1725
 
                                        dest[channel][wide_sample]  = ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1726
 
                                        dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1727
 
                                        dest[channel][wide_sample] |= ucbuffer_[byte++];
1728
 
                                        dest[channel][wide_sample] -= 0x800000;
 
2321
                                        out[channel][wide_sample]  = ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
 
2322
                                        out[channel][wide_sample] |= ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
 
2323
                                        out[channel][wide_sample] |= ucbuffer_[byte++];
 
2324
                                        out[channel][wide_sample] -= 0x800000;
1729
2325
                                }
1730
2326
                }
1731
2327
                else {
1732
2328
                        for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1733
2329
                                for(channel = 0; channel < channels; channel++, sample++) {
1734
 
                                        dest[channel][wide_sample]  = scbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1735
 
                                        dest[channel][wide_sample] |= ucbuffer_[byte++]; dest[channel][wide_sample] <<= 8;
1736
 
                                        dest[channel][wide_sample] |= ucbuffer_[byte++];
 
2330
                                        out[channel][wide_sample]  = scbuffer_[byte++]; out[channel][wide_sample] <<= 8;
 
2331
                                        out[channel][wide_sample] |= ucbuffer_[byte++]; out[channel][wide_sample] <<= 8;
 
2332
                                        out[channel][wide_sample] |= ucbuffer_[byte++];
1737
2333
                                }
1738
2334
                }
1739
2335
        }
1740
2336
        else {
1741
2337
                FLAC__ASSERT(0);
1742
2338
        }
1743
 
}
1744
 
 
1745
 
#ifdef FLAC__HAS_OGG
1746
 
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)
1747
 
{
1748
 
        EncoderSession *encoder_session = (EncoderSession*)client_data;
1749
 
 
1750
 
        (void)encoder;
1751
 
 
1752
 
        encoder_session->bytes_written += bytes;
1753
 
        /*
1754
 
         * With Ogg FLAC we don't get one write callback per frame and
1755
 
         * we don't have a good number for 'samples', so we estimate based
1756
 
         * on the frame number and the knowledge that all blocks (except
1757
 
         * the last) are the same size.
1758
 
         */
1759
 
        (void)samples;
1760
 
        encoder_session->samples_written = (current_frame+1) * encoder_session->blocksize;
1761
 
 
1762
 
        if(encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
1763
 
                print_stats(encoder_session);
1764
 
 
1765
 
        if(flac__utils_fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
1766
 
                return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1767
 
        else
1768
 
                return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1769
 
}
1770
 
 
1771
 
void ogg_stream_encoder_metadata_callback(const OggFLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1772
 
{
1773
 
        // do nothing, for compatibilty.  soon we will be using the ogg file encoder anyway.
1774
 
        (void)encoder, (void)metadata, (void)client_data;
1775
 
}
1776
 
 
1777
 
void ogg_file_encoder_progress_callback(const OggFLAC__FileEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
1778
 
{
1779
 
        EncoderSession *encoder_session = (EncoderSession*)client_data;
1780
 
 
1781
 
        (void)encoder;
1782
 
 
1783
 
        /*
1784
 
         * With Ogg FLAC we don't get a value for 'samples_written', so we
1785
 
         * estimate based on the frames written and the knowledge that all
1786
 
         * blocks (except the last) are the same size.
1787
 
         */
1788
 
        samples_written = frames_written * encoder_session->blocksize;
1789
 
        flac_file_encoder_progress_callback(0, bytes_written, samples_written, frames_written, total_frames_estimate, client_data);
1790
 
}
1791
 
 
1792
 
#endif
1793
 
 
1794
 
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)
1795
 
{
1796
 
        EncoderSession *encoder_session = (EncoderSession*)client_data;
1797
 
 
1798
 
        (void)encoder;
1799
 
 
1800
 
        encoder_session->bytes_written += bytes;
1801
 
        encoder_session->samples_written += samples;
1802
 
 
1803
 
        if(samples && encoder_session->total_samples_to_encode > 0 && !(current_frame & encoder_session->stats_mask))
1804
 
                print_stats(encoder_session);
1805
 
 
1806
 
        if(flac__utils_fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_session->fout) == bytes)
1807
 
                return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1808
 
        else
1809
 
                return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1810
 
}
1811
 
 
1812
 
void flac_stream_encoder_metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1813
 
{
1814
 
        /*
1815
 
         * Nothing to do; if we get here, we're decoding to stdout, in
1816
 
         * which case we can't seek backwards to write new metadata.
1817
 
         */
1818
 
        (void)encoder, (void)metadata, (void)client_data;
1819
 
}
1820
 
 
1821
 
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)
 
2339
        if(shift > 0) {
 
2340
                FLAC__int32 mask = (1<<shift)-1;
 
2341
                for(wide_sample = 0; wide_sample < wide_samples; wide_sample++)
 
2342
                        for(channel = 0; channel < channels; channel++) {
 
2343
                                if(out[channel][wide_sample] & mask) {
 
2344
                                        flac__utils_printf(stderr, 1, "ERROR during read, sample data (channel#%u sample#%u = %d) has non-zero least-significant bits\n  WAVE/AIFF header said the last %u bits are not significant and should be zero.\n", channel, wide_sample, out[channel][wide_sample], shift);
 
2345
                                        return false;
 
2346
                                }
 
2347
                                out[channel][wide_sample] >>= shift;
 
2348
                        }
 
2349
        }
 
2350
        return true;
 
2351
}
 
2352
 
 
2353
void encoder_progress_callback(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
1822
2354
{
1823
2355
        EncoderSession *encoder_session = (EncoderSession*)client_data;
1824
2356
 
1831
2363
                print_stats(encoder_session);
1832
2364
}
1833
2365
 
1834
 
FLAC__bool parse_cuesheet_(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset)
 
2366
FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
 
2367
{
 
2368
        size_t n = 0;
 
2369
        FLACDecoderData *data = (FLACDecoderData*)client_data;
 
2370
        (void)decoder;
 
2371
 
 
2372
        if (data->fatal_error)
 
2373
                return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
 
2374
 
 
2375
        /* use up lookahead first */
 
2376
        if (data->lookahead_length) {
 
2377
                n = min(data->lookahead_length, *bytes);
 
2378
                memcpy(buffer, data->lookahead, n);
 
2379
                buffer += n;
 
2380
                data->lookahead += n;
 
2381
                data->lookahead_length -= n;
 
2382
        }
 
2383
 
 
2384
        /* get the rest from file */
 
2385
        if (*bytes > n) {
 
2386
                *bytes = n + fread(buffer, 1, *bytes-n, data->encoder_session->fin);
 
2387
                if(ferror(data->encoder_session->fin))
 
2388
                        return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
 
2389
                else if(0 == *bytes)
 
2390
                        return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
 
2391
                else
 
2392
                        return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
 
2393
        }
 
2394
        else
 
2395
                return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
 
2396
}
 
2397
 
 
2398
FLAC__StreamDecoderSeekStatus flac_decoder_seek_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
 
2399
{
 
2400
        FLACDecoderData *data = (FLACDecoderData*)client_data;
 
2401
        (void)decoder;
 
2402
 
 
2403
        if(fseeko(data->encoder_session->fin, (off_t)absolute_byte_offset, SEEK_SET) < 0)
 
2404
                return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
 
2405
        else
 
2406
                return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
 
2407
}
 
2408
 
 
2409
FLAC__StreamDecoderTellStatus flac_decoder_tell_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
 
2410
{
 
2411
        FLACDecoderData *data = (FLACDecoderData*)client_data;
 
2412
        off_t pos;
 
2413
        (void)decoder;
 
2414
 
 
2415
        if((pos = ftello(data->encoder_session->fin)) < 0)
 
2416
                return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
 
2417
        else {
 
2418
                *absolute_byte_offset = (FLAC__uint64)pos;
 
2419
                return FLAC__STREAM_DECODER_TELL_STATUS_OK;
 
2420
        }
 
2421
}
 
2422
 
 
2423
FLAC__StreamDecoderLengthStatus flac_decoder_length_callback(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
 
2424
{
 
2425
        FLACDecoderData *data = (FLACDecoderData*)client_data;
 
2426
        (void)decoder;
 
2427
 
 
2428
        if(0 == data->filesize)
 
2429
                return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
 
2430
        else {
 
2431
                *stream_length = (FLAC__uint64)data->filesize;
 
2432
                return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
 
2433
        }
 
2434
}
 
2435
 
 
2436
FLAC__bool flac_decoder_eof_callback(const FLAC__StreamDecoder *decoder, void *client_data)
 
2437
{
 
2438
        FLACDecoderData *data = (FLACDecoderData*)client_data;
 
2439
        (void)decoder;
 
2440
 
 
2441
        return feof(data->encoder_session->fin)? true : false;
 
2442
}
 
2443
 
 
2444
FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
 
2445
{
 
2446
        FLACDecoderData *data = (FLACDecoderData*)client_data;
 
2447
        FLAC__uint64 n = min(data->samples_left_to_process, frame->header.blocksize);
 
2448
        (void)decoder;
 
2449
 
 
2450
        if(!EncoderSession_process(data->encoder_session, buffer, (unsigned)n)) {
 
2451
                print_error_with_state(data->encoder_session, "ERROR during encoding");
 
2452
                data->fatal_error = true;
 
2453
                return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
 
2454
        }
 
2455
 
 
2456
        data->samples_left_to_process -= n;
 
2457
        return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
 
2458
}
 
2459
 
 
2460
void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
 
2461
{
 
2462
        FLACDecoderData *data = (FLACDecoderData*)client_data;
 
2463
        (void)decoder;
 
2464
 
 
2465
        if (data->fatal_error)
 
2466
                return;
 
2467
 
 
2468
        if (
 
2469
                data->num_metadata_blocks == sizeof(data->metadata_blocks)/sizeof(data->metadata_blocks[0]) ||
 
2470
                0 == (data->metadata_blocks[data->num_metadata_blocks] = FLAC__metadata_object_clone(metadata))
 
2471
        )
 
2472
                data->fatal_error = true;
 
2473
        else
 
2474
                data->num_metadata_blocks++;
 
2475
}
 
2476
 
 
2477
void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
 
2478
{
 
2479
        FLACDecoderData *data = (FLACDecoderData*)client_data;
 
2480
        (void)decoder;
 
2481
 
 
2482
        flac__utils_printf(stderr, 1, "%s: ERROR got %s while decoding FLAC input\n", data->encoder_session->inbasefilename, FLAC__StreamDecoderErrorStatusString[status]);
 
2483
        if(!data->encoder_session->continue_through_decode_errors)
 
2484
                data->fatal_error = true;
 
2485
}
 
2486
 
 
2487
FLAC__bool parse_cuesheet(FLAC__StreamMetadata **cuesheet, const char *cuesheet_filename, const char *inbasefilename, FLAC__bool is_cdda, FLAC__uint64 lead_out_offset, FLAC__bool treat_warnings_as_errors)
1835
2488
{
1836
2489
        FILE *f;
1837
2490
        unsigned last_line_read;
1846
2499
        }
1847
2500
 
1848
2501
        if(0 == (f = fopen(cuesheet_filename, "r"))) {
1849
 
                flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading\n", inbasefilename, cuesheet_filename);
 
2502
                flac__utils_printf(stderr, 1, "%s: ERROR opening cuesheet \"%s\" for reading: %s\n", inbasefilename, cuesheet_filename, strerror(errno));
1850
2503
                return false;
1851
2504
        }
1852
2505
 
1859
2512
                return false;
1860
2513
        }
1861
2514
 
 
2515
        if(!FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/false, &error_message)) {
 
2516
                flac__utils_printf(stderr, 1, "%s: ERROR parsing cuesheet \"%s\": %s\n", inbasefilename, cuesheet_filename, error_message);
 
2517
                return false;
 
2518
        }
 
2519
 
 
2520
        /* if we're expecting CDDA, warn about non-compliance */
 
2521
        if(is_cdda && !FLAC__format_cuesheet_is_legal(&(*cuesheet)->data.cue_sheet, /*check_cd_da_subset=*/true, &error_message)) {
 
2522
                flac__utils_printf(stderr, 1, "%s: WARNING cuesheet \"%s\" is not audio CD compliant: %s\n", inbasefilename, cuesheet_filename, error_message);
 
2523
                if(treat_warnings_as_errors)
 
2524
                        return false;
 
2525
                (*cuesheet)->data.cue_sheet.is_cd = false;
 
2526
        }
 
2527
 
1862
2528
        return true;
1863
2529
}
1864
2530
 
1874
2540
        const double ratio = (double)encoder_session->bytes_written / ((double)encoder_session->unencoded_size * min(1.0, progress));
1875
2541
#endif
1876
2542
 
1877
 
 
1878
2543
        if(samples_written == encoder_session->total_samples_to_encode) {
1879
2544
                flac__utils_printf(stderr, 2, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1880
2545
                        encoder_session->inbasefilename,
1888
2553
        }
1889
2554
}
1890
2555
 
 
2556
void print_error_with_init_status(const EncoderSession *e, const char *message, FLAC__StreamEncoderInitStatus init_status)
 
2557
{
 
2558
        const int ilen = strlen(e->inbasefilename) + 1;
 
2559
        const char *state_string = "";
 
2560
 
 
2561
        flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
 
2562
 
 
2563
        flac__utils_printf(stderr, 1, "%*s init_status = %s\n", ilen, "", FLAC__StreamEncoderInitStatusString[init_status]);
 
2564
 
 
2565
        if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR) {
 
2566
                state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
 
2567
 
 
2568
                flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
 
2569
 
 
2570
                /* print out some more info for some errors: */
 
2571
                if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
 
2572
                        flac__utils_printf(stderr, 1,
 
2573
                                "\n"
 
2574
                                "An error occurred while writing; the most common cause is that the disk is full.\n"
 
2575
                        );
 
2576
                }
 
2577
                else if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_IO_ERROR])) {
 
2578
                        flac__utils_printf(stderr, 1,
 
2579
                                "\n"
 
2580
                                "An error occurred opening the output file; it is likely that the output\n"
 
2581
                                "directory does not exist or is not writable, the output file already exists and\n"
 
2582
                                "is not writable, or the disk is full.\n"
 
2583
                        );
 
2584
                }
 
2585
        }
 
2586
        else if(init_status == FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE) {
 
2587
                flac__utils_printf(stderr, 1,
 
2588
                        "\n"
 
2589
                        "The encoding parameters specified do not conform to the FLAC Subset and may not\n"
 
2590
                        "be streamable or playable in hardware devices.  If you really understand the\n"
 
2591
                        "consequences, you can add --lax to the command-line options to encode with\n"
 
2592
                        "these parameters anyway.  See http://flac.sourceforge.net/format.html#subset\n"
 
2593
                );
 
2594
        }
 
2595
}
 
2596
 
1891
2597
void print_error_with_state(const EncoderSession *e, const char *message)
1892
2598
{
1893
2599
        const int ilen = strlen(e->inbasefilename) + 1;
1895
2601
 
1896
2602
        flac__utils_printf(stderr, 1, "\n%s: %s\n", e->inbasefilename, message);
1897
2603
 
1898
 
#ifdef FLAC__HAS_OGG
1899
 
        if(e->use_ogg) {
1900
 
                if(e->is_stdout) {
1901
 
                        state_string = OggFLAC__stream_encoder_get_resolved_state_string(e->encoder.ogg.stream);
1902
 
                }
1903
 
                else {
1904
 
                        state_string = OggFLAC__file_encoder_get_resolved_state_string(e->encoder.ogg.file);
1905
 
                }
1906
 
        }
1907
 
        else
1908
 
#endif
1909
 
        if(e->is_stdout) {
1910
 
                state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder.flac.stream);
1911
 
        }
1912
 
        else {
1913
 
                state_string = FLAC__file_encoder_get_resolved_state_string(e->encoder.flac.file);
1914
 
        }
 
2604
        state_string = FLAC__stream_encoder_get_resolved_state_string(e->encoder);
1915
2605
 
1916
2606
        flac__utils_printf(stderr, 1, "%*s state = %s\n", ilen, "", state_string);
1917
2607
 
1918
2608
        /* print out some more info for some errors: */
1919
 
        if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_NOT_STREAMABLE])) {
1920
 
                flac__utils_printf(stderr, 1,
1921
 
                        "\n"
1922
 
                        "The encoding parameters specified do not conform to the FLAC Subset and may not\n"
1923
 
                        "be streamable or playable in hardware devices.  Add --lax to the command-line\n"
1924
 
                        "options to encode with these parameters.\n"
1925
 
                );
1926
 
        }
1927
 
        else if(
1928
 
                0 == strcmp(state_string, FLAC__FileEncoderStateString[FLAC__FILE_ENCODER_FATAL_ERROR_WHILE_WRITING])
1929
 
#ifdef FLAC__HAS_OGG
1930
 
                || 0 == strcmp(state_string, OggFLAC__FileEncoderStateString[OggFLAC__FILE_ENCODER_FATAL_ERROR_WHILE_WRITING])
1931
 
#endif
1932
 
        ) {
 
2609
        if(0 == strcmp(state_string, FLAC__StreamEncoderStateString[FLAC__STREAM_ENCODER_CLIENT_ERROR])) {
1933
2610
                flac__utils_printf(stderr, 1,
1934
2611
                        "\n"
1935
2612
                        "An error occurred while writing; the most common cause is that the disk is full.\n"
1936
2613
                );
1937
2614
        }
1938
 
        else if(
1939
 
                0 == strcmp(state_string, FLAC__FileEncoderStateString[FLAC__FILE_ENCODER_ERROR_OPENING_FILE])
1940
 
#ifdef FLAC__HAS_OGG
1941
 
                || 0 == strcmp(state_string, OggFLAC__FileEncoderStateString[OggFLAC__FILE_ENCODER_ERROR_OPENING_FILE])
1942
 
#endif
1943
 
        ) {
1944
 
                flac__utils_printf(stderr, 1,
1945
 
                        "\n"
1946
 
                        "An error occurred opening the output file; it is likely that the output\n"
1947
 
                        "directory does not exist or is not writable, the output file already exists and\n"
1948
 
                        "is not writable, or the disk is full.\n"
1949
 
                );
1950
 
        }
1951
2615
}
1952
2616
 
1953
2617
void print_verify_error(EncoderSession *e)
1959
2623
        FLAC__int32 expected;
1960
2624
        FLAC__int32 got;
1961
2625
 
1962
 
#ifdef FLAC__HAS_OGG
1963
 
        if(e->use_ogg) {
1964
 
                if(e->is_stdout) {
1965
 
                        OggFLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.ogg.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1966
 
                }
1967
 
                else {
1968
 
                        OggFLAC__file_encoder_get_verify_decoder_error_stats(e->encoder.ogg.file, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1969
 
                }
1970
 
        }
1971
 
        else
1972
 
#endif
1973
 
        if(e->is_stdout) {
1974
 
                FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder.flac.stream, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1975
 
        }
1976
 
        else {
1977
 
                FLAC__file_encoder_get_verify_decoder_error_stats(e->encoder.flac.file, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1978
 
        }
 
2626
        FLAC__stream_encoder_get_verify_decoder_error_stats(e->encoder, &absolute_sample, &frame_number, &channel, &sample, &expected, &got);
1979
2627
 
1980
2628
        flac__utils_printf(stderr, 1, "%s: ERROR: mismatch in decoded data, verify FAILED!\n", e->inbasefilename);
1981
2629
        flac__utils_printf(stderr, 1, "       Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)absolute_sample, frame_number, channel, sample, expected, got);
1982
2630
        flac__utils_printf(stderr, 1, "       In all known cases, verify errors are caused by hardware problems,\n");
1983
 
        flac__utils_printf(stderr, 1, "       usually overclocking or bad RAM.  Delete %s\n", e->inbasefilename);
 
2631
        flac__utils_printf(stderr, 1, "       usually overclocking or bad RAM.  Delete %s\n", e->outfilename);
1984
2632
        flac__utils_printf(stderr, 1, "       and repeat the flac command exactly as before.  If it does not give a\n");
1985
2633
        flac__utils_printf(stderr, 1, "       verify error in the exact same place each time you try it, then there is\n");
1986
 
        flac__utils_printf(stderr, 1, "       a problem with your hardware.  If it does, keep the bad FLAC file and\n");
1987
 
        flac__utils_printf(stderr, 1, "       submit a bug report to:\n");
1988
 
        flac__utils_printf(stderr, 1, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1989
 
        flac__utils_printf(stderr, 1, "       Make sure to include an email contact in the comment and/or use the\n");
1990
 
        flac__utils_printf(stderr, 1, "       \"Monitor\" feature to monitor the bug status.\n");
 
2634
        flac__utils_printf(stderr, 1, "       a problem with your hardware; please see the FAQ:\n");
 
2635
        flac__utils_printf(stderr, 1, "           http://flac.sourceforge.net/faq.html#tools__hardware_prob\n");
 
2636
        flac__utils_printf(stderr, 1, "       If it does fail in the exact same place every time, keep\n");
 
2637
        flac__utils_printf(stderr, 1, "       %s and submit a bug report to:\n", e->outfilename);
 
2638
        flac__utils_printf(stderr, 1, "           https://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
 
2639
        flac__utils_printf(stderr, 1, "       Make sure to upload the FLAC file and use the \"Monitor\" feature to\n");
 
2640
        flac__utils_printf(stderr, 1, "       monitor the bug status.\n");
1991
2641
        flac__utils_printf(stderr, 1, "Verify FAILED!  Do not trust %s\n", e->outfilename);
1992
2642
}
1993
2643
 
2118
2768
 
2119
2769
        while(offset > 0) {
2120
2770
                long need = (long)min(offset, LONG_MAX);
2121
 
                if(fseek(f, need, SEEK_CUR) < 0) {
 
2771
                if(fseeko(f, need, SEEK_CUR) < 0) {
2122
2772
                        need = (long)min(offset, sizeof(dump));
2123
 
                        if(fread(dump, need, 1, f) < 1)
 
2773
                        if((long)fread(dump, 1, need, f) < need)
2124
2774
                                return false;
2125
2775
                }
2126
2776
                offset -= need;
2127
2777
        }
 
2778
#if 0 /* pure non-fseek() version */
 
2779
        while(offset > 0) {
 
2780
                const long need = (long)min(offset, sizeof(dump));
 
2781
                if(fread(dump, 1, need, f) < need)
 
2782
                        return false;
 
2783
                offset -= need;
 
2784
        }
 
2785
#endif
2128
2786
        return true;
2129
2787
}
 
2788
 
 
2789
unsigned count_channel_mask_bits(FLAC__uint32 mask)
 
2790
{
 
2791
        unsigned count = 0;
 
2792
        while(mask) {
 
2793
                if(mask & 1)
 
2794
                        count++;
 
2795
                mask >>= 1;
 
2796
        }
 
2797
        return count;
 
2798
}
 
2799
 
 
2800
FLAC__uint32 limit_channel_mask(FLAC__uint32 mask, unsigned channels)
 
2801
{
 
2802
        FLAC__uint32 x = 0x80000000;
 
2803
        unsigned count = count_channel_mask_bits(mask);
 
2804
        while(x && count > channels) {
 
2805
                if(mask & x) {
 
2806
                        mask &= ~x;
 
2807
                        count--;
 
2808
                }
 
2809
                x >>= 1;
 
2810
        }
 
2811
        FLAC__ASSERT(count_channel_mask_bits(mask) == channels);
 
2812
        return mask;
 
2813
}