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

« back to all changes in this revision

Viewing changes to src/libFLAC/stream_encoder.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
/* libFLAC - Free Lossless Audio Codec library
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
 * Redistribution and use in source and binary forms, with or without
5
5
 * modification, are permitted provided that the following conditions
29
29
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
30
 */
31
31
 
 
32
#if HAVE_CONFIG_H
 
33
#  include <config.h>
 
34
#endif
 
35
 
 
36
#if defined _MSC_VER || defined __MINGW32__
 
37
#include <io.h> /* for _setmode() */
 
38
#include <fcntl.h> /* for _O_BINARY */
 
39
#endif
 
40
#if defined __CYGWIN__ || defined __EMX__
 
41
#include <io.h> /* for setmode(), O_BINARY */
 
42
#include <fcntl.h> /* for _O_BINARY */
 
43
#endif
32
44
#include <limits.h>
33
45
#include <stdio.h>
34
46
#include <stdlib.h> /* for malloc() */
35
47
#include <string.h> /* for memcpy() */
 
48
#include <sys/types.h> /* for off_t */
 
49
#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
 
50
#if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
 
51
#define fseeko fseek
 
52
#define ftello ftell
 
53
#endif
 
54
#endif
36
55
#include "FLAC/assert.h"
37
56
#include "FLAC/stream_decoder.h"
38
57
#include "protected/stream_encoder.h"
39
 
#include "private/bitbuffer.h"
 
58
#include "private/bitwriter.h"
40
59
#include "private/bitmath.h"
41
60
#include "private/crc.h"
42
61
#include "private/cpu.h"
45
64
#include "private/lpc.h"
46
65
#include "private/md5.h"
47
66
#include "private/memory.h"
 
67
#if FLAC__HAS_OGG
 
68
#include "private/ogg_helper.h"
 
69
#include "private/ogg_mapping.h"
 
70
#endif
48
71
#include "private/stream_encoder_framing.h"
49
 
 
50
 
#ifdef HAVE_CONFIG_H
51
 
#include <config.h>
52
 
#endif
 
72
#include "private/window.h"
53
73
 
54
74
#ifdef min
55
75
#undef min
61
81
#endif
62
82
#define max(x,y) ((x)>(y)?(x):(y))
63
83
 
 
84
/* Exact Rice codeword length calculation is off by default.  The simple
 
85
 * (and fast) estimation (of how many bits a residual value will be
 
86
 * encoded with) in this encoder is very good, almost always yielding
 
87
 * compression within 0.1% of exact calculation.
 
88
 */
 
89
#undef EXACT_RICE_BITS_CALCULATION
 
90
/* Rice parameter searching is off by default.  The simple (and fast)
 
91
 * parameter estimation in this encoder is very good, almost always
 
92
 * yielding compression within 0.1% of the optimal parameters.
 
93
 */
 
94
#undef ENABLE_RICE_PARAMETER_SEARCH 
 
95
 
 
96
 
64
97
typedef struct {
65
98
        FLAC__int32 *data[FLAC__MAX_CHANNELS];
66
99
        unsigned size; /* of each data[] in samples */
79
112
        ENCODER_IN_AUDIO = 2
80
113
} EncoderStateHint;
81
114
 
 
115
static struct CompressionLevels {
 
116
        FLAC__bool do_mid_side_stereo;
 
117
        FLAC__bool loose_mid_side_stereo;
 
118
        unsigned max_lpc_order;
 
119
        unsigned qlp_coeff_precision;
 
120
        FLAC__bool do_qlp_coeff_prec_search;
 
121
        FLAC__bool do_escape_coding;
 
122
        FLAC__bool do_exhaustive_model_search;
 
123
        unsigned min_residual_partition_order;
 
124
        unsigned max_residual_partition_order;
 
125
        unsigned rice_parameter_search_dist;
 
126
} compression_levels_[] = {
 
127
        { false, false,  0, 0, false, false, false, 0, 3, 0 },
 
128
        { true , true ,  0, 0, false, false, false, 0, 3, 0 },
 
129
        { true , false,  0, 0, false, false, false, 0, 3, 0 },
 
130
        { false, false,  6, 0, false, false, false, 0, 4, 0 },
 
131
        { true , true ,  8, 0, false, false, false, 0, 4, 0 },
 
132
        { true , false,  8, 0, false, false, false, 0, 5, 0 },
 
133
        { true , false,  8, 0, false, false, false, 0, 6, 0 },
 
134
        { true , false,  8, 0, false, false, true , 0, 6, 0 },
 
135
        { true , false, 12, 0, false, false, true , 0, 6, 0 }
 
136
};
 
137
 
 
138
 
82
139
/***********************************************************************
83
140
 *
84
141
 * Private class method prototypes
87
144
 
88
145
static void set_defaults_(FLAC__StreamEncoder *encoder);
89
146
static void free_(FLAC__StreamEncoder *encoder);
90
 
static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size);
91
 
static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples);
92
 
static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
93
 
static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame);
 
147
static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
 
148
static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
 
149
static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
 
150
static void update_metadata_(const FLAC__StreamEncoder *encoder);
 
151
#if FLAC__HAS_OGG
 
152
static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
 
153
#endif
 
154
static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
 
155
static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
94
156
 
95
157
static FLAC__bool process_subframe_(
96
158
        FLAC__StreamEncoder *encoder,
97
159
        unsigned min_partition_order,
98
160
        unsigned max_partition_order,
99
 
        FLAC__bool precompute_partition_sums,
100
161
        const FLAC__FrameHeader *frame_header,
101
162
        unsigned subframe_bps,
102
163
        const FLAC__int32 integer_signal[],
112
173
 
113
174
static FLAC__bool add_subframe_(
114
175
        FLAC__StreamEncoder *encoder,
115
 
        const FLAC__FrameHeader *frame_header,
 
176
        unsigned blocksize,
116
177
        unsigned subframe_bps,
117
178
        const FLAC__Subframe *subframe,
118
 
        FLAC__BitBuffer *frame
 
179
        FLAC__BitWriter *frame
119
180
);
120
181
 
121
182
static unsigned evaluate_constant_subframe_(
 
183
        FLAC__StreamEncoder *encoder,
122
184
        const FLAC__int32 signal,
 
185
        unsigned blocksize,
123
186
        unsigned subframe_bps,
124
187
        FLAC__Subframe *subframe
125
188
);
128
191
        FLAC__StreamEncoder *encoder,
129
192
        const FLAC__int32 signal[],
130
193
        FLAC__int32 residual[],
131
 
        FLAC__uint32 abs_residual[],
132
194
        FLAC__uint64 abs_residual_partition_sums[],
133
195
        unsigned raw_bits_per_partition[],
134
196
        unsigned blocksize,
137
199
        unsigned rice_parameter,
138
200
        unsigned min_partition_order,
139
201
        unsigned max_partition_order,
140
 
        FLAC__bool precompute_partition_sums,
141
202
        FLAC__bool do_escape_coding,
142
203
        unsigned rice_parameter_search_dist,
143
204
        FLAC__Subframe *subframe,
149
210
        FLAC__StreamEncoder *encoder,
150
211
        const FLAC__int32 signal[],
151
212
        FLAC__int32 residual[],
152
 
        FLAC__uint32 abs_residual[],
153
213
        FLAC__uint64 abs_residual_partition_sums[],
154
214
        unsigned raw_bits_per_partition[],
155
215
        const FLAC__real lp_coeff[],
160
220
        unsigned rice_parameter,
161
221
        unsigned min_partition_order,
162
222
        unsigned max_partition_order,
163
 
        FLAC__bool precompute_partition_sums,
164
223
        FLAC__bool do_escape_coding,
165
224
        unsigned rice_parameter_search_dist,
166
225
        FLAC__Subframe *subframe,
169
228
#endif
170
229
 
171
230
static unsigned evaluate_verbatim_subframe_(
 
231
        FLAC__StreamEncoder *encoder, 
172
232
        const FLAC__int32 signal[],
173
233
        unsigned blocksize,
174
234
        unsigned subframe_bps,
178
238
static unsigned find_best_partition_order_(
179
239
        struct FLAC__StreamEncoderPrivate *private_,
180
240
        const FLAC__int32 residual[],
181
 
        FLAC__uint32 abs_residual[],
182
241
        FLAC__uint64 abs_residual_partition_sums[],
183
242
        unsigned raw_bits_per_partition[],
184
243
        unsigned residual_samples,
186
245
        unsigned rice_parameter,
187
246
        unsigned min_partition_order,
188
247
        unsigned max_partition_order,
189
 
        FLAC__bool precompute_partition_sums,
190
248
        FLAC__bool do_escape_coding,
191
249
        unsigned rice_parameter_search_dist,
192
250
        FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
193
251
);
194
252
 
195
253
static void precompute_partition_info_sums_(
196
 
        const FLAC__uint32 abs_residual[],
 
254
        const FLAC__int32 residual[],
197
255
        FLAC__uint64 abs_residual_partition_sums[],
198
256
        unsigned residual_samples,
199
257
        unsigned predictor_order,
210
268
        unsigned max_partition_order
211
269
);
212
270
 
213
 
#ifdef DONT_ESTIMATE_RICE_BITS
214
 
static FLAC__bool set_partitioned_rice_(
215
 
        const FLAC__uint32 abs_residual[],
216
 
        const FLAC__int32 residual[],
217
 
        const unsigned residual_samples,
218
 
        const unsigned predictor_order,
219
 
        const unsigned suggested_rice_parameter,
220
 
        const unsigned rice_parameter_search_dist,
221
 
        const unsigned partition_order,
222
 
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
223
 
        unsigned *bits
224
 
);
225
 
 
226
 
static FLAC__bool set_partitioned_rice_with_precompute_(
227
 
        const FLAC__int32 residual[],
228
 
        const FLAC__uint64 abs_residual_partition_sums[],
229
 
        const unsigned raw_bits_per_partition[],
230
 
        const unsigned residual_samples,
231
 
        const unsigned predictor_order,
232
 
        const unsigned suggested_rice_parameter,
233
 
        const unsigned rice_parameter_search_dist,
234
 
        const unsigned partition_order,
235
 
        const FLAC__bool search_for_escapes,
236
 
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
237
 
        unsigned *bits
238
 
);
239
 
#else
240
 
static FLAC__bool set_partitioned_rice_(
241
 
        const FLAC__uint32 abs_residual[],
242
 
        const unsigned residual_samples,
243
 
        const unsigned predictor_order,
244
 
        const unsigned suggested_rice_parameter,
245
 
        const unsigned rice_parameter_search_dist,
246
 
        const unsigned partition_order,
247
 
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
248
 
        unsigned *bits
249
 
);
250
 
 
251
 
static FLAC__bool set_partitioned_rice_with_precompute_(
252
 
        const FLAC__uint32 abs_residual[],
253
 
        const FLAC__uint64 abs_residual_partition_sums[],
254
 
        const unsigned raw_bits_per_partition[],
255
 
        const unsigned residual_samples,
256
 
        const unsigned predictor_order,
257
 
        const unsigned suggested_rice_parameter,
258
 
        const unsigned rice_parameter_search_dist,
259
 
        const unsigned partition_order,
260
 
        const FLAC__bool search_for_escapes,
261
 
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
262
 
        unsigned *bits
263
 
);
 
271
static FLAC__bool set_partitioned_rice_(
 
272
#ifdef EXACT_RICE_BITS_CALCULATION
 
273
        const FLAC__int32 residual[],
264
274
#endif
 
275
        const FLAC__uint64 abs_residual_partition_sums[],
 
276
        const unsigned raw_bits_per_partition[],
 
277
        const unsigned residual_samples,
 
278
        const unsigned predictor_order,
 
279
        const unsigned suggested_rice_parameter,
 
280
        const unsigned rice_parameter_search_dist,
 
281
        const unsigned partition_order,
 
282
        const FLAC__bool search_for_escapes,
 
283
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
 
284
        unsigned *bits
 
285
);
265
286
 
266
287
static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
267
288
 
282
303
        unsigned wide_samples
283
304
);
284
305
 
285
 
static FLAC__StreamDecoderReadStatus verify_read_callback_(
286
 
        const FLAC__StreamDecoder *decoder,
287
 
        FLAC__byte buffer[],
288
 
        unsigned *bytes,
289
 
        void *client_data
290
 
);
291
 
 
292
 
static FLAC__StreamDecoderWriteStatus verify_write_callback_(
293
 
        const FLAC__StreamDecoder *decoder,
294
 
        const FLAC__Frame *frame,
295
 
        const FLAC__int32 * const buffer[],
296
 
        void *client_data
297
 
);
298
 
 
299
 
static void verify_metadata_callback_(
300
 
        const FLAC__StreamDecoder *decoder,
301
 
        const FLAC__StreamMetadata *metadata,
302
 
        void *client_data
303
 
);
304
 
 
305
 
static void verify_error_callback_(
306
 
        const FLAC__StreamDecoder *decoder,
307
 
        FLAC__StreamDecoderErrorStatus status,
308
 
        void *client_data
309
 
);
 
306
static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
 
307
static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
 
308
static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
 
309
static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
 
310
 
 
311
static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
 
312
static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
 
313
static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
 
314
static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
 
315
static FILE *get_binary_stdout_(void);
310
316
 
311
317
 
312
318
/***********************************************************************
322
328
#ifndef FLAC__INTEGER_ONLY_LIBRARY
323
329
        FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* the floating-point version of the input signal */
324
330
        FLAC__real *real_signal_mid_side[2];              /* the floating-point version of the mid-side input signal (stereo only) */
 
331
        FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
 
332
        FLAC__real *windowed_signal;                      /* the real_signal[] * current window[] */
325
333
#endif
326
334
        unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
327
335
        unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
335
343
        FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
336
344
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
337
345
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
338
 
        unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index into the above workspaces */
 
346
        unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index (0 or 1) into 2nd dimension of the above workspaces */
339
347
        unsigned best_subframe_mid_side[2];
340
348
        unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
341
349
        unsigned best_subframe_bits_mid_side[2];
342
 
        FLAC__uint32 *abs_residual;                       /* workspace where abs(candidate residual) is stored */
343
350
        FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
344
351
        unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
345
 
        FLAC__BitBuffer *frame;                           /* the current frame being worked on */
 
352
        FLAC__BitWriter *frame;                           /* the current frame being worked on */
346
353
        unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
347
354
        unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
348
355
        FLAC__ChannelAssignment last_channel_assignment;
349
 
        FLAC__StreamMetadata metadata;
 
356
        FLAC__StreamMetadata streaminfo;                  /* scratchpad for STREAMINFO as it is built */
 
357
        FLAC__StreamMetadata_SeekTable *seek_table;       /* pointer into encoder->protected_->metadata_ where the seek table is */
350
358
        unsigned current_sample_number;
351
359
        unsigned current_frame_number;
352
360
        struct FLAC__MD5Context md5context;
365
373
        FLAC__bool use_wide_by_block;          /* use slow 64-bit versions of some functions because of the block size */
366
374
        FLAC__bool use_wide_by_partition;      /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
367
375
        FLAC__bool use_wide_by_order;          /* use slow 64-bit versions of some functions because of the lpc order */
368
 
        FLAC__bool precompute_partition_sums;  /* our initial guess as to whether precomputing the partitions sums will be a speed improvement */
369
376
        FLAC__bool disable_constant_subframes;
370
377
        FLAC__bool disable_fixed_subframes;
371
378
        FLAC__bool disable_verbatim_subframes;
 
379
#if FLAC__HAS_OGG
 
380
        FLAC__bool is_ogg;
 
381
#endif
 
382
        FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
 
383
        FLAC__StreamEncoderSeekCallback seek_callback;
 
384
        FLAC__StreamEncoderTellCallback tell_callback;
372
385
        FLAC__StreamEncoderWriteCallback write_callback;
373
386
        FLAC__StreamEncoderMetadataCallback metadata_callback;
 
387
        FLAC__StreamEncoderProgressCallback progress_callback;
374
388
        void *client_data;
 
389
        unsigned first_seekpoint_to_check;
 
390
        FILE *file;                            /* only used when encoding to a file */
 
391
        FLAC__uint64 bytes_written;
 
392
        FLAC__uint64 samples_written;
 
393
        unsigned frames_written;
 
394
        unsigned total_frames_estimate;
375
395
        /* unaligned (original) pointers to allocated data */
376
396
        FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
377
397
        FLAC__int32 *integer_signal_mid_side_unaligned[2];
378
398
#ifndef FLAC__INTEGER_ONLY_LIBRARY
379
399
        FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS];
380
400
        FLAC__real *real_signal_mid_side_unaligned[2];
 
401
        FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
 
402
        FLAC__real *windowed_signal_unaligned;
381
403
#endif
382
404
        FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
383
405
        FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
384
 
        FLAC__uint32 *abs_residual_unaligned;
385
406
        FLAC__uint64 *abs_residual_partition_sums_unaligned;
386
407
        unsigned *raw_bits_per_partition_unaligned;
387
408
        /*
421
442
 
422
443
FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
423
444
        "FLAC__STREAM_ENCODER_OK",
 
445
        "FLAC__STREAM_ENCODER_UNINITIALIZED",
 
446
        "FLAC__STREAM_ENCODER_OGG_ERROR",
424
447
        "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
425
448
        "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
426
 
        "FLAC__STREAM_ENCODER_INVALID_CALLBACK",
427
 
        "FLAC__STREAM_ENCODER_INVALID_NUMBER_OF_CHANNELS",
428
 
        "FLAC__STREAM_ENCODER_INVALID_BITS_PER_SAMPLE",
429
 
        "FLAC__STREAM_ENCODER_INVALID_SAMPLE_RATE",
430
 
        "FLAC__STREAM_ENCODER_INVALID_BLOCK_SIZE",
431
 
        "FLAC__STREAM_ENCODER_INVALID_MAX_LPC_ORDER",
432
 
        "FLAC__STREAM_ENCODER_INVALID_QLP_COEFF_PRECISION",
433
 
        "FLAC__STREAM_ENCODER_MID_SIDE_CHANNELS_MISMATCH",
434
 
        "FLAC__STREAM_ENCODER_MID_SIDE_SAMPLE_SIZE_MISMATCH",
435
 
        "FLAC__STREAM_ENCODER_ILLEGAL_MID_SIDE_FORCE",
436
 
        "FLAC__STREAM_ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
437
 
        "FLAC__STREAM_ENCODER_NOT_STREAMABLE",
 
449
        "FLAC__STREAM_ENCODER_CLIENT_ERROR",
 
450
        "FLAC__STREAM_ENCODER_IO_ERROR",
438
451
        "FLAC__STREAM_ENCODER_FRAMING_ERROR",
439
 
        "FLAC__STREAM_ENCODER_INVALID_METADATA",
440
 
        "FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING",
441
 
        "FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_WRITING",
442
 
        "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR",
443
 
        "FLAC__STREAM_ENCODER_ALREADY_INITIALIZED",
444
 
        "FLAC__STREAM_ENCODER_UNINITIALIZED"
 
452
        "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
 
453
};
 
454
 
 
455
FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
 
456
        "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
 
457
        "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
 
458
        "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
 
459
        "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
 
460
        "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
 
461
        "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
 
462
        "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
 
463
        "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
 
464
        "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
 
465
        "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
 
466
        "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
 
467
        "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
 
468
        "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
 
469
        "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
 
470
};
 
471
 
 
472
FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
 
473
        "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
 
474
        "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
 
475
        "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
 
476
        "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
445
477
};
446
478
 
447
479
FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
449
481
        "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
450
482
};
451
483
 
 
484
FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
 
485
        "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
 
486
        "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
 
487
        "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
 
488
};
 
489
 
 
490
FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
 
491
        "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
 
492
        "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
 
493
        "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
 
494
};
 
495
 
 
496
/* Number of samples that will be overread to watch for end of stream.  By
 
497
 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
 
498
 * always try to read blocksize+1 samples before encoding a block, so that
 
499
 * even if the stream has a total sample count that is an integral multiple
 
500
 * of the blocksize, we will still notice when we are encoding the last
 
501
 * block.  This is needed, for example, to correctly set the end-of-stream
 
502
 * marker in Ogg FLAC.
 
503
 *
 
504
 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
 
505
 * not really any reason to change it.
 
506
 */
 
507
static const unsigned OVERREAD_ = 1;
 
508
 
452
509
/***********************************************************************
453
510
 *
454
511
 * Class constructor/destructor
455
512
 *
456
513
 */
457
 
FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new()
 
514
FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
458
515
{
459
516
        FLAC__StreamEncoder *encoder;
460
517
        unsigned i;
479
536
                return 0;
480
537
        }
481
538
 
482
 
        encoder->private_->frame = FLAC__bitbuffer_new();
 
539
        encoder->private_->frame = FLAC__bitwriter_new();
483
540
        if(encoder->private_->frame == 0) {
484
541
                free(encoder->private_);
485
542
                free(encoder->protected_);
487
544
                return 0;
488
545
        }
489
546
 
 
547
        encoder->private_->file = 0;
 
548
 
490
549
        set_defaults_(encoder);
491
550
 
492
551
        encoder->private_->is_being_deleted = false;
535
594
 
536
595
        encoder->private_->is_being_deleted = true;
537
596
 
538
 
        FLAC__stream_encoder_finish(encoder);
 
597
        (void)FLAC__stream_encoder_finish(encoder);
539
598
 
540
599
        if(0 != encoder->private_->verify.decoder)
541
600
                FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
551
610
        for(i = 0; i < 2; i++)
552
611
                FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
553
612
 
554
 
        FLAC__bitbuffer_delete(encoder->private_->frame);
 
613
        FLAC__bitwriter_delete(encoder->private_->frame);
555
614
        free(encoder->private_);
556
615
        free(encoder->protected_);
557
616
        free(encoder);
563
622
 *
564
623
 ***********************************************************************/
565
624
 
566
 
FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_init(FLAC__StreamEncoder *encoder)
 
625
static FLAC__StreamEncoderInitStatus init_stream_internal_(
 
626
        FLAC__StreamEncoder *encoder,
 
627
        FLAC__StreamEncoderReadCallback read_callback,
 
628
        FLAC__StreamEncoderWriteCallback write_callback,
 
629
        FLAC__StreamEncoderSeekCallback seek_callback,
 
630
        FLAC__StreamEncoderTellCallback tell_callback,
 
631
        FLAC__StreamEncoderMetadataCallback metadata_callback,
 
632
        void *client_data,
 
633
        FLAC__bool is_ogg
 
634
)
567
635
{
568
636
        unsigned i;
569
 
        FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment;
 
637
        FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
570
638
 
571
639
        FLAC__ASSERT(0 != encoder);
572
640
 
573
641
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
574
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_ALREADY_INITIALIZED;
575
 
 
576
 
        encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
577
 
 
578
 
        if(0 == encoder->private_->write_callback || 0 == encoder->private_->metadata_callback)
579
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_CALLBACK;
 
642
                return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
 
643
 
 
644
#if !FLAC__HAS_OGG
 
645
        if(is_ogg)
 
646
                return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
 
647
#endif
 
648
 
 
649
        if(0 == write_callback || (seek_callback && 0 == tell_callback))
 
650
                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
580
651
 
581
652
        if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
582
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_NUMBER_OF_CHANNELS;
583
 
 
584
 
        if(encoder->protected_->do_mid_side_stereo && encoder->protected_->channels != 2)
585
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_MID_SIDE_CHANNELS_MISMATCH;
586
 
 
587
 
        if(encoder->protected_->loose_mid_side_stereo && !encoder->protected_->do_mid_side_stereo)
588
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_ILLEGAL_MID_SIDE_FORCE;
 
653
                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
 
654
 
 
655
        if(encoder->protected_->channels != 2) {
 
656
                encoder->protected_->do_mid_side_stereo = false;
 
657
                encoder->protected_->loose_mid_side_stereo = false;
 
658
        }
 
659
        else if(!encoder->protected_->do_mid_side_stereo)
 
660
                encoder->protected_->loose_mid_side_stereo = false;
589
661
 
590
662
        if(encoder->protected_->bits_per_sample >= 32)
591
 
                encoder->protected_->do_mid_side_stereo = false; /* since we do 32-bit math, the side channel would have 33 bps and overflow */
 
663
                encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
592
664
 
593
665
        if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
594
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_BITS_PER_SAMPLE;
 
666
                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
595
667
 
596
668
        if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
597
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_SAMPLE_RATE;
 
669
                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
 
670
 
 
671
        if(encoder->protected_->blocksize == 0) {
 
672
                if(encoder->protected_->max_lpc_order == 0)
 
673
                        encoder->protected_->blocksize = 1152;
 
674
                else
 
675
                        encoder->protected_->blocksize = 4096;
 
676
        }
598
677
 
599
678
        if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
600
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_BLOCK_SIZE;
 
679
                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
601
680
 
602
681
        if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
603
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_MAX_LPC_ORDER;
 
682
                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
604
683
 
605
684
        if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
606
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
 
685
                return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
607
686
 
608
687
        if(encoder->protected_->qlp_coeff_precision == 0) {
609
688
                if(encoder->protected_->bits_per_sample < 16) {
638
717
                FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
639
718
        }
640
719
        else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
641
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_QLP_COEFF_PRECISION;
 
720
                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
642
721
 
643
722
        if(encoder->protected_->streamable_subset) {
644
723
                if(
655
734
                        encoder->protected_->blocksize != 8192 &&
656
735
                        encoder->protected_->blocksize != 16384
657
736
                )
658
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_NOT_STREAMABLE;
 
737
                        return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
659
738
                if(
660
739
                        encoder->protected_->sample_rate != 8000 &&
661
740
                        encoder->protected_->sample_rate != 16000 &&
666
745
                        encoder->protected_->sample_rate != 48000 &&
667
746
                        encoder->protected_->sample_rate != 96000
668
747
                )
669
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_NOT_STREAMABLE;
 
748
                        return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
670
749
                if(
671
750
                        encoder->protected_->bits_per_sample != 8 &&
672
751
                        encoder->protected_->bits_per_sample != 12 &&
674
753
                        encoder->protected_->bits_per_sample != 20 &&
675
754
                        encoder->protected_->bits_per_sample != 24
676
755
                )
677
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_NOT_STREAMABLE;
 
756
                        return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
678
757
                if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
679
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_NOT_STREAMABLE;
 
758
                        return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
 
759
                if(
 
760
                        encoder->protected_->sample_rate <= 48000 &&
 
761
                        (
 
762
                                encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
 
763
                                encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
 
764
                        )
 
765
                ) {
 
766
                        return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
 
767
                }
680
768
        }
681
769
 
682
770
        if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
684
772
        if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
685
773
                encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
686
774
 
 
775
#if FLAC__HAS_OGG
 
776
        /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
 
777
        if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
 
778
                unsigned i;
 
779
                for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
 
780
                        if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
 
781
                                FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
 
782
                                for( ; i > 0; i--)
 
783
                                        encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
 
784
                                encoder->protected_->metadata[0] = vc;
 
785
                                break;
 
786
                        }
 
787
                }
 
788
        }
 
789
#endif
 
790
        /* keep track of any SEEKTABLE block */
 
791
        if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
 
792
                unsigned i;
 
793
                for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
 
794
                        if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
 
795
                                encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
 
796
                                break; /* take only the first one */
 
797
                        }
 
798
                }
 
799
        }
 
800
 
687
801
        /* validate metadata */
688
802
        if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
689
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
 
803
                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
690
804
        metadata_has_seektable = false;
691
805
        metadata_has_vorbis_comment = false;
 
806
        metadata_picture_has_type1 = false;
 
807
        metadata_picture_has_type2 = false;
692
808
        for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
693
 
                if(encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_STREAMINFO)
694
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
695
 
                else if(encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
 
809
                const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
 
810
                if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
 
811
                        return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
 
812
                else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
696
813
                        if(metadata_has_seektable) /* only one is allowed */
697
 
                                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
 
814
                                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
698
815
                        metadata_has_seektable = true;
699
 
                        if(!FLAC__format_seektable_is_legal(&encoder->protected_->metadata[i]->data.seek_table))
700
 
                                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
 
816
                        if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
 
817
                                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
701
818
                }
702
 
                else if(encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
 
819
                else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
703
820
                        if(metadata_has_vorbis_comment) /* only one is allowed */
704
 
                                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
 
821
                                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
705
822
                        metadata_has_vorbis_comment = true;
706
823
                }
707
 
                else if(encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_CUESHEET) {
708
 
                        if(!FLAC__format_cuesheet_is_legal(&encoder->protected_->metadata[i]->data.cue_sheet, encoder->protected_->metadata[i]->data.cue_sheet.is_cd, /*violation=*/0))
709
 
                                return encoder->protected_->state = FLAC__STREAM_ENCODER_INVALID_METADATA;
 
824
                else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
 
825
                        if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
 
826
                                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
 
827
                }
 
828
                else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
 
829
                        if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
 
830
                                return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
 
831
                        if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
 
832
                                if(metadata_picture_has_type1) /* there should only be 1 per stream */
 
833
                                        return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
 
834
                                metadata_picture_has_type1 = true;
 
835
                                /* standard icon must be 32x32 pixel PNG */
 
836
                                if(
 
837
                                        m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD && 
 
838
                                        (
 
839
                                                (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
 
840
                                                m->data.picture.width != 32 ||
 
841
                                                m->data.picture.height != 32
 
842
                                        )
 
843
                                )
 
844
                                        return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
 
845
                        }
 
846
                        else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
 
847
                                if(metadata_picture_has_type2) /* there should only be 1 per stream */
 
848
                                        return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
 
849
                                metadata_picture_has_type2 = true;
 
850
                        }
710
851
                }
711
852
        }
712
853
 
723
864
                encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
724
865
#endif
725
866
        }
 
867
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
868
        for(i = 0; i < encoder->protected_->num_apodizations; i++)
 
869
                encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
 
870
        encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
 
871
#endif
726
872
        for(i = 0; i < encoder->protected_->channels; i++) {
727
873
                encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
728
874
                encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
733
879
                encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
734
880
                encoder->private_->best_subframe_mid_side[i] = 0;
735
881
        }
736
 
        encoder->private_->abs_residual_unaligned = encoder->private_->abs_residual = 0;
737
882
        encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
738
883
        encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
739
884
#ifndef FLAC__INTEGER_ONLY_LIBRARY
815
960
                encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
816
961
        }
817
962
 
818
 
        /* we require precompute_partition_sums if do_escape_coding because of their intertwined nature */
819
 
        encoder->private_->precompute_partition_sums = (encoder->protected_->max_residual_partition_order > encoder->protected_->min_residual_partition_order) || encoder->protected_->do_escape_coding;
 
963
        /* set state to OK; from here on, errors are fatal and we'll override the state then */
 
964
        encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
 
965
 
 
966
#if FLAC__HAS_OGG
 
967
        encoder->private_->is_ogg = is_ogg;
 
968
        if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
 
969
                encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
 
970
                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
971
        }
 
972
#endif
 
973
 
 
974
        encoder->private_->read_callback = read_callback;
 
975
        encoder->private_->write_callback = write_callback;
 
976
        encoder->private_->seek_callback = seek_callback;
 
977
        encoder->private_->tell_callback = tell_callback;
 
978
        encoder->private_->metadata_callback = metadata_callback;
 
979
        encoder->private_->client_data = client_data;
820
980
 
821
981
        if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
822
982
                /* the above function sets the state for us in case of an error */
823
 
                return encoder->protected_->state;
 
983
                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
824
984
        }
825
985
 
826
 
        if(!FLAC__bitbuffer_init(encoder->private_->frame))
827
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
 
986
        if(!FLAC__bitwriter_init(encoder->private_->frame)) {
 
987
                encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
 
988
                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
989
        }
828
990
 
829
991
        /*
830
992
         * Set up the verify stuff if necessary
834
996
                 * First, set up the fifo which will hold the
835
997
                 * original signal to compare against
836
998
                 */
837
 
                encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize;
 
999
                encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
838
1000
                for(i = 0; i < encoder->protected_->channels; i++) {
839
 
                        if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size)))
840
 
                                return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
 
1001
                        if(0 == (encoder->private_->verify.input_fifo.data[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder->private_->verify.input_fifo.size))) {
 
1002
                                encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
 
1003
                                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
1004
                        }
841
1005
                }
842
1006
                encoder->private_->verify.input_fifo.tail = 0;
843
1007
 
845
1009
                 * Now set up a stream decoder for verification
846
1010
                 */
847
1011
                encoder->private_->verify.decoder = FLAC__stream_decoder_new();
848
 
                if(0 == encoder->private_->verify.decoder)
849
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
 
1012
                if(0 == encoder->private_->verify.decoder) {
 
1013
                        encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
 
1014
                        return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
1015
                }
850
1016
 
851
 
                FLAC__stream_decoder_set_read_callback(encoder->private_->verify.decoder, verify_read_callback_);
852
 
                FLAC__stream_decoder_set_write_callback(encoder->private_->verify.decoder, verify_write_callback_);
853
 
                FLAC__stream_decoder_set_metadata_callback(encoder->private_->verify.decoder, verify_metadata_callback_);
854
 
                FLAC__stream_decoder_set_error_callback(encoder->private_->verify.decoder, verify_error_callback_);
855
 
                FLAC__stream_decoder_set_client_data(encoder->private_->verify.decoder, encoder);
856
 
                if(FLAC__stream_decoder_init(encoder->private_->verify.decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA)
857
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
 
1017
                if(FLAC__stream_decoder_init_stream(encoder->private_->verify.decoder, verify_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, verify_write_callback_, verify_metadata_callback_, verify_error_callback_, /*client_data=*/encoder) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
 
1018
                        encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
 
1019
                        return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
1020
                }
858
1021
        }
859
1022
        encoder->private_->verify.error_stats.absolute_sample = 0;
860
1023
        encoder->private_->verify.error_stats.frame_number = 0;
864
1027
        encoder->private_->verify.error_stats.got = 0;
865
1028
 
866
1029
        /*
 
1030
         * These must be done before we write any metadata, because that
 
1031
         * calls the write_callback, which uses these values.
 
1032
         */
 
1033
        encoder->private_->first_seekpoint_to_check = 0;
 
1034
        encoder->private_->samples_written = 0;
 
1035
        encoder->protected_->streaminfo_offset = 0;
 
1036
        encoder->protected_->seektable_offset = 0;
 
1037
        encoder->protected_->audio_offset = 0;
 
1038
 
 
1039
        /*
867
1040
         * write the stream header
868
1041
         */
869
1042
        if(encoder->protected_->verify)
870
1043
                encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
871
 
        if(!FLAC__bitbuffer_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN))
872
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
873
 
        if(!write_bitbuffer_(encoder, 0)) {
 
1044
        if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
 
1045
                encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
 
1046
                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
1047
        }
 
1048
        if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
874
1049
                /* the above function sets the state for us in case of an error */
875
 
                return encoder->protected_->state;
 
1050
                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
876
1051
        }
877
1052
 
878
1053
        /*
880
1055
         */
881
1056
        if(encoder->protected_->verify)
882
1057
                encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
883
 
        encoder->private_->metadata.type = FLAC__METADATA_TYPE_STREAMINFO;
884
 
        encoder->private_->metadata.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
885
 
        encoder->private_->metadata.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
886
 
        encoder->private_->metadata.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
887
 
        encoder->private_->metadata.data.stream_info.max_blocksize = encoder->protected_->blocksize;
888
 
        encoder->private_->metadata.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
889
 
        encoder->private_->metadata.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
890
 
        encoder->private_->metadata.data.stream_info.sample_rate = encoder->protected_->sample_rate;
891
 
        encoder->private_->metadata.data.stream_info.channels = encoder->protected_->channels;
892
 
        encoder->private_->metadata.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
893
 
        encoder->private_->metadata.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
894
 
        memset(encoder->private_->metadata.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
 
1058
        encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
 
1059
        encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
 
1060
        encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
 
1061
        encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
 
1062
        encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
 
1063
        encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
 
1064
        encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
 
1065
        encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
 
1066
        encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
 
1067
        encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
 
1068
        encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
 
1069
        memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
895
1070
        FLAC__MD5Init(&encoder->private_->md5context);
896
 
        if(!FLAC__bitbuffer_clear(encoder->private_->frame))
897
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
898
 
        if(!FLAC__add_metadata_block(&encoder->private_->metadata, encoder->private_->frame))
899
 
                return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
900
 
        if(!write_bitbuffer_(encoder, 0)) {
 
1071
        if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
 
1072
                encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
 
1073
                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
1074
        }
 
1075
        if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
901
1076
                /* the above function sets the state for us in case of an error */
902
 
                return encoder->protected_->state;
 
1077
                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
903
1078
        }
904
1079
 
905
1080
        /*
906
1081
         * Now that the STREAMINFO block is written, we can init this to an
907
1082
         * absurdly-high value...
908
1083
         */
909
 
        encoder->private_->metadata.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
 
1084
        encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
910
1085
        /* ... and clear this to 0 */
911
 
        encoder->private_->metadata.data.stream_info.total_samples = 0;
 
1086
        encoder->private_->streaminfo.data.stream_info.total_samples = 0;
912
1087
 
913
1088
        /*
914
1089
         * Check to see if the supplied metadata contains a VORBIS_COMMENT;
915
1090
         * if not, we will write an empty one (FLAC__add_metadata_block()
916
1091
         * automatically supplies the vendor string).
917
1092
         *
918
 
         * WATCHOUT: libOggFLAC depends on us to write this block after the
919
 
         * STREAMINFO since that's what the mapping requires.  (In the case
920
 
         * that metadata_has_vorbis_comment is true it will have already
921
 
         * insured that the metadata list is properly ordered.)
 
1093
         * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
 
1094
         * the STREAMINFO.  (In the case that metadata_has_vorbis_comment is
 
1095
         * true it will have already insured that the metadata list is properly
 
1096
         * ordered.)
922
1097
         */
923
1098
        if(!metadata_has_vorbis_comment) {
924
1099
                FLAC__StreamMetadata vorbis_comment;
929
1104
                vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
930
1105
                vorbis_comment.data.vorbis_comment.num_comments = 0;
931
1106
                vorbis_comment.data.vorbis_comment.comments = 0;
932
 
                if(!FLAC__bitbuffer_clear(encoder->private_->frame))
933
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
934
 
                if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame))
935
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
936
 
                if(!write_bitbuffer_(encoder, 0)) {
 
1107
                if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
 
1108
                        encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
 
1109
                        return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
1110
                }
 
1111
                if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
937
1112
                        /* the above function sets the state for us in case of an error */
938
 
                        return encoder->protected_->state;
 
1113
                        return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
939
1114
                }
940
1115
        }
941
1116
 
944
1119
         */
945
1120
        for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
946
1121
                encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
947
 
                if(!FLAC__bitbuffer_clear(encoder->private_->frame))
948
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
949
 
                if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame))
950
 
                        return encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
951
 
                if(!write_bitbuffer_(encoder, 0)) {
 
1122
                if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
 
1123
                        encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
 
1124
                        return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
1125
                }
 
1126
                if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
952
1127
                        /* the above function sets the state for us in case of an error */
953
 
                        return encoder->protected_->state;
 
1128
                        return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
954
1129
                }
955
1130
        }
956
1131
 
 
1132
        /* now that all the metadata is written, we save the stream offset */
 
1133
        if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &encoder->protected_->audio_offset, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) { /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
 
1134
                encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
1135
                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
1136
        }
 
1137
 
957
1138
        if(encoder->protected_->verify)
958
1139
                encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
959
1140
 
960
 
        return encoder->protected_->state;
961
 
}
962
 
 
963
 
FLAC_API void FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
964
 
{
965
 
        FLAC__ASSERT(0 != encoder);
 
1141
        return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
 
1142
}
 
1143
 
 
1144
FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
 
1145
        FLAC__StreamEncoder *encoder,
 
1146
        FLAC__StreamEncoderWriteCallback write_callback,
 
1147
        FLAC__StreamEncoderSeekCallback seek_callback,
 
1148
        FLAC__StreamEncoderTellCallback tell_callback,
 
1149
        FLAC__StreamEncoderMetadataCallback metadata_callback,
 
1150
        void *client_data
 
1151
)
 
1152
{
 
1153
        return init_stream_internal_(
 
1154
                encoder,
 
1155
                /*read_callback=*/0,
 
1156
                write_callback,
 
1157
                seek_callback,
 
1158
                tell_callback,
 
1159
                metadata_callback,
 
1160
                client_data,
 
1161
                /*is_ogg=*/false
 
1162
        );
 
1163
}
 
1164
 
 
1165
FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
 
1166
        FLAC__StreamEncoder *encoder,
 
1167
        FLAC__StreamEncoderReadCallback read_callback,
 
1168
        FLAC__StreamEncoderWriteCallback write_callback,
 
1169
        FLAC__StreamEncoderSeekCallback seek_callback,
 
1170
        FLAC__StreamEncoderTellCallback tell_callback,
 
1171
        FLAC__StreamEncoderMetadataCallback metadata_callback,
 
1172
        void *client_data
 
1173
)
 
1174
{
 
1175
        return init_stream_internal_(
 
1176
                encoder,
 
1177
                read_callback,
 
1178
                write_callback,
 
1179
                seek_callback,
 
1180
                tell_callback,
 
1181
                metadata_callback,
 
1182
                client_data,
 
1183
                /*is_ogg=*/true
 
1184
        );
 
1185
}
 
1186
 
 
1187
static FLAC__StreamEncoderInitStatus init_FILE_internal_(
 
1188
        FLAC__StreamEncoder *encoder,
 
1189
        FILE *file,
 
1190
        FLAC__StreamEncoderProgressCallback progress_callback,
 
1191
        void *client_data,
 
1192
        FLAC__bool is_ogg
 
1193
)
 
1194
{
 
1195
        FLAC__StreamEncoderInitStatus init_status;
 
1196
 
 
1197
        FLAC__ASSERT(0 != encoder);
 
1198
        FLAC__ASSERT(0 != file);
 
1199
 
 
1200
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
 
1201
                return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
 
1202
 
 
1203
        /* double protection */
 
1204
        if(file == 0) {
 
1205
                encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
 
1206
                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
1207
        }
 
1208
 
 
1209
        /*
 
1210
         * To make sure that our file does not go unclosed after an error, we
 
1211
         * must assign the FILE pointer before any further error can occur in
 
1212
         * this routine.
 
1213
         */
 
1214
        if(file == stdout)
 
1215
                file = get_binary_stdout_(); /* just to be safe */
 
1216
 
 
1217
        encoder->private_->file = file;
 
1218
 
 
1219
        encoder->private_->progress_callback = progress_callback;
 
1220
        encoder->private_->bytes_written = 0;
 
1221
        encoder->private_->samples_written = 0;
 
1222
        encoder->private_->frames_written = 0;
 
1223
 
 
1224
        init_status = init_stream_internal_(
 
1225
                encoder,
 
1226
                encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
 
1227
                file_write_callback_,
 
1228
                encoder->private_->file == stdout? 0 : file_seek_callback_,
 
1229
                encoder->private_->file == stdout? 0 : file_tell_callback_,
 
1230
                /*metadata_callback=*/0,
 
1231
                client_data,
 
1232
                is_ogg
 
1233
        );
 
1234
        if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
 
1235
                /* the above function sets the state for us in case of an error */
 
1236
                return init_status;
 
1237
        }
 
1238
 
 
1239
        {
 
1240
                unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
 
1241
 
 
1242
                FLAC__ASSERT(blocksize != 0);
 
1243
                encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
 
1244
        }
 
1245
 
 
1246
        return init_status;
 
1247
}
 
1248
 
 
1249
FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
 
1250
        FLAC__StreamEncoder *encoder,
 
1251
        FILE *file,
 
1252
        FLAC__StreamEncoderProgressCallback progress_callback,
 
1253
        void *client_data
 
1254
)
 
1255
{
 
1256
        return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
 
1257
}
 
1258
 
 
1259
FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
 
1260
        FLAC__StreamEncoder *encoder,
 
1261
        FILE *file,
 
1262
        FLAC__StreamEncoderProgressCallback progress_callback,
 
1263
        void *client_data
 
1264
)
 
1265
{
 
1266
        return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
 
1267
}
 
1268
 
 
1269
static FLAC__StreamEncoderInitStatus init_file_internal_(
 
1270
        FLAC__StreamEncoder *encoder,
 
1271
        const char *filename,
 
1272
        FLAC__StreamEncoderProgressCallback progress_callback,
 
1273
        void *client_data,
 
1274
        FLAC__bool is_ogg
 
1275
)
 
1276
{
 
1277
        FILE *file;
 
1278
 
 
1279
        FLAC__ASSERT(0 != encoder);
 
1280
 
 
1281
        /*
 
1282
         * To make sure that our file does not go unclosed after an error, we
 
1283
         * have to do the same entrance checks here that are later performed
 
1284
         * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
 
1285
         */
 
1286
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
 
1287
                return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
 
1288
 
 
1289
        file = filename? fopen(filename, "w+b") : stdout;
 
1290
 
 
1291
        if(file == 0) {
 
1292
                encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
 
1293
                return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
 
1294
        }
 
1295
 
 
1296
        return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
 
1297
}
 
1298
 
 
1299
FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
 
1300
        FLAC__StreamEncoder *encoder,
 
1301
        const char *filename,
 
1302
        FLAC__StreamEncoderProgressCallback progress_callback,
 
1303
        void *client_data
 
1304
)
 
1305
{
 
1306
        return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
 
1307
}
 
1308
 
 
1309
FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
 
1310
        FLAC__StreamEncoder *encoder,
 
1311
        const char *filename,
 
1312
        FLAC__StreamEncoderProgressCallback progress_callback,
 
1313
        void *client_data
 
1314
)
 
1315
{
 
1316
        return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
 
1317
}
 
1318
 
 
1319
FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
 
1320
{
 
1321
        FLAC__bool error = false;
 
1322
 
 
1323
        FLAC__ASSERT(0 != encoder);
 
1324
        FLAC__ASSERT(0 != encoder->private_);
 
1325
        FLAC__ASSERT(0 != encoder->protected_);
966
1326
 
967
1327
        if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
968
 
                return;
 
1328
                return true;
969
1329
 
970
1330
        if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
971
1331
                if(encoder->private_->current_sample_number != 0) {
 
1332
                        const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
972
1333
                        encoder->protected_->blocksize = encoder->private_->current_sample_number;
973
 
                        process_frame_(encoder, true); /* true => is last frame */
974
 
                }
975
 
        }
976
 
 
977
 
        FLAC__MD5Final(encoder->private_->metadata.data.stream_info.md5sum, &encoder->private_->md5context);
978
 
 
979
 
        if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
980
 
                encoder->private_->metadata_callback(encoder, &encoder->private_->metadata, encoder->private_->client_data);
981
 
        }
982
 
 
983
 
        if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder)
984
 
                FLAC__stream_decoder_finish(encoder->private_->verify.decoder);
 
1334
                        if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
 
1335
                                error = true;
 
1336
                }
 
1337
        }
 
1338
 
 
1339
        FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
 
1340
 
 
1341
        if(!encoder->private_->is_being_deleted) {
 
1342
                if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
 
1343
                        if(encoder->private_->seek_callback) {
 
1344
#if FLAC__HAS_OGG
 
1345
                                if(encoder->private_->is_ogg)
 
1346
                                        update_ogg_metadata_(encoder);
 
1347
                                else
 
1348
#endif
 
1349
                                update_metadata_(encoder);
 
1350
 
 
1351
                                /* check if an error occurred while updating metadata */
 
1352
                                if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
 
1353
                                        error = true;
 
1354
                        }
 
1355
                        if(encoder->private_->metadata_callback)
 
1356
                                encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
 
1357
                }
 
1358
 
 
1359
                if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
 
1360
                        if(!error)
 
1361
                                encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
 
1362
                        error = true;
 
1363
                }
 
1364
        }
 
1365
 
 
1366
        if(0 != encoder->private_->file) {
 
1367
                if(encoder->private_->file != stdout)
 
1368
                        fclose(encoder->private_->file);
 
1369
                encoder->private_->file = 0;
 
1370
        }
 
1371
 
 
1372
#if FLAC__HAS_OGG
 
1373
        if(encoder->private_->is_ogg)
 
1374
                FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
 
1375
#endif
985
1376
 
986
1377
        free_(encoder);
987
1378
        set_defaults_(encoder);
988
1379
 
989
 
        encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
 
1380
        if(!error)
 
1381
                encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
 
1382
 
 
1383
        return !error;
 
1384
}
 
1385
 
 
1386
FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
 
1387
{
 
1388
        FLAC__ASSERT(0 != encoder);
 
1389
        FLAC__ASSERT(0 != encoder->private_);
 
1390
        FLAC__ASSERT(0 != encoder->protected_);
 
1391
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
 
1392
                return false;
 
1393
#if FLAC__HAS_OGG
 
1394
        /* can't check encoder->private_->is_ogg since that's not set until init time */
 
1395
        FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
 
1396
        return true;
 
1397
#else
 
1398
        (void)value;
 
1399
        return false;
 
1400
#endif
990
1401
}
991
1402
 
992
1403
FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
993
1404
{
994
1405
        FLAC__ASSERT(0 != encoder);
 
1406
        FLAC__ASSERT(0 != encoder->private_);
 
1407
        FLAC__ASSERT(0 != encoder->protected_);
995
1408
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
996
1409
                return false;
997
1410
#ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1003
1416
FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1004
1417
{
1005
1418
        FLAC__ASSERT(0 != encoder);
 
1419
        FLAC__ASSERT(0 != encoder->private_);
 
1420
        FLAC__ASSERT(0 != encoder->protected_);
1006
1421
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1007
1422
                return false;
1008
1423
        encoder->protected_->streamable_subset = value;
1009
1424
        return true;
1010
1425
}
1011
1426
 
1012
 
FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1013
 
{
1014
 
        FLAC__ASSERT(0 != encoder);
1015
 
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1016
 
                return false;
1017
 
        encoder->protected_->do_mid_side_stereo = value;
1018
 
        return true;
1019
 
}
1020
 
 
1021
 
FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1022
 
{
1023
 
        FLAC__ASSERT(0 != encoder);
1024
 
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1025
 
                return false;
1026
 
        encoder->protected_->loose_mid_side_stereo = value;
1027
 
        return true;
1028
 
}
1029
 
 
1030
1427
FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1031
1428
{
1032
1429
        FLAC__ASSERT(0 != encoder);
 
1430
        FLAC__ASSERT(0 != encoder->private_);
 
1431
        FLAC__ASSERT(0 != encoder->protected_);
1033
1432
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1034
1433
                return false;
1035
1434
        encoder->protected_->channels = value;
1039
1438
FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1040
1439
{
1041
1440
        FLAC__ASSERT(0 != encoder);
 
1441
        FLAC__ASSERT(0 != encoder->private_);
 
1442
        FLAC__ASSERT(0 != encoder->protected_);
1042
1443
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1043
1444
                return false;
1044
1445
        encoder->protected_->bits_per_sample = value;
1048
1449
FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1049
1450
{
1050
1451
        FLAC__ASSERT(0 != encoder);
 
1452
        FLAC__ASSERT(0 != encoder->private_);
 
1453
        FLAC__ASSERT(0 != encoder->protected_);
1051
1454
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1052
1455
                return false;
1053
1456
        encoder->protected_->sample_rate = value;
1054
1457
        return true;
1055
1458
}
1056
1459
 
 
1460
FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
 
1461
{
 
1462
        FLAC__bool ok = true;
 
1463
        FLAC__ASSERT(0 != encoder);
 
1464
        FLAC__ASSERT(0 != encoder->private_);
 
1465
        FLAC__ASSERT(0 != encoder->protected_);
 
1466
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
 
1467
                return false;
 
1468
        if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
 
1469
                value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
 
1470
        ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
 
1471
        ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
 
1472
#if 0
 
1473
        /* was: */
 
1474
        ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
 
1475
        /* but it's too hard to specify the string in a locale-specific way */
 
1476
#else
 
1477
        encoder->protected_->num_apodizations = 1;
 
1478
        encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
 
1479
        encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
 
1480
#endif
 
1481
        ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
 
1482
        ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
 
1483
        ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
 
1484
        ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
 
1485
        ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
 
1486
        ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
 
1487
        ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
 
1488
        ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
 
1489
        return ok;
 
1490
}
 
1491
 
1057
1492
FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1058
1493
{
1059
1494
        FLAC__ASSERT(0 != encoder);
 
1495
        FLAC__ASSERT(0 != encoder->private_);
 
1496
        FLAC__ASSERT(0 != encoder->protected_);
1060
1497
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1061
1498
                return false;
1062
1499
        encoder->protected_->blocksize = value;
1063
1500
        return true;
1064
1501
}
1065
1502
 
 
1503
FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
 
1504
{
 
1505
        FLAC__ASSERT(0 != encoder);
 
1506
        FLAC__ASSERT(0 != encoder->private_);
 
1507
        FLAC__ASSERT(0 != encoder->protected_);
 
1508
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
 
1509
                return false;
 
1510
        encoder->protected_->do_mid_side_stereo = value;
 
1511
        return true;
 
1512
}
 
1513
 
 
1514
FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
 
1515
{
 
1516
        FLAC__ASSERT(0 != encoder);
 
1517
        FLAC__ASSERT(0 != encoder->private_);
 
1518
        FLAC__ASSERT(0 != encoder->protected_);
 
1519
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
 
1520
                return false;
 
1521
        encoder->protected_->loose_mid_side_stereo = value;
 
1522
        return true;
 
1523
}
 
1524
 
 
1525
FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
 
1526
{
 
1527
        FLAC__ASSERT(0 != encoder);
 
1528
        FLAC__ASSERT(0 != encoder->private_);
 
1529
        FLAC__ASSERT(0 != encoder->protected_);
 
1530
        FLAC__ASSERT(0 != specification);
 
1531
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
 
1532
                return false;
 
1533
#ifdef FLAC__INTEGER_ONLY_LIBRARY
 
1534
        (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
 
1535
#else
 
1536
        encoder->protected_->num_apodizations = 0;
 
1537
        while(1) {
 
1538
                const char *s = strchr(specification, ';');
 
1539
                const size_t n = s? (size_t)(s - specification) : strlen(specification);
 
1540
                if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
 
1541
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
 
1542
                else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
 
1543
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
 
1544
                else if(n==8  && 0 == strncmp("blackman"     , specification, n))
 
1545
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
 
1546
                else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
 
1547
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
 
1548
                else if(n==6  && 0 == strncmp("connes"       , specification, n))
 
1549
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
 
1550
                else if(n==7  && 0 == strncmp("flattop"      , specification, n))
 
1551
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
 
1552
                else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
 
1553
                        FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
 
1554
                        if (stddev > 0.0 && stddev <= 0.5) {
 
1555
                                encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
 
1556
                                encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
 
1557
                        }
 
1558
                }
 
1559
                else if(n==7  && 0 == strncmp("hamming"      , specification, n))
 
1560
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
 
1561
                else if(n==4  && 0 == strncmp("hann"         , specification, n))
 
1562
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
 
1563
                else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
 
1564
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
 
1565
                else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
 
1566
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
 
1567
                else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
 
1568
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
 
1569
                else if(n==8  && 0 == strncmp("triangle"     , specification, n))
 
1570
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
 
1571
                else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
 
1572
                        FLAC__real p = (FLAC__real)strtod(specification+6, 0);
 
1573
                        if (p >= 0.0 && p <= 1.0) {
 
1574
                                encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
 
1575
                                encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
 
1576
                        }
 
1577
                }
 
1578
                else if(n==5  && 0 == strncmp("welch"        , specification, n))
 
1579
                        encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
 
1580
                if (encoder->protected_->num_apodizations == 32)
 
1581
                        break;
 
1582
                if (s)
 
1583
                        specification = s+1;
 
1584
                else
 
1585
                        break;
 
1586
        }
 
1587
        if(encoder->protected_->num_apodizations == 0) {
 
1588
                encoder->protected_->num_apodizations = 1;
 
1589
                encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
 
1590
                encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
 
1591
        }
 
1592
#endif
 
1593
        return true;
 
1594
}
 
1595
 
1066
1596
FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1067
1597
{
1068
1598
        FLAC__ASSERT(0 != encoder);
 
1599
        FLAC__ASSERT(0 != encoder->private_);
 
1600
        FLAC__ASSERT(0 != encoder->protected_);
1069
1601
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1070
1602
                return false;
1071
1603
        encoder->protected_->max_lpc_order = value;
1075
1607
FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1076
1608
{
1077
1609
        FLAC__ASSERT(0 != encoder);
 
1610
        FLAC__ASSERT(0 != encoder->private_);
 
1611
        FLAC__ASSERT(0 != encoder->protected_);
1078
1612
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1079
1613
                return false;
1080
1614
        encoder->protected_->qlp_coeff_precision = value;
1084
1618
FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1085
1619
{
1086
1620
        FLAC__ASSERT(0 != encoder);
 
1621
        FLAC__ASSERT(0 != encoder->private_);
 
1622
        FLAC__ASSERT(0 != encoder->protected_);
1087
1623
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1088
1624
                return false;
1089
1625
        encoder->protected_->do_qlp_coeff_prec_search = value;
1093
1629
FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1094
1630
{
1095
1631
        FLAC__ASSERT(0 != encoder);
 
1632
        FLAC__ASSERT(0 != encoder->private_);
 
1633
        FLAC__ASSERT(0 != encoder->protected_);
1096
1634
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1097
1635
                return false;
1098
1636
#if 0
1107
1645
FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1108
1646
{
1109
1647
        FLAC__ASSERT(0 != encoder);
 
1648
        FLAC__ASSERT(0 != encoder->private_);
 
1649
        FLAC__ASSERT(0 != encoder->protected_);
1110
1650
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1111
1651
                return false;
1112
1652
        encoder->protected_->do_exhaustive_model_search = value;
1116
1656
FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1117
1657
{
1118
1658
        FLAC__ASSERT(0 != encoder);
 
1659
        FLAC__ASSERT(0 != encoder->private_);
 
1660
        FLAC__ASSERT(0 != encoder->protected_);
1119
1661
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1120
1662
                return false;
1121
1663
        encoder->protected_->min_residual_partition_order = value;
1125
1667
FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1126
1668
{
1127
1669
        FLAC__ASSERT(0 != encoder);
 
1670
        FLAC__ASSERT(0 != encoder->private_);
 
1671
        FLAC__ASSERT(0 != encoder->protected_);
1128
1672
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1129
1673
                return false;
1130
1674
        encoder->protected_->max_residual_partition_order = value;
1134
1678
FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1135
1679
{
1136
1680
        FLAC__ASSERT(0 != encoder);
 
1681
        FLAC__ASSERT(0 != encoder->private_);
 
1682
        FLAC__ASSERT(0 != encoder->protected_);
1137
1683
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1138
1684
                return false;
1139
1685
#if 0
1148
1694
FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1149
1695
{
1150
1696
        FLAC__ASSERT(0 != encoder);
 
1697
        FLAC__ASSERT(0 != encoder->private_);
 
1698
        FLAC__ASSERT(0 != encoder->protected_);
1151
1699
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1152
1700
                return false;
1153
1701
        encoder->protected_->total_samples_estimate = value;
1157
1705
FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1158
1706
{
1159
1707
        FLAC__ASSERT(0 != encoder);
1160
 
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1161
 
                return false;
1162
 
        encoder->protected_->metadata = metadata;
1163
 
        encoder->protected_->num_metadata_blocks = num_blocks;
1164
 
        return true;
1165
 
}
1166
 
 
1167
 
FLAC_API FLAC__bool FLAC__stream_encoder_set_write_callback(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderWriteCallback value)
1168
 
{
1169
 
        FLAC__ASSERT(0 != encoder);
1170
 
        FLAC__ASSERT(0 != value);
1171
 
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1172
 
                return false;
1173
 
        encoder->private_->write_callback = value;
1174
 
        return true;
1175
 
}
1176
 
 
1177
 
FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata_callback(FLAC__StreamEncoder *encoder, FLAC__StreamEncoderMetadataCallback value)
1178
 
{
1179
 
        FLAC__ASSERT(0 != encoder);
1180
 
        FLAC__ASSERT(0 != value);
1181
 
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1182
 
                return false;
1183
 
        encoder->private_->metadata_callback = value;
1184
 
        return true;
1185
 
}
1186
 
 
1187
 
FLAC_API FLAC__bool FLAC__stream_encoder_set_client_data(FLAC__StreamEncoder *encoder, void *value)
1188
 
{
1189
 
        FLAC__ASSERT(0 != encoder);
1190
 
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1191
 
                return false;
1192
 
        encoder->private_->client_data = value;
 
1708
        FLAC__ASSERT(0 != encoder->private_);
 
1709
        FLAC__ASSERT(0 != encoder->protected_);
 
1710
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
 
1711
                return false;
 
1712
        if(0 == metadata)
 
1713
                num_blocks = 0;
 
1714
        if(0 == num_blocks)
 
1715
                metadata = 0;
 
1716
        /* realloc() does not do exactly what we want so... */
 
1717
        if(encoder->protected_->metadata) {
 
1718
                free(encoder->protected_->metadata);
 
1719
                encoder->protected_->metadata = 0;
 
1720
                encoder->protected_->num_metadata_blocks = 0;
 
1721
        }
 
1722
        if(num_blocks) {
 
1723
                FLAC__StreamMetadata **m;
 
1724
                if(0 == (m = (FLAC__StreamMetadata**)malloc(sizeof(m[0]) * num_blocks)))
 
1725
                        return false;
 
1726
                memcpy(m, metadata, sizeof(m[0]) * num_blocks);
 
1727
                encoder->protected_->metadata = m;
 
1728
                encoder->protected_->num_metadata_blocks = num_blocks;
 
1729
        }
 
1730
#if FLAC__HAS_OGG
 
1731
        if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
 
1732
                return false;
 
1733
#endif
1193
1734
        return true;
1194
1735
}
1195
1736
 
1200
1741
FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1201
1742
{
1202
1743
        FLAC__ASSERT(0 != encoder);
 
1744
        FLAC__ASSERT(0 != encoder->private_);
 
1745
        FLAC__ASSERT(0 != encoder->protected_);
1203
1746
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1204
1747
                return false;
1205
1748
        encoder->private_->disable_constant_subframes = value;
1209
1752
FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1210
1753
{
1211
1754
        FLAC__ASSERT(0 != encoder);
 
1755
        FLAC__ASSERT(0 != encoder->private_);
 
1756
        FLAC__ASSERT(0 != encoder->protected_);
1212
1757
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1213
1758
                return false;
1214
1759
        encoder->private_->disable_fixed_subframes = value;
1218
1763
FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1219
1764
{
1220
1765
        FLAC__ASSERT(0 != encoder);
 
1766
        FLAC__ASSERT(0 != encoder->private_);
 
1767
        FLAC__ASSERT(0 != encoder->protected_);
1221
1768
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1222
1769
                return false;
1223
1770
        encoder->private_->disable_verbatim_subframes = value;
1227
1774
FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1228
1775
{
1229
1776
        FLAC__ASSERT(0 != encoder);
 
1777
        FLAC__ASSERT(0 != encoder->private_);
 
1778
        FLAC__ASSERT(0 != encoder->protected_);
1230
1779
        return encoder->protected_->state;
1231
1780
}
1232
1781
 
1233
1782
FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1234
1783
{
1235
1784
        FLAC__ASSERT(0 != encoder);
 
1785
        FLAC__ASSERT(0 != encoder->private_);
 
1786
        FLAC__ASSERT(0 != encoder->protected_);
1236
1787
        if(encoder->protected_->verify)
1237
1788
                return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1238
1789
        else
1241
1792
 
1242
1793
FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1243
1794
{
 
1795
        FLAC__ASSERT(0 != encoder);
 
1796
        FLAC__ASSERT(0 != encoder->private_);
 
1797
        FLAC__ASSERT(0 != encoder->protected_);
1244
1798
        if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1245
1799
                return FLAC__StreamEncoderStateString[encoder->protected_->state];
1246
1800
        else
1250
1804
FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
1251
1805
{
1252
1806
        FLAC__ASSERT(0 != encoder);
 
1807
        FLAC__ASSERT(0 != encoder->private_);
 
1808
        FLAC__ASSERT(0 != encoder->protected_);
1253
1809
        if(0 != absolute_sample)
1254
1810
                *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1255
1811
        if(0 != frame_number)
1267
1823
FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1268
1824
{
1269
1825
        FLAC__ASSERT(0 != encoder);
 
1826
        FLAC__ASSERT(0 != encoder->private_);
 
1827
        FLAC__ASSERT(0 != encoder->protected_);
1270
1828
        return encoder->protected_->verify;
1271
1829
}
1272
1830
 
1273
1831
FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1274
1832
{
1275
1833
        FLAC__ASSERT(0 != encoder);
 
1834
        FLAC__ASSERT(0 != encoder->private_);
 
1835
        FLAC__ASSERT(0 != encoder->protected_);
1276
1836
        return encoder->protected_->streamable_subset;
1277
1837
}
1278
1838
 
1279
 
FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1280
 
{
1281
 
        FLAC__ASSERT(0 != encoder);
1282
 
        return encoder->protected_->do_mid_side_stereo;
1283
 
}
1284
 
 
1285
 
FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1286
 
{
1287
 
        FLAC__ASSERT(0 != encoder);
1288
 
        return encoder->protected_->loose_mid_side_stereo;
1289
 
}
1290
 
 
1291
1839
FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1292
1840
{
1293
1841
        FLAC__ASSERT(0 != encoder);
 
1842
        FLAC__ASSERT(0 != encoder->private_);
 
1843
        FLAC__ASSERT(0 != encoder->protected_);
1294
1844
        return encoder->protected_->channels;
1295
1845
}
1296
1846
 
1297
1847
FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1298
1848
{
1299
1849
        FLAC__ASSERT(0 != encoder);
 
1850
        FLAC__ASSERT(0 != encoder->private_);
 
1851
        FLAC__ASSERT(0 != encoder->protected_);
1300
1852
        return encoder->protected_->bits_per_sample;
1301
1853
}
1302
1854
 
1303
1855
FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1304
1856
{
1305
1857
        FLAC__ASSERT(0 != encoder);
 
1858
        FLAC__ASSERT(0 != encoder->private_);
 
1859
        FLAC__ASSERT(0 != encoder->protected_);
1306
1860
        return encoder->protected_->sample_rate;
1307
1861
}
1308
1862
 
1309
1863
FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1310
1864
{
1311
1865
        FLAC__ASSERT(0 != encoder);
 
1866
        FLAC__ASSERT(0 != encoder->private_);
 
1867
        FLAC__ASSERT(0 != encoder->protected_);
1312
1868
        return encoder->protected_->blocksize;
1313
1869
}
1314
1870
 
 
1871
FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
 
1872
{
 
1873
        FLAC__ASSERT(0 != encoder);
 
1874
        FLAC__ASSERT(0 != encoder->private_);
 
1875
        FLAC__ASSERT(0 != encoder->protected_);
 
1876
        return encoder->protected_->do_mid_side_stereo;
 
1877
}
 
1878
 
 
1879
FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
 
1880
{
 
1881
        FLAC__ASSERT(0 != encoder);
 
1882
        FLAC__ASSERT(0 != encoder->private_);
 
1883
        FLAC__ASSERT(0 != encoder->protected_);
 
1884
        return encoder->protected_->loose_mid_side_stereo;
 
1885
}
 
1886
 
1315
1887
FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1316
1888
{
1317
1889
        FLAC__ASSERT(0 != encoder);
 
1890
        FLAC__ASSERT(0 != encoder->private_);
 
1891
        FLAC__ASSERT(0 != encoder->protected_);
1318
1892
        return encoder->protected_->max_lpc_order;
1319
1893
}
1320
1894
 
1321
1895
FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1322
1896
{
1323
1897
        FLAC__ASSERT(0 != encoder);
 
1898
        FLAC__ASSERT(0 != encoder->private_);
 
1899
        FLAC__ASSERT(0 != encoder->protected_);
1324
1900
        return encoder->protected_->qlp_coeff_precision;
1325
1901
}
1326
1902
 
1327
1903
FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1328
1904
{
1329
1905
        FLAC__ASSERT(0 != encoder);
 
1906
        FLAC__ASSERT(0 != encoder->private_);
 
1907
        FLAC__ASSERT(0 != encoder->protected_);
1330
1908
        return encoder->protected_->do_qlp_coeff_prec_search;
1331
1909
}
1332
1910
 
1333
1911
FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1334
1912
{
1335
1913
        FLAC__ASSERT(0 != encoder);
 
1914
        FLAC__ASSERT(0 != encoder->private_);
 
1915
        FLAC__ASSERT(0 != encoder->protected_);
1336
1916
        return encoder->protected_->do_escape_coding;
1337
1917
}
1338
1918
 
1339
1919
FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1340
1920
{
1341
1921
        FLAC__ASSERT(0 != encoder);
 
1922
        FLAC__ASSERT(0 != encoder->private_);
 
1923
        FLAC__ASSERT(0 != encoder->protected_);
1342
1924
        return encoder->protected_->do_exhaustive_model_search;
1343
1925
}
1344
1926
 
1345
1927
FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1346
1928
{
1347
1929
        FLAC__ASSERT(0 != encoder);
 
1930
        FLAC__ASSERT(0 != encoder->private_);
 
1931
        FLAC__ASSERT(0 != encoder->protected_);
1348
1932
        return encoder->protected_->min_residual_partition_order;
1349
1933
}
1350
1934
 
1351
1935
FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1352
1936
{
1353
1937
        FLAC__ASSERT(0 != encoder);
 
1938
        FLAC__ASSERT(0 != encoder->private_);
 
1939
        FLAC__ASSERT(0 != encoder->protected_);
1354
1940
        return encoder->protected_->max_residual_partition_order;
1355
1941
}
1356
1942
 
1357
1943
FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1358
1944
{
1359
1945
        FLAC__ASSERT(0 != encoder);
 
1946
        FLAC__ASSERT(0 != encoder->private_);
 
1947
        FLAC__ASSERT(0 != encoder->protected_);
1360
1948
        return encoder->protected_->rice_parameter_search_dist;
1361
1949
}
1362
1950
 
1363
1951
FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1364
1952
{
1365
1953
        FLAC__ASSERT(0 != encoder);
 
1954
        FLAC__ASSERT(0 != encoder->private_);
 
1955
        FLAC__ASSERT(0 != encoder->protected_);
1366
1956
        return encoder->protected_->total_samples_estimate;
1367
1957
}
1368
1958
 
1373
1963
        const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1374
1964
 
1375
1965
        FLAC__ASSERT(0 != encoder);
 
1966
        FLAC__ASSERT(0 != encoder->private_);
 
1967
        FLAC__ASSERT(0 != encoder->protected_);
1376
1968
        FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1377
1969
 
1378
1970
        j = 0;
1388
1980
                         */
1389
1981
                        do {
1390
1982
                                if(encoder->protected_->verify)
1391
 
                                        append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
 
1983
                                        append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1392
1984
 
1393
 
                                for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
 
1985
                                /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
 
1986
                                for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1394
1987
                                        x = mid = side = buffer[0][j];
1395
1988
                                        encoder->private_->integer_signal[0][i] = x;
1396
1989
#ifndef FLAC__INTEGER_ONLY_LIBRARY
1412
2005
#endif
1413
2006
                                        encoder->private_->current_sample_number++;
1414
2007
                                }
1415
 
                                if(i == blocksize) {
1416
 
                                        if(!process_frame_(encoder, false)) /* false => not last frame */
 
2008
                                /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
 
2009
                                if(i > blocksize) {
 
2010
                                        if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1417
2011
                                                return false;
 
2012
                                        /* move unprocessed overread samples to beginnings of arrays */
 
2013
                                        FLAC__ASSERT(i == blocksize+OVERREAD_);
 
2014
                                        FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
 
2015
                                        i--;
 
2016
                                        encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
 
2017
                                        encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
 
2018
                                        encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
 
2019
                                        encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
 
2020
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
2021
                                        encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
 
2022
                                        encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
 
2023
                                        encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
 
2024
                                        encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
 
2025
#endif
 
2026
                                        encoder->private_->current_sample_number = 1;
1418
2027
                                }
1419
2028
                        } while(j < samples);
1420
2029
                }
1425
2034
                         */
1426
2035
                        do {
1427
2036
                                if(encoder->protected_->verify)
1428
 
                                        append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
 
2037
                                        append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1429
2038
 
1430
 
                                for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
 
2039
                                /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
 
2040
                                for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1431
2041
                                        for(channel = 0; channel < channels; channel++) {
1432
2042
                                                x = buffer[channel][j];
1433
2043
                                                encoder->private_->integer_signal[channel][i] = x;
1437
2047
                                        }
1438
2048
                                        encoder->private_->current_sample_number++;
1439
2049
                                }
1440
 
                                if(i == blocksize) {
1441
 
                                        if(!process_frame_(encoder, false)) /* false => not last frame */
 
2050
                                /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
 
2051
                                if(i > blocksize) {
 
2052
                                        if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1442
2053
                                                return false;
 
2054
                                        /* move unprocessed overread samples to beginnings of arrays */
 
2055
                                        FLAC__ASSERT(i == blocksize+OVERREAD_);
 
2056
                                        FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
 
2057
                                        i--;
 
2058
                                        for(channel = 0; channel < channels; channel++) {
 
2059
                                                encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
 
2060
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
2061
                                                encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
 
2062
#endif
 
2063
                                        }
 
2064
                                        encoder->private_->current_sample_number = 1;
1443
2065
                                }
1444
2066
                        } while(j < samples);
1445
2067
                }
1452
2074
                         */
1453
2075
                        do {
1454
2076
                                if(encoder->protected_->verify)
1455
 
                                        append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
 
2077
                                        append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1456
2078
 
1457
 
                                for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
 
2079
                                /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
 
2080
                                for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1458
2081
                                        encoder->private_->integer_signal[0][i] = mid = side = buffer[0][j];
1459
2082
                                        x = buffer[1][j];
1460
2083
                                        encoder->private_->integer_signal[1][i] = x;
1465
2088
                                        encoder->private_->integer_signal_mid_side[0][i] = mid;
1466
2089
                                        encoder->private_->current_sample_number++;
1467
2090
                                }
1468
 
                                if(i == blocksize) {
1469
 
                                        if(!process_frame_(encoder, false)) /* false => not last frame */
 
2091
                                /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
 
2092
                                if(i > blocksize) {
 
2093
                                        if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1470
2094
                                                return false;
 
2095
                                        /* move unprocessed overread samples to beginnings of arrays */
 
2096
                                        FLAC__ASSERT(i == blocksize+OVERREAD_);
 
2097
                                        FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
 
2098
                                        i--;
 
2099
                                        encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
 
2100
                                        encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
 
2101
                                        encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
 
2102
                                        encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
 
2103
                                        encoder->private_->current_sample_number = 1;
1471
2104
                                }
1472
2105
                        } while(j < samples);
1473
2106
                }
1478
2111
                         */
1479
2112
                        do {
1480
2113
                                if(encoder->protected_->verify)
1481
 
                                        append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
 
2114
                                        append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1482
2115
 
1483
 
                                for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
 
2116
                                /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
 
2117
                                for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1484
2118
                                        for(channel = 0; channel < channels; channel++)
1485
2119
                                                encoder->private_->integer_signal[channel][i] = buffer[channel][j];
1486
2120
                                        encoder->private_->current_sample_number++;
1487
2121
                                }
1488
 
                                if(i == blocksize) {
1489
 
                                        if(!process_frame_(encoder, false)) /* false => not last frame */
 
2122
                                /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
 
2123
                                if(i > blocksize) {
 
2124
                                        if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1490
2125
                                                return false;
 
2126
                                        /* move unprocessed overread samples to beginnings of arrays */
 
2127
                                        FLAC__ASSERT(i == blocksize+OVERREAD_);
 
2128
                                        FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
 
2129
                                        i--;
 
2130
                                        for(channel = 0; channel < channels; channel++)
 
2131
                                                encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
 
2132
                                        encoder->private_->current_sample_number = 1;
1491
2133
                                }
1492
2134
                        } while(j < samples);
1493
2135
                }
1503
2145
        const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1504
2146
 
1505
2147
        FLAC__ASSERT(0 != encoder);
 
2148
        FLAC__ASSERT(0 != encoder->private_);
 
2149
        FLAC__ASSERT(0 != encoder->protected_);
1506
2150
        FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1507
2151
 
1508
2152
        j = k = 0;
1518
2162
                         */
1519
2163
                        do {
1520
2164
                                if(encoder->protected_->verify)
1521
 
                                        append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
 
2165
                                        append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1522
2166
 
1523
 
                                for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
 
2167
                                /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
 
2168
                                for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1524
2169
                                        x = mid = side = buffer[k++];
1525
2170
                                        encoder->private_->integer_signal[0][i] = x;
1526
2171
#ifndef FLAC__INTEGER_ONLY_LIBRARY
1542
2187
#endif
1543
2188
                                        encoder->private_->current_sample_number++;
1544
2189
                                }
1545
 
                                if(i == blocksize) {
1546
 
                                        if(!process_frame_(encoder, false)) /* false => not last frame */
 
2190
                                /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
 
2191
                                if(i > blocksize) {
 
2192
                                        if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1547
2193
                                                return false;
 
2194
                                        /* move unprocessed overread samples to beginnings of arrays */
 
2195
                                        FLAC__ASSERT(i == blocksize+OVERREAD_);
 
2196
                                        FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
 
2197
                                        i--;
 
2198
                                        encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
 
2199
                                        encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
 
2200
                                        encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
 
2201
                                        encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
 
2202
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
2203
                                        encoder->private_->real_signal[0][0] = encoder->private_->real_signal[0][i];
 
2204
                                        encoder->private_->real_signal[1][0] = encoder->private_->real_signal[1][i];
 
2205
                                        encoder->private_->real_signal_mid_side[0][0] = encoder->private_->real_signal_mid_side[0][i];
 
2206
                                        encoder->private_->real_signal_mid_side[1][0] = encoder->private_->real_signal_mid_side[1][i];
 
2207
#endif
 
2208
                                        encoder->private_->current_sample_number = 1;
1548
2209
                                }
1549
2210
                        } while(j < samples);
1550
2211
                }
1555
2216
                         */
1556
2217
                        do {
1557
2218
                                if(encoder->protected_->verify)
1558
 
                                        append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
 
2219
                                        append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1559
2220
 
1560
 
                                for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
 
2221
                                /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
 
2222
                                for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1561
2223
                                        for(channel = 0; channel < channels; channel++) {
1562
2224
                                                x = buffer[k++];
1563
2225
                                                encoder->private_->integer_signal[channel][i] = x;
1567
2229
                                        }
1568
2230
                                        encoder->private_->current_sample_number++;
1569
2231
                                }
1570
 
                                if(i == blocksize) {
1571
 
                                        if(!process_frame_(encoder, false)) /* false => not last frame */
 
2232
                                /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
 
2233
                                if(i > blocksize) {
 
2234
                                        if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1572
2235
                                                return false;
 
2236
                                        /* move unprocessed overread samples to beginnings of arrays */
 
2237
                                        FLAC__ASSERT(i == blocksize+OVERREAD_);
 
2238
                                        FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
 
2239
                                        i--;
 
2240
                                        for(channel = 0; channel < channels; channel++) {
 
2241
                                                encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
 
2242
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
2243
                                                encoder->private_->real_signal[channel][0] = encoder->private_->real_signal[channel][i];
 
2244
#endif
 
2245
                                        }
 
2246
                                        encoder->private_->current_sample_number = 1;
1573
2247
                                }
1574
2248
                        } while(j < samples);
1575
2249
                }
1582
2256
                         */
1583
2257
                        do {
1584
2258
                                if(encoder->protected_->verify)
1585
 
                                        append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
 
2259
                                        append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1586
2260
 
1587
 
                                for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
 
2261
                                /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
 
2262
                                for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1588
2263
                                        encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
1589
2264
                                        x = buffer[k++];
1590
2265
                                        encoder->private_->integer_signal[1][i] = x;
1595
2270
                                        encoder->private_->integer_signal_mid_side[0][i] = mid;
1596
2271
                                        encoder->private_->current_sample_number++;
1597
2272
                                }
1598
 
                                if(i == blocksize) {
1599
 
                                        if(!process_frame_(encoder, false)) /* false => not last frame */
 
2273
                                /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
 
2274
                                if(i > blocksize) {
 
2275
                                        if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1600
2276
                                                return false;
 
2277
                                        /* move unprocessed overread samples to beginnings of arrays */
 
2278
                                        FLAC__ASSERT(i == blocksize+OVERREAD_);
 
2279
                                        FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
 
2280
                                        i--;
 
2281
                                        encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][i];
 
2282
                                        encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][i];
 
2283
                                        encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][i];
 
2284
                                        encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][i];
 
2285
                                        encoder->private_->current_sample_number = 1;
1601
2286
                                }
1602
2287
                        } while(j < samples);
1603
2288
                }
1608
2293
                         */
1609
2294
                        do {
1610
2295
                                if(encoder->protected_->verify)
1611
 
                                        append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize-encoder->private_->current_sample_number, samples-j));
 
2296
                                        append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+1-encoder->private_->current_sample_number, samples-j));
1612
2297
 
1613
 
                                for(i = encoder->private_->current_sample_number; i < blocksize && j < samples; i++, j++) {
 
2298
                                /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
 
2299
                                for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1614
2300
                                        for(channel = 0; channel < channels; channel++)
1615
2301
                                                encoder->private_->integer_signal[channel][i] = buffer[k++];
1616
2302
                                        encoder->private_->current_sample_number++;
1617
2303
                                }
1618
 
                                if(i == blocksize) {
1619
 
                                        if(!process_frame_(encoder, false)) /* false => not last frame */
 
2304
                                /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
 
2305
                                if(i > blocksize) {
 
2306
                                        if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
1620
2307
                                                return false;
 
2308
                                        /* move unprocessed overread samples to beginnings of arrays */
 
2309
                                        FLAC__ASSERT(i == blocksize+OVERREAD_);
 
2310
                                        FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
 
2311
                                        i--;
 
2312
                                        for(channel = 0; channel < channels; channel++)
 
2313
                                                encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][i];
 
2314
                                        encoder->private_->current_sample_number = 1;
1621
2315
                                }
1622
2316
                        } while(j < samples);
1623
2317
                }
1647
2341
        encoder->protected_->channels = 2;
1648
2342
        encoder->protected_->bits_per_sample = 16;
1649
2343
        encoder->protected_->sample_rate = 44100;
1650
 
        encoder->protected_->blocksize = 1152;
 
2344
        encoder->protected_->blocksize = 0;
 
2345
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
2346
        encoder->protected_->num_apodizations = 1;
 
2347
        encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
 
2348
        encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
 
2349
#endif
1651
2350
        encoder->protected_->max_lpc_order = 0;
1652
2351
        encoder->protected_->qlp_coeff_precision = 0;
1653
2352
        encoder->protected_->do_qlp_coeff_prec_search = false;
1660
2359
        encoder->protected_->metadata = 0;
1661
2360
        encoder->protected_->num_metadata_blocks = 0;
1662
2361
 
 
2362
        encoder->private_->seek_table = 0;
1663
2363
        encoder->private_->disable_constant_subframes = false;
1664
2364
        encoder->private_->disable_fixed_subframes = false;
1665
2365
        encoder->private_->disable_verbatim_subframes = false;
 
2366
#if FLAC__HAS_OGG
 
2367
        encoder->private_->is_ogg = false;
 
2368
#endif
 
2369
        encoder->private_->read_callback = 0;
1666
2370
        encoder->private_->write_callback = 0;
 
2371
        encoder->private_->seek_callback = 0;
 
2372
        encoder->private_->tell_callback = 0;
1667
2373
        encoder->private_->metadata_callback = 0;
 
2374
        encoder->private_->progress_callback = 0;
1668
2375
        encoder->private_->client_data = 0;
 
2376
 
 
2377
#if FLAC__HAS_OGG
 
2378
        FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
 
2379
#endif
1669
2380
}
1670
2381
 
1671
2382
void free_(FLAC__StreamEncoder *encoder)
1673
2384
        unsigned i, channel;
1674
2385
 
1675
2386
        FLAC__ASSERT(0 != encoder);
 
2387
        if(encoder->protected_->metadata) {
 
2388
                free(encoder->protected_->metadata);
 
2389
                encoder->protected_->metadata = 0;
 
2390
                encoder->protected_->num_metadata_blocks = 0;
 
2391
        }
1676
2392
        for(i = 0; i < encoder->protected_->channels; i++) {
1677
2393
                if(0 != encoder->private_->integer_signal_unaligned[i]) {
1678
2394
                        free(encoder->private_->integer_signal_unaligned[i]);
1697
2413
                }
1698
2414
#endif
1699
2415
        }
 
2416
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
2417
        for(i = 0; i < encoder->protected_->num_apodizations; i++) {
 
2418
                if(0 != encoder->private_->window_unaligned[i]) {
 
2419
                        free(encoder->private_->window_unaligned[i]);
 
2420
                        encoder->private_->window_unaligned[i] = 0;
 
2421
                }
 
2422
        }
 
2423
        if(0 != encoder->private_->windowed_signal_unaligned) {
 
2424
                free(encoder->private_->windowed_signal_unaligned);
 
2425
                encoder->private_->windowed_signal_unaligned = 0;
 
2426
        }
 
2427
#endif
1700
2428
        for(channel = 0; channel < encoder->protected_->channels; channel++) {
1701
2429
                for(i = 0; i < 2; i++) {
1702
2430
                        if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
1713
2441
                        }
1714
2442
                }
1715
2443
        }
1716
 
        if(0 != encoder->private_->abs_residual_unaligned) {
1717
 
                free(encoder->private_->abs_residual_unaligned);
1718
 
                encoder->private_->abs_residual_unaligned = 0;
1719
 
        }
1720
2444
        if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
1721
2445
                free(encoder->private_->abs_residual_partition_sums_unaligned);
1722
2446
                encoder->private_->abs_residual_partition_sums_unaligned = 0;
1733
2457
                        }
1734
2458
                }
1735
2459
        }
1736
 
        FLAC__bitbuffer_free(encoder->private_->frame);
 
2460
        FLAC__bitwriter_free(encoder->private_->frame);
1737
2461
}
1738
2462
 
1739
 
FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_size)
 
2463
FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
1740
2464
{
1741
2465
        FLAC__bool ok;
1742
2466
        unsigned i, channel;
1743
2467
 
1744
 
        FLAC__ASSERT(new_size > 0);
 
2468
        FLAC__ASSERT(new_blocksize > 0);
1745
2469
        FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1746
2470
        FLAC__ASSERT(encoder->private_->current_sample_number == 0);
1747
2471
 
1748
2472
        /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
1749
 
        if(new_size <= encoder->private_->input_capacity)
 
2473
        if(new_blocksize <= encoder->private_->input_capacity)
1750
2474
                return true;
1751
2475
 
1752
2476
        ok = true;
1754
2478
        /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
1755
2479
         * requires that the input arrays (in our case the integer signals)
1756
2480
         * have a buffer of up to 3 zeroes in front (at negative indices) for
1757
 
         * alignment purposes; we use 4 to keep the data well-aligned.
 
2481
         * alignment purposes; we use 4 in front to keep the data well-aligned.
1758
2482
         */
1759
2483
 
1760
2484
        for(i = 0; ok && i < encoder->protected_->channels; i++) {
1761
 
                ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size+4, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
1762
 
#ifndef FLAC__INTEGER_ONLY_LIBRARY
1763
 
                if(encoder->protected_->max_lpc_order > 0)
1764
 
                        ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
1765
 
#endif
 
2485
                ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
1766
2486
                memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
1767
2487
                encoder->private_->integer_signal[i] += 4;
 
2488
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
2489
                if(encoder->protected_->max_lpc_order > 0)
 
2490
                        ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
 
2491
#endif
1768
2492
        }
1769
2493
        for(i = 0; ok && i < 2; i++) {
1770
 
                ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size+4, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
1771
 
#ifndef FLAC__INTEGER_ONLY_LIBRARY
1772
 
                if(encoder->protected_->max_lpc_order > 0)
1773
 
                        ok = ok && FLAC__memory_alloc_aligned_real_array(new_size, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
1774
 
#endif
 
2494
                ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_mid_side_unaligned[i], &encoder->private_->integer_signal_mid_side[i]);
1775
2495
                memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
1776
2496
                encoder->private_->integer_signal_mid_side[i] += 4;
1777
 
        }
 
2497
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
2498
                if(encoder->protected_->max_lpc_order > 0)
 
2499
                        ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_mid_side_unaligned[i], &encoder->private_->real_signal_mid_side[i]);
 
2500
#endif
 
2501
        }
 
2502
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
2503
        if(ok && encoder->protected_->max_lpc_order > 0) {
 
2504
                for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
 
2505
                        ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
 
2506
                ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
 
2507
        }
 
2508
#endif
1778
2509
        for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
1779
2510
                for(i = 0; ok && i < 2; i++) {
1780
 
                        ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
 
2511
                        ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
1781
2512
                }
1782
2513
        }
1783
2514
        for(channel = 0; ok && channel < 2; channel++) {
1784
2515
                for(i = 0; ok && i < 2; i++) {
1785
 
                        ok = ok && FLAC__memory_alloc_aligned_int32_array(new_size, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
 
2516
                        ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_mid_side_unaligned[channel][i], &encoder->private_->residual_workspace_mid_side[channel][i]);
1786
2517
                }
1787
2518
        }
1788
 
        ok = ok && FLAC__memory_alloc_aligned_uint32_array(new_size, &encoder->private_->abs_residual_unaligned, &encoder->private_->abs_residual);
1789
 
        if(encoder->private_->precompute_partition_sums || encoder->protected_->do_escape_coding) /* we require precompute_partition_sums if do_escape_coding because of their intertwined nature */
1790
 
                ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_size * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
 
2519
        /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
 
2520
        /*@@@ new_blocksize*2 is too pessimistic, but to fix, we need smarter logic because a smaller new_blocksize can actually increase the # of partitions; would require moving this out into a separate function, then checking its capacity against the need of the current blocksize&min/max_partition_order (and maybe predictor order) */
 
2521
        ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
1791
2522
        if(encoder->protected_->do_escape_coding)
1792
 
                ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_size * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
 
2523
                ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
 
2524
 
 
2525
        /* now adjust the windows if the blocksize has changed */
 
2526
#ifndef FLAC__INTEGER_ONLY_LIBRARY
 
2527
        if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
 
2528
                for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
 
2529
                        switch(encoder->protected_->apodizations[i].type) {
 
2530
                                case FLAC__APODIZATION_BARTLETT:
 
2531
                                        FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
 
2532
                                        break;
 
2533
                                case FLAC__APODIZATION_BARTLETT_HANN:
 
2534
                                        FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
 
2535
                                        break;
 
2536
                                case FLAC__APODIZATION_BLACKMAN:
 
2537
                                        FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
 
2538
                                        break;
 
2539
                                case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
 
2540
                                        FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
 
2541
                                        break;
 
2542
                                case FLAC__APODIZATION_CONNES:
 
2543
                                        FLAC__window_connes(encoder->private_->window[i], new_blocksize);
 
2544
                                        break;
 
2545
                                case FLAC__APODIZATION_FLATTOP:
 
2546
                                        FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
 
2547
                                        break;
 
2548
                                case FLAC__APODIZATION_GAUSS:
 
2549
                                        FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
 
2550
                                        break;
 
2551
                                case FLAC__APODIZATION_HAMMING:
 
2552
                                        FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
 
2553
                                        break;
 
2554
                                case FLAC__APODIZATION_HANN:
 
2555
                                        FLAC__window_hann(encoder->private_->window[i], new_blocksize);
 
2556
                                        break;
 
2557
                                case FLAC__APODIZATION_KAISER_BESSEL:
 
2558
                                        FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
 
2559
                                        break;
 
2560
                                case FLAC__APODIZATION_NUTTALL:
 
2561
                                        FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
 
2562
                                        break;
 
2563
                                case FLAC__APODIZATION_RECTANGLE:
 
2564
                                        FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
 
2565
                                        break;
 
2566
                                case FLAC__APODIZATION_TRIANGLE:
 
2567
                                        FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
 
2568
                                        break;
 
2569
                                case FLAC__APODIZATION_TUKEY:
 
2570
                                        FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
 
2571
                                        break;
 
2572
                                case FLAC__APODIZATION_WELCH:
 
2573
                                        FLAC__window_welch(encoder->private_->window[i], new_blocksize);
 
2574
                                        break;
 
2575
                                default:
 
2576
                                        FLAC__ASSERT(0);
 
2577
                                        /* double protection */
 
2578
                                        FLAC__window_hann(encoder->private_->window[i], new_blocksize);
 
2579
                                        break;
 
2580
                        }
 
2581
                }
 
2582
        }
 
2583
#endif
1793
2584
 
1794
2585
        if(ok)
1795
 
                encoder->private_->input_capacity = new_size;
 
2586
                encoder->private_->input_capacity = new_blocksize;
1796
2587
        else
1797
2588
                encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1798
2589
 
1799
2590
        return ok;
1800
2591
}
1801
2592
 
1802
 
FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples)
 
2593
FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
1803
2594
{
1804
2595
        const FLAC__byte *buffer;
1805
 
        unsigned bytes;
1806
 
 
1807
 
        FLAC__ASSERT(FLAC__bitbuffer_is_byte_aligned(encoder->private_->frame));
1808
 
 
1809
 
        FLAC__bitbuffer_get_buffer(encoder->private_->frame, &buffer, &bytes);
 
2596
        size_t bytes;
 
2597
 
 
2598
        FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
 
2599
 
 
2600
        if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
 
2601
                encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
 
2602
                return false;
 
2603
        }
1810
2604
 
1811
2605
        if(encoder->protected_->verify) {
1812
2606
                encoder->private_->verify.output.data = buffer;
1816
2610
                }
1817
2611
                else {
1818
2612
                        if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
1819
 
                                FLAC__bitbuffer_release_buffer(encoder->private_->frame);
 
2613
                                FLAC__bitwriter_release_buffer(encoder->private_->frame);
 
2614
                                FLAC__bitwriter_clear(encoder->private_->frame);
1820
2615
                                if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
1821
2616
                                        encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1822
2617
                                return false;
1824
2619
                }
1825
2620
        }
1826
2621
 
1827
 
        if(encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
1828
 
                FLAC__bitbuffer_release_buffer(encoder->private_->frame);
1829
 
                encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_WRITING;
 
2622
        if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
 
2623
                FLAC__bitwriter_release_buffer(encoder->private_->frame);
 
2624
                FLAC__bitwriter_clear(encoder->private_->frame);
 
2625
                encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1830
2626
                return false;
1831
2627
        }
1832
2628
 
1833
 
        FLAC__bitbuffer_release_buffer(encoder->private_->frame);
 
2629
        FLAC__bitwriter_release_buffer(encoder->private_->frame);
 
2630
        FLAC__bitwriter_clear(encoder->private_->frame);
1834
2631
 
1835
2632
        if(samples > 0) {
1836
 
                encoder->private_->metadata.data.stream_info.min_framesize = min(bytes, encoder->private_->metadata.data.stream_info.min_framesize);
1837
 
                encoder->private_->metadata.data.stream_info.max_framesize = max(bytes, encoder->private_->metadata.data.stream_info.max_framesize);
 
2633
                encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
 
2634
                encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
1838
2635
        }
1839
2636
 
1840
2637
        return true;
1841
2638
}
1842
2639
 
1843
 
FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
1844
 
{
 
2640
FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
 
2641
{
 
2642
        FLAC__StreamEncoderWriteStatus status;
 
2643
        FLAC__uint64 output_position = 0;
 
2644
 
 
2645
        /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
 
2646
        if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
 
2647
                encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
2648
                return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
 
2649
        }
 
2650
 
 
2651
        /*
 
2652
         * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
 
2653
         */
 
2654
        if(samples == 0) {
 
2655
                FLAC__MetadataType type = (buffer[0] & 0x7f);
 
2656
                if(type == FLAC__METADATA_TYPE_STREAMINFO)
 
2657
                        encoder->protected_->streaminfo_offset = output_position;
 
2658
                else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
 
2659
                        encoder->protected_->seektable_offset = output_position;
 
2660
        }
 
2661
 
 
2662
        /*
 
2663
         * Mark the current seek point if hit (if audio_offset == 0 that
 
2664
         * means we're still writing metadata and haven't hit the first
 
2665
         * frame yet)
 
2666
         */
 
2667
        if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
 
2668
                const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
 
2669
                const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
 
2670
                const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
 
2671
                FLAC__uint64 test_sample;
 
2672
                unsigned i;
 
2673
                for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
 
2674
                        test_sample = encoder->private_->seek_table->points[i].sample_number;
 
2675
                        if(test_sample > frame_last_sample) {
 
2676
                                break;
 
2677
                        }
 
2678
                        else if(test_sample >= frame_first_sample) {
 
2679
                                encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
 
2680
                                encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
 
2681
                                encoder->private_->seek_table->points[i].frame_samples = blocksize;
 
2682
                                encoder->private_->first_seekpoint_to_check++;
 
2683
                                /* DO NOT: "break;" and here's why:
 
2684
                                 * The seektable template may contain more than one target
 
2685
                                 * sample for any given frame; we will keep looping, generating
 
2686
                                 * duplicate seekpoints for them, and we'll clean it up later,
 
2687
                                 * just before writing the seektable back to the metadata.
 
2688
                                 */
 
2689
                        }
 
2690
                        else {
 
2691
                                encoder->private_->first_seekpoint_to_check++;
 
2692
                        }
 
2693
                }
 
2694
        }
 
2695
 
 
2696
#if FLAC__HAS_OGG
 
2697
        if(encoder->private_->is_ogg) {
 
2698
                status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
 
2699
                        &encoder->protected_->ogg_encoder_aspect,
 
2700
                        buffer,
 
2701
                        bytes,
 
2702
                        samples,
 
2703
                        encoder->private_->current_frame_number,
 
2704
                        is_last_block,
 
2705
                        (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
 
2706
                        encoder,
 
2707
                        encoder->private_->client_data
 
2708
                );
 
2709
        }
 
2710
        else
 
2711
#endif
 
2712
        status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
 
2713
 
 
2714
        if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
 
2715
                encoder->private_->bytes_written += bytes;
 
2716
                encoder->private_->samples_written += samples;
 
2717
                /* we keep a high watermark on the number of frames written because
 
2718
                 * when the encoder goes back to write metadata, 'current_frame'
 
2719
                 * will drop back to 0.
 
2720
                 */
 
2721
                encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
 
2722
        }
 
2723
        else
 
2724
                encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
2725
 
 
2726
        return status;
 
2727
}
 
2728
 
 
2729
/* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
 
2730
void update_metadata_(const FLAC__StreamEncoder *encoder)
 
2731
{
 
2732
        FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
 
2733
        const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
 
2734
        const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
 
2735
        const unsigned min_framesize = metadata->data.stream_info.min_framesize;
 
2736
        const unsigned max_framesize = metadata->data.stream_info.max_framesize;
 
2737
        const unsigned bps = metadata->data.stream_info.bits_per_sample;
 
2738
        FLAC__StreamEncoderSeekStatus seek_status;
 
2739
 
 
2740
        FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
 
2741
 
 
2742
        /* All this is based on intimate knowledge of the stream header
 
2743
         * layout, but a change to the header format that would break this
 
2744
         * would also break all streams encoded in the previous format.
 
2745
         */
 
2746
 
 
2747
        /*
 
2748
         * Write MD5 signature
 
2749
         */
 
2750
        {
 
2751
                const unsigned md5_offset =
 
2752
                        FLAC__STREAM_METADATA_HEADER_LENGTH +
 
2753
                        (
 
2754
                                FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
 
2755
                                FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
 
2756
                                FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
 
2757
                                FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
 
2758
                                FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
 
2759
                                FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
 
2760
                                FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
 
2761
                                FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
 
2762
                        ) / 8;
 
2763
 
 
2764
                if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
 
2765
                        if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
 
2766
                                encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
2767
                        return;
 
2768
                }
 
2769
                if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
 
2770
                        encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
2771
                        return;
 
2772
                }
 
2773
        }
 
2774
 
 
2775
        /*
 
2776
         * Write total samples
 
2777
         */
 
2778
        {
 
2779
                const unsigned total_samples_byte_offset =
 
2780
                        FLAC__STREAM_METADATA_HEADER_LENGTH +
 
2781
                        (
 
2782
                                FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
 
2783
                                FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
 
2784
                                FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
 
2785
                                FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
 
2786
                                FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
 
2787
                                FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
 
2788
                                FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
 
2789
                                - 4
 
2790
                        ) / 8;
 
2791
 
 
2792
                b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
 
2793
                b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
 
2794
                b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
 
2795
                b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
 
2796
                b[4] = (FLAC__byte)(samples & 0xFF);
 
2797
                if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + total_samples_byte_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
 
2798
                        if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
 
2799
                                encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
2800
                        return;
 
2801
                }
 
2802
                if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
 
2803
                        encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
2804
                        return;
 
2805
                }
 
2806
        }
 
2807
 
 
2808
        /*
 
2809
         * Write min/max framesize
 
2810
         */
 
2811
        {
 
2812
                const unsigned min_framesize_offset =
 
2813
                        FLAC__STREAM_METADATA_HEADER_LENGTH +
 
2814
                        (
 
2815
                                FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
 
2816
                                FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
 
2817
                        ) / 8;
 
2818
 
 
2819
                b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
 
2820
                b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
 
2821
                b[2] = (FLAC__byte)(min_framesize & 0xFF);
 
2822
                b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
 
2823
                b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
 
2824
                b[5] = (FLAC__byte)(max_framesize & 0xFF);
 
2825
                if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + min_framesize_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
 
2826
                        if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
 
2827
                                encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
2828
                        return;
 
2829
                }
 
2830
                if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
 
2831
                        encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
2832
                        return;
 
2833
                }
 
2834
        }
 
2835
 
 
2836
        /*
 
2837
         * Write seektable
 
2838
         */
 
2839
        if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
 
2840
                unsigned i;
 
2841
 
 
2842
                FLAC__format_seektable_sort(encoder->private_->seek_table);
 
2843
 
 
2844
                FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
 
2845
 
 
2846
                if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->seektable_offset + FLAC__STREAM_METADATA_HEADER_LENGTH, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
 
2847
                        if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
 
2848
                                encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
2849
                        return;
 
2850
                }
 
2851
 
 
2852
                for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
 
2853
                        FLAC__uint64 xx;
 
2854
                        unsigned x;
 
2855
                        xx = encoder->private_->seek_table->points[i].sample_number;
 
2856
                        b[7] = (FLAC__byte)xx; xx >>= 8;
 
2857
                        b[6] = (FLAC__byte)xx; xx >>= 8;
 
2858
                        b[5] = (FLAC__byte)xx; xx >>= 8;
 
2859
                        b[4] = (FLAC__byte)xx; xx >>= 8;
 
2860
                        b[3] = (FLAC__byte)xx; xx >>= 8;
 
2861
                        b[2] = (FLAC__byte)xx; xx >>= 8;
 
2862
                        b[1] = (FLAC__byte)xx; xx >>= 8;
 
2863
                        b[0] = (FLAC__byte)xx; xx >>= 8;
 
2864
                        xx = encoder->private_->seek_table->points[i].stream_offset;
 
2865
                        b[15] = (FLAC__byte)xx; xx >>= 8;
 
2866
                        b[14] = (FLAC__byte)xx; xx >>= 8;
 
2867
                        b[13] = (FLAC__byte)xx; xx >>= 8;
 
2868
                        b[12] = (FLAC__byte)xx; xx >>= 8;
 
2869
                        b[11] = (FLAC__byte)xx; xx >>= 8;
 
2870
                        b[10] = (FLAC__byte)xx; xx >>= 8;
 
2871
                        b[9] = (FLAC__byte)xx; xx >>= 8;
 
2872
                        b[8] = (FLAC__byte)xx; xx >>= 8;
 
2873
                        x = encoder->private_->seek_table->points[i].frame_samples;
 
2874
                        b[17] = (FLAC__byte)x; x >>= 8;
 
2875
                        b[16] = (FLAC__byte)x; x >>= 8;
 
2876
                        if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
 
2877
                                encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
 
2878
                                return;
 
2879
                        }
 
2880
                }
 
2881
        }
 
2882
}
 
2883
 
 
2884
#if FLAC__HAS_OGG
 
2885
/* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
 
2886
void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
 
2887
{
 
2888
        /* the # of bytes in the 1st packet that precede the STREAMINFO */
 
2889
        static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
 
2890
                FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
 
2891
                FLAC__OGG_MAPPING_MAGIC_LENGTH +
 
2892
                FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
 
2893
                FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
 
2894
                FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
 
2895
                FLAC__STREAM_SYNC_LENGTH
 
2896
        ;
 
2897
        FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
 
2898
        const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
 
2899
        const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
 
2900
        const unsigned min_framesize = metadata->data.stream_info.min_framesize;
 
2901
        const unsigned max_framesize = metadata->data.stream_info.max_framesize;
 
2902
        ogg_page page;
 
2903
 
 
2904
        FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
 
2905
        FLAC__ASSERT(0 != encoder->private_->seek_callback);
 
2906
 
 
2907
        /* Pre-check that client supports seeking, since we don't want the
 
2908
         * ogg_helper code to ever have to deal with this condition.
 
2909
         */
 
2910
        if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
 
2911
                return;
 
2912
 
 
2913
        /* All this is based on intimate knowledge of the stream header
 
2914
         * layout, but a change to the header format that would break this
 
2915
         * would also break all streams encoded in the previous format.
 
2916
         */
 
2917
 
 
2918
        /**
 
2919
         ** Write STREAMINFO stats
 
2920
         **/
 
2921
        simple_ogg_page__init(&page);
 
2922
        if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
 
2923
                simple_ogg_page__clear(&page);
 
2924
                return; /* state already set */
 
2925
        }
 
2926
 
 
2927
        /*
 
2928
         * Write MD5 signature
 
2929
         */
 
2930
        {
 
2931
                const unsigned md5_offset =
 
2932
                        FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
 
2933
                        FLAC__STREAM_METADATA_HEADER_LENGTH +
 
2934
                        (
 
2935
                                FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
 
2936
                                FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
 
2937
                                FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
 
2938
                                FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
 
2939
                                FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
 
2940
                                FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
 
2941
                                FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
 
2942
                                FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
 
2943
                        ) / 8;
 
2944
 
 
2945
                if(md5_offset + 16 > (unsigned)page.body_len) {
 
2946
                        encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
 
2947
                        simple_ogg_page__clear(&page);
 
2948
                        return;
 
2949
                }
 
2950
                memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
 
2951
        }
 
2952
 
 
2953
        /*
 
2954
         * Write total samples
 
2955
         */
 
2956
        {
 
2957
                const unsigned total_samples_byte_offset =
 
2958
                        FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
 
2959
                        FLAC__STREAM_METADATA_HEADER_LENGTH +
 
2960
                        (
 
2961
                                FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
 
2962
                                FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
 
2963
                                FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
 
2964
                                FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
 
2965
                                FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
 
2966
                                FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
 
2967
                                FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
 
2968
                                - 4
 
2969
                        ) / 8;
 
2970
 
 
2971
                if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
 
2972
                        encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
 
2973
                        simple_ogg_page__clear(&page);
 
2974
                        return;
 
2975
                }
 
2976
                b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
 
2977
                b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
 
2978
                b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
 
2979
                b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
 
2980
                b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
 
2981
                b[4] = (FLAC__byte)(samples & 0xFF);
 
2982
                memcpy(page.body + total_samples_byte_offset, b, 5);
 
2983
        }
 
2984
 
 
2985
        /*
 
2986
         * Write min/max framesize
 
2987
         */
 
2988
        {
 
2989
                const unsigned min_framesize_offset =
 
2990
                        FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
 
2991
                        FLAC__STREAM_METADATA_HEADER_LENGTH +
 
2992
                        (
 
2993
                                FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
 
2994
                                FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
 
2995
                        ) / 8;
 
2996
 
 
2997
                if(min_framesize_offset + 6 > (unsigned)page.body_len) {
 
2998
                        encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
 
2999
                        simple_ogg_page__clear(&page);
 
3000
                        return;
 
3001
                }
 
3002
                b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
 
3003
                b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
 
3004
                b[2] = (FLAC__byte)(min_framesize & 0xFF);
 
3005
                b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
 
3006
                b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
 
3007
                b[5] = (FLAC__byte)(max_framesize & 0xFF);
 
3008
                memcpy(page.body + min_framesize_offset, b, 6);
 
3009
        }
 
3010
        if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
 
3011
                simple_ogg_page__clear(&page);
 
3012
                return; /* state already set */
 
3013
        }
 
3014
        simple_ogg_page__clear(&page);
 
3015
 
 
3016
        /*
 
3017
         * Write seektable
 
3018
         */
 
3019
        if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
 
3020
                unsigned i;
 
3021
                FLAC__byte *p;
 
3022
 
 
3023
                FLAC__format_seektable_sort(encoder->private_->seek_table);
 
3024
 
 
3025
                FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
 
3026
 
 
3027
                simple_ogg_page__init(&page);
 
3028
                if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
 
3029
                        simple_ogg_page__clear(&page);
 
3030
                        return; /* state already set */
 
3031
                }
 
3032
 
 
3033
                if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
 
3034
                        encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
 
3035
                        simple_ogg_page__clear(&page);
 
3036
                        return;
 
3037
                }
 
3038
 
 
3039
                for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
 
3040
                        FLAC__uint64 xx;
 
3041
                        unsigned x;
 
3042
                        xx = encoder->private_->seek_table->points[i].sample_number;
 
3043
                        b[7] = (FLAC__byte)xx; xx >>= 8;
 
3044
                        b[6] = (FLAC__byte)xx; xx >>= 8;
 
3045
                        b[5] = (FLAC__byte)xx; xx >>= 8;
 
3046
                        b[4] = (FLAC__byte)xx; xx >>= 8;
 
3047
                        b[3] = (FLAC__byte)xx; xx >>= 8;
 
3048
                        b[2] = (FLAC__byte)xx; xx >>= 8;
 
3049
                        b[1] = (FLAC__byte)xx; xx >>= 8;
 
3050
                        b[0] = (FLAC__byte)xx; xx >>= 8;
 
3051
                        xx = encoder->private_->seek_table->points[i].stream_offset;
 
3052
                        b[15] = (FLAC__byte)xx; xx >>= 8;
 
3053
                        b[14] = (FLAC__byte)xx; xx >>= 8;
 
3054
                        b[13] = (FLAC__byte)xx; xx >>= 8;
 
3055
                        b[12] = (FLAC__byte)xx; xx >>= 8;
 
3056
                        b[11] = (FLAC__byte)xx; xx >>= 8;
 
3057
                        b[10] = (FLAC__byte)xx; xx >>= 8;
 
3058
                        b[9] = (FLAC__byte)xx; xx >>= 8;
 
3059
                        b[8] = (FLAC__byte)xx; xx >>= 8;
 
3060
                        x = encoder->private_->seek_table->points[i].frame_samples;
 
3061
                        b[17] = (FLAC__byte)x; x >>= 8;
 
3062
                        b[16] = (FLAC__byte)x; x >>= 8;
 
3063
                        memcpy(p, b, 18);
 
3064
                }
 
3065
 
 
3066
                if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
 
3067
                        simple_ogg_page__clear(&page);
 
3068
                        return; /* state already set */
 
3069
                }
 
3070
                simple_ogg_page__clear(&page);
 
3071
        }
 
3072
}
 
3073
#endif
 
3074
 
 
3075
FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
 
3076
{
 
3077
        FLAC__uint16 crc;
1845
3078
        FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1846
3079
 
1847
3080
        /*
1855
3088
        /*
1856
3089
         * Process the frame header and subframes into the frame bitbuffer
1857
3090
         */
1858
 
        if(!process_subframes_(encoder, is_last_frame)) {
 
3091
        if(!process_subframes_(encoder, is_fractional_block)) {
1859
3092
                /* the above function sets the state for us in case of an error */
1860
3093
                return false;
1861
3094
        }
1863
3096
        /*
1864
3097
         * Zero-pad the frame to a byte_boundary
1865
3098
         */
1866
 
        if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(encoder->private_->frame)) {
 
3099
        if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
1867
3100
                encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1868
3101
                return false;
1869
3102
        }
1871
3104
        /*
1872
3105
         * CRC-16 the whole thing
1873
3106
         */
1874
 
        FLAC__ASSERT(FLAC__bitbuffer_is_byte_aligned(encoder->private_->frame));
1875
 
        FLAC__bitbuffer_write_raw_uint32(encoder->private_->frame, FLAC__bitbuffer_get_write_crc16(encoder->private_->frame), FLAC__FRAME_FOOTER_CRC_LEN);
 
3107
        FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
 
3108
        if(
 
3109
                !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
 
3110
                !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
 
3111
        ) {
 
3112
                encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
 
3113
                return false;
 
3114
        }
1876
3115
 
1877
3116
        /*
1878
3117
         * Write it
1879
3118
         */
1880
 
        if(!write_bitbuffer_(encoder, encoder->protected_->blocksize)) {
 
3119
        if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
1881
3120
                /* the above function sets the state for us in case of an error */
1882
3121
                return false;
1883
3122
        }
1887
3126
         */
1888
3127
        encoder->private_->current_sample_number = 0;
1889
3128
        encoder->private_->current_frame_number++;
1890
 
        encoder->private_->metadata.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
 
3129
        encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
1891
3130
 
1892
3131
        return true;
1893
3132
}
1894
3133
 
1895
 
FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_last_frame)
 
3134
FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
1896
3135
{
1897
3136
        FLAC__FrameHeader frame_header;
1898
3137
        unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
1899
 
        FLAC__bool do_independent, do_mid_side, precompute_partition_sums;
 
3138
        FLAC__bool do_independent, do_mid_side;
1900
3139
 
1901
3140
        /*
1902
3141
         * Calculate the min,max Rice partition orders
1903
3142
         */
1904
 
        if(is_last_frame) {
 
3143
        if(is_fractional_block) {
1905
3144
                max_partition_order = 0;
1906
3145
        }
1907
3146
        else {
1910
3149
        }
1911
3150
        min_partition_order = min(min_partition_order, max_partition_order);
1912
3151
 
1913
 
        precompute_partition_sums = encoder->private_->precompute_partition_sums && ((max_partition_order > min_partition_order) || encoder->protected_->do_escape_coding);
1914
 
 
1915
3152
        /*
1916
3153
         * Setup the frame
1917
3154
         */
1918
 
        if(!FLAC__bitbuffer_clear(encoder->private_->frame)) {
1919
 
                encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
1920
 
                return false;
1921
 
        }
1922
3155
        frame_header.blocksize = encoder->protected_->blocksize;
1923
3156
        frame_header.sample_rate = encoder->protected_->sample_rate;
1924
3157
        frame_header.channels = encoder->protected_->channels;
1982
3215
                                        encoder,
1983
3216
                                        min_partition_order,
1984
3217
                                        max_partition_order,
1985
 
                                        precompute_partition_sums,
1986
3218
                                        &frame_header,
1987
3219
                                        encoder->private_->subframe_bps[channel],
1988
3220
                                        encoder->private_->integer_signal[channel],
2012
3244
                                        encoder,
2013
3245
                                        min_partition_order,
2014
3246
                                        max_partition_order,
2015
 
                                        precompute_partition_sums,
2016
3247
                                        &frame_header,
2017
3248
                                        encoder->private_->subframe_bps_mid_side[channel],
2018
3249
                                        encoder->private_->integer_signal_mid_side[channel],
2046
3277
                else {
2047
3278
                        unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
2048
3279
                        unsigned min_bits;
2049
 
                        FLAC__ChannelAssignment ca;
 
3280
                        int ca;
2050
3281
 
 
3282
                        FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
 
3283
                        FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
 
3284
                        FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
 
3285
                        FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
2051
3286
                        FLAC__ASSERT(do_independent && do_mid_side);
2052
3287
 
2053
3288
                        /* We have to figure out which channel assignent results in the smallest frame */
2056
3291
                        bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
2057
3292
                        bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
2058
3293
 
2059
 
                        for(channel_assignment = (FLAC__ChannelAssignment)0, min_bits = bits[0], ca = (FLAC__ChannelAssignment)1; (int)ca <= 3; ca = (FLAC__ChannelAssignment)((int)ca + 1)) {
 
3294
                        channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
 
3295
                        min_bits = bits[channel_assignment];
 
3296
                        for(ca = 1; ca <= 3; ca++) {
2060
3297
                                if(bits[ca] < min_bits) {
2061
3298
                                        min_bits = bits[ca];
2062
 
                                        channel_assignment = ca;
 
3299
                                        channel_assignment = (FLAC__ChannelAssignment)ca;
2063
3300
                                }
2064
3301
                        }
2065
3302
                }
2066
3303
 
2067
3304
                frame_header.channel_assignment = channel_assignment;
2068
3305
 
2069
 
                if(!FLAC__frame_add_header(&frame_header, encoder->protected_->streamable_subset, encoder->private_->frame)) {
 
3306
                if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
2070
3307
                        encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2071
3308
                        return false;
2072
3309
                }
2114
3351
                }
2115
3352
 
2116
3353
                /* note that encoder_add_subframe_ sets the state for us in case of an error */
2117
 
                if(!add_subframe_(encoder, &frame_header, left_bps , left_subframe , encoder->private_->frame))
 
3354
                if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
2118
3355
                        return false;
2119
 
                if(!add_subframe_(encoder, &frame_header, right_bps, right_subframe, encoder->private_->frame))
 
3356
                if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
2120
3357
                        return false;
2121
3358
        }
2122
3359
        else {
2123
 
                if(!FLAC__frame_add_header(&frame_header, encoder->protected_->streamable_subset, encoder->private_->frame)) {
 
3360
                if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
2124
3361
                        encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2125
3362
                        return false;
2126
3363
                }
2127
3364
 
2128
3365
                for(channel = 0; channel < encoder->protected_->channels; channel++) {
2129
 
                        if(!add_subframe_(encoder, &frame_header, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
 
3366
                        if(!add_subframe_(encoder, frame_header.blocksize, encoder->private_->subframe_bps[channel], &encoder->private_->subframe_workspace[channel][encoder->private_->best_subframe[channel]], encoder->private_->frame)) {
2130
3367
                                /* the above function sets the state for us in case of an error */
2131
3368
                                return false;
2132
3369
                        }
2148
3385
        FLAC__StreamEncoder *encoder,
2149
3386
        unsigned min_partition_order,
2150
3387
        unsigned max_partition_order,
2151
 
        FLAC__bool precompute_partition_sums,
2152
3388
        const FLAC__FrameHeader *frame_header,
2153
3389
        unsigned subframe_bps,
2154
3390
        const FLAC__int32 integer_signal[],
2179
3415
        unsigned _candidate_bits, _best_bits;
2180
3416
        unsigned _best_subframe;
2181
3417
 
 
3418
        FLAC__ASSERT(frame_header->blocksize > 0);
 
3419
 
2182
3420
        /* verbatim subframe is the baseline against which we measure other compressed subframes */
2183
3421
        _best_subframe = 0;
2184
3422
        if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
2185
3423
                _best_bits = UINT_MAX;
2186
3424
        else
2187
 
                _best_bits = evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
 
3425
                _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
2188
3426
 
2189
3427
        if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
2190
3428
                unsigned signal_is_constant = false;
2209
3447
                        }
2210
3448
                }
2211
3449
                if(signal_is_constant) {
2212
 
                        _candidate_bits = evaluate_constant_subframe_(integer_signal[0], subframe_bps, subframe[!_best_subframe]);
 
3450
                        _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
2213
3451
                        if(_candidate_bits < _best_bits) {
2214
3452
                                _best_subframe = !_best_subframe;
2215
3453
                                _best_bits = _candidate_bits;
2225
3463
                                else {
2226
3464
                                        min_fixed_order = max_fixed_order = guess_fixed_order;
2227
3465
                                }
 
3466
                                if(max_fixed_order >= frame_header->blocksize)
 
3467
                                        max_fixed_order = frame_header->blocksize - 1;
2228
3468
                                for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
2229
3469
#ifndef FLAC__INTEGER_ONLY_LIBRARY
2230
3470
                                        if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
2235
3475
                                                continue; /* don't even try */
2236
3476
                                        rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > FLAC__FP_ZERO)? (unsigned)FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]+FLAC__FP_ONE_HALF) : 0; /* 0.5 is for rounding */
2237
3477
#endif
2238
 
#ifndef FLAC__SYMMETRIC_RICE
2239
3478
                                        rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
2240
 
#endif
2241
3479
                                        if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2242
3480
#ifdef DEBUG_VERBOSE
2243
3481
                                                fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2249
3487
                                                        encoder,
2250
3488
                                                        integer_signal,
2251
3489
                                                        residual[!_best_subframe],
2252
 
                                                        encoder->private_->abs_residual,
2253
3490
                                                        encoder->private_->abs_residual_partition_sums,
2254
3491
                                                        encoder->private_->raw_bits_per_partition,
2255
3492
                                                        frame_header->blocksize,
2258
3495
                                                        rice_parameter,
2259
3496
                                                        min_partition_order,
2260
3497
                                                        max_partition_order,
2261
 
                                                        precompute_partition_sums,
2262
3498
                                                        encoder->protected_->do_escape_coding,
2263
3499
                                                        encoder->protected_->rice_parameter_search_dist,
2264
3500
                                                        subframe[!_best_subframe],
2279
3515
                                else
2280
3516
                                        max_lpc_order = encoder->protected_->max_lpc_order;
2281
3517
                                if(max_lpc_order > 0) {
2282
 
                                        encoder->private_->local_lpc_compute_autocorrelation(real_signal, frame_header->blocksize, max_lpc_order+1, autoc);
2283
 
                                        /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
2284
 
                                        if(autoc[0] != 0.0) {
2285
 
                                                FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, encoder->private_->lp_coeff, lpc_error);
2286
 
                                                if(encoder->protected_->do_exhaustive_model_search) {
2287
 
                                                        min_lpc_order = 1;
2288
 
                                                }
2289
 
                                                else {
2290
 
                                                        unsigned guess_lpc_order = FLAC__lpc_compute_best_order(lpc_error, max_lpc_order, frame_header->blocksize, subframe_bps);
2291
 
                                                        min_lpc_order = max_lpc_order = guess_lpc_order;
2292
 
                                                }
2293
 
                                                for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
2294
 
                                                        lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
2295
 
                                                        if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
2296
 
                                                                continue; /* don't even try */
2297
 
                                                        rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
2298
 
#ifndef FLAC__SYMMETRIC_RICE
2299
 
                                                        rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
2300
 
#endif
2301
 
                                                        if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2302
 
#ifdef DEBUG_VERBOSE
2303
 
                                                                fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2304
 
#endif
2305
 
                                                                rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2306
 
                                                        }
2307
 
                                                        if(encoder->protected_->do_qlp_coeff_prec_search) {
2308
 
                                                                min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
2309
 
                                                                /* ensure a 32-bit datapath throughout for 16bps or less */
2310
 
                                                                if(subframe_bps <= 16)
2311
 
                                                                        max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
2312
 
                                                                else
2313
 
                                                                        max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
 
3518
                                        unsigned a;
 
3519
                                        for (a = 0; a < encoder->protected_->num_apodizations; a++) {
 
3520
                                                FLAC__lpc_window_data(real_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
 
3521
                                                encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
 
3522
                                                /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
 
3523
                                                if(autoc[0] != 0.0) {
 
3524
                                                        FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
 
3525
                                                        if(encoder->protected_->do_exhaustive_model_search) {
 
3526
                                                                min_lpc_order = 1;
2314
3527
                                                        }
2315
3528
                                                        else {
2316
 
                                                                min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
2317
 
                                                        }
2318
 
                                                        for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
2319
 
                                                                _candidate_bits =
2320
 
                                                                        evaluate_lpc_subframe_(
2321
 
                                                                                encoder,
2322
 
                                                                                integer_signal,
2323
 
                                                                                residual[!_best_subframe],
2324
 
                                                                                encoder->private_->abs_residual,
2325
 
                                                                                encoder->private_->abs_residual_partition_sums,
2326
 
                                                                                encoder->private_->raw_bits_per_partition,
2327
 
                                                                                encoder->private_->lp_coeff[lpc_order-1],
 
3529
                                                                const unsigned guess_lpc_order =
 
3530
                                                                        FLAC__lpc_compute_best_order(
 
3531
                                                                                lpc_error,
 
3532
                                                                                max_lpc_order,
2328
3533
                                                                                frame_header->blocksize,
2329
 
                                                                                subframe_bps,
2330
 
                                                                                lpc_order,
2331
 
                                                                                qlp_coeff_precision,
2332
 
                                                                                rice_parameter,
2333
 
                                                                                min_partition_order,
2334
 
                                                                                max_partition_order,
2335
 
                                                                                precompute_partition_sums,
2336
 
                                                                                encoder->protected_->do_escape_coding,
2337
 
                                                                                encoder->protected_->rice_parameter_search_dist,
2338
 
                                                                                subframe[!_best_subframe],
2339
 
                                                                                partitioned_rice_contents[!_best_subframe]
 
3534
                                                                                subframe_bps + (
 
3535
                                                                                        encoder->protected_->do_qlp_coeff_prec_search?
 
3536
                                                                                                FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
 
3537
                                                                                                encoder->protected_->qlp_coeff_precision
 
3538
                                                                                )
2340
3539
                                                                        );
2341
 
                                                                if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
2342
 
                                                                        if(_candidate_bits < _best_bits) {
2343
 
                                                                                _best_subframe = !_best_subframe;
2344
 
                                                                                _best_bits = _candidate_bits;
 
3540
                                                                min_lpc_order = max_lpc_order = guess_lpc_order;
 
3541
                                                        }
 
3542
                                                        if(max_lpc_order >= frame_header->blocksize)
 
3543
                                                                max_lpc_order = frame_header->blocksize - 1;
 
3544
                                                        for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
 
3545
                                                                lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
 
3546
                                                                if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
 
3547
                                                                        continue; /* don't even try */
 
3548
                                                                rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
 
3549
                                                                rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
 
3550
                                                                if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
 
3551
#ifdef DEBUG_VERBOSE
 
3552
                                                                        fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
 
3553
#endif
 
3554
                                                                        rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
 
3555
                                                                }
 
3556
                                                                if(encoder->protected_->do_qlp_coeff_prec_search) {
 
3557
                                                                        min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
 
3558
                                                                        /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
 
3559
                                                                        if(subframe_bps <= 17) {
 
3560
                                                                                max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
 
3561
                                                                                max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
 
3562
                                                                        }
 
3563
                                                                        else
 
3564
                                                                                max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
 
3565
                                                                }
 
3566
                                                                else {
 
3567
                                                                        min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
 
3568
                                                                }
 
3569
                                                                for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
 
3570
                                                                        _candidate_bits =
 
3571
                                                                                evaluate_lpc_subframe_(
 
3572
                                                                                        encoder,
 
3573
                                                                                        integer_signal,
 
3574
                                                                                        residual[!_best_subframe],
 
3575
                                                                                        encoder->private_->abs_residual_partition_sums,
 
3576
                                                                                        encoder->private_->raw_bits_per_partition,
 
3577
                                                                                        encoder->private_->lp_coeff[lpc_order-1],
 
3578
                                                                                        frame_header->blocksize,
 
3579
                                                                                        subframe_bps,
 
3580
                                                                                        lpc_order,
 
3581
                                                                                        qlp_coeff_precision,
 
3582
                                                                                        rice_parameter,
 
3583
                                                                                        min_partition_order,
 
3584
                                                                                        max_partition_order,
 
3585
                                                                                        encoder->protected_->do_escape_coding,
 
3586
                                                                                        encoder->protected_->rice_parameter_search_dist,
 
3587
                                                                                        subframe[!_best_subframe],
 
3588
                                                                                        partitioned_rice_contents[!_best_subframe]
 
3589
                                                                                );
 
3590
                                                                        if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
 
3591
                                                                                if(_candidate_bits < _best_bits) {
 
3592
                                                                                        _best_subframe = !_best_subframe;
 
3593
                                                                                        _best_bits = _candidate_bits;
 
3594
                                                                                }
2345
3595
                                                                        }
2346
3596
                                                                }
2347
3597
                                                        }
2356
3606
        /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
2357
3607
        if(_best_bits == UINT_MAX) {
2358
3608
                FLAC__ASSERT(_best_subframe == 0);
2359
 
                _best_bits = evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
 
3609
                _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
2360
3610
        }
2361
3611
 
2362
3612
        *best_subframe = _best_subframe;
2367
3617
 
2368
3618
FLAC__bool add_subframe_(
2369
3619
        FLAC__StreamEncoder *encoder,
2370
 
        const FLAC__FrameHeader *frame_header,
 
3620
        unsigned blocksize,
2371
3621
        unsigned subframe_bps,
2372
3622
        const FLAC__Subframe *subframe,
2373
 
        FLAC__BitBuffer *frame
 
3623
        FLAC__BitWriter *frame
2374
3624
)
2375
3625
{
2376
3626
        switch(subframe->type) {
2377
3627
                case FLAC__SUBFRAME_TYPE_CONSTANT:
2378
3628
                        if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
2379
 
                                encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
 
3629
                                encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2380
3630
                                return false;
2381
3631
                        }
2382
3632
                        break;
2383
3633
                case FLAC__SUBFRAME_TYPE_FIXED:
2384
 
                        if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), frame_header->blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
2385
 
                                encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
 
3634
                        if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
 
3635
                                encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2386
3636
                                return false;
2387
3637
                        }
2388
3638
                        break;
2389
3639
                case FLAC__SUBFRAME_TYPE_LPC:
2390
 
                        if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), frame_header->blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
2391
 
                                encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
 
3640
                        if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
 
3641
                                encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2392
3642
                                return false;
2393
3643
                        }
2394
3644
                        break;
2395
3645
                case FLAC__SUBFRAME_TYPE_VERBATIM:
2396
 
                        if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), frame_header->blocksize, subframe_bps, subframe->wasted_bits, frame)) {
2397
 
                                encoder->protected_->state = FLAC__STREAM_ENCODER_FATAL_ERROR_WHILE_ENCODING;
 
3646
                        if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
 
3647
                                encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
2398
3648
                                return false;
2399
3649
                        }
2400
3650
                        break;
2405
3655
        return true;
2406
3656
}
2407
3657
 
 
3658
#define SPOTCHECK_ESTIMATE 0
 
3659
#if SPOTCHECK_ESTIMATE
 
3660
static void spotcheck_subframe_estimate_(
 
3661
        FLAC__StreamEncoder *encoder,
 
3662
        unsigned blocksize,
 
3663
        unsigned subframe_bps,
 
3664
        const FLAC__Subframe *subframe,
 
3665
        unsigned estimate
 
3666
)
 
3667
{
 
3668
        FLAC__bool ret;
 
3669
        FLAC__BitWriter *frame = FLAC__bitwriter_new();
 
3670
        if(frame == 0) {
 
3671
                fprintf(stderr, "EST: can't allocate frame\n");
 
3672
                return;
 
3673
        }
 
3674
        if(!FLAC__bitwriter_init(frame)) {
 
3675
                fprintf(stderr, "EST: can't init frame\n");
 
3676
                return;
 
3677
        }
 
3678
        ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
 
3679
        FLAC__ASSERT(ret);
 
3680
        {
 
3681
                const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
 
3682
                if(estimate != actual)
 
3683
                        fprintf(stderr, "EST: bad, frame#%u sub#%%d type=%8s est=%u, actual=%u, delta=%d\n", encoder->private_->current_frame_number, FLAC__SubframeTypeString[subframe->type], estimate, actual, (int)actual-(int)estimate);
 
3684
        }
 
3685
        FLAC__bitwriter_delete(frame);
 
3686
}
 
3687
#endif
 
3688
 
2408
3689
unsigned evaluate_constant_subframe_(
 
3690
        FLAC__StreamEncoder *encoder,
2409
3691
        const FLAC__int32 signal,
 
3692
        unsigned blocksize,
2410
3693
        unsigned subframe_bps,
2411
3694
        FLAC__Subframe *subframe
2412
3695
)
2413
3696
{
 
3697
        unsigned estimate;
2414
3698
        subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
2415
3699
        subframe->data.constant.value = signal;
2416
3700
 
2417
 
        return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe_bps;
 
3701
        estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
 
3702
 
 
3703
#if SPOTCHECK_ESTIMATE
 
3704
        spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
 
3705
#else
 
3706
        (void)encoder, (void)blocksize;
 
3707
#endif
 
3708
 
 
3709
        return estimate;
2418
3710
}
2419
3711
 
2420
3712
unsigned evaluate_fixed_subframe_(
2421
3713
        FLAC__StreamEncoder *encoder,
2422
3714
        const FLAC__int32 signal[],
2423
3715
        FLAC__int32 residual[],
2424
 
        FLAC__uint32 abs_residual[],
2425
3716
        FLAC__uint64 abs_residual_partition_sums[],
2426
3717
        unsigned raw_bits_per_partition[],
2427
3718
        unsigned blocksize,
2430
3721
        unsigned rice_parameter,
2431
3722
        unsigned min_partition_order,
2432
3723
        unsigned max_partition_order,
2433
 
        FLAC__bool precompute_partition_sums,
2434
3724
        FLAC__bool do_escape_coding,
2435
3725
        unsigned rice_parameter_search_dist,
2436
3726
        FLAC__Subframe *subframe,
2437
3727
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
2438
3728
)
2439
3729
{
2440
 
        unsigned i, residual_bits;
 
3730
        unsigned i, residual_bits, estimate;
2441
3731
        const unsigned residual_samples = blocksize - order;
2442
3732
 
2443
3733
        FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
2452
3742
                find_best_partition_order_(
2453
3743
                        encoder->private_,
2454
3744
                        residual,
2455
 
                        abs_residual,
2456
3745
                        abs_residual_partition_sums,
2457
3746
                        raw_bits_per_partition,
2458
3747
                        residual_samples,
2460
3749
                        rice_parameter,
2461
3750
                        min_partition_order,
2462
3751
                        max_partition_order,
2463
 
                        precompute_partition_sums,
2464
3752
                        do_escape_coding,
2465
3753
                        rice_parameter_search_dist,
2466
3754
                        &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
2470
3758
        for(i = 0; i < order; i++)
2471
3759
                subframe->data.fixed.warmup[i] = signal[i];
2472
3760
 
2473
 
        return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (order * subframe_bps) + residual_bits;
 
3761
        estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
 
3762
 
 
3763
#if SPOTCHECK_ESTIMATE
 
3764
        spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
 
3765
#endif
 
3766
 
 
3767
        return estimate;
2474
3768
}
2475
3769
 
2476
3770
#ifndef FLAC__INTEGER_ONLY_LIBRARY
2478
3772
        FLAC__StreamEncoder *encoder,
2479
3773
        const FLAC__int32 signal[],
2480
3774
        FLAC__int32 residual[],
2481
 
        FLAC__uint32 abs_residual[],
2482
3775
        FLAC__uint64 abs_residual_partition_sums[],
2483
3776
        unsigned raw_bits_per_partition[],
2484
3777
        const FLAC__real lp_coeff[],
2489
3782
        unsigned rice_parameter,
2490
3783
        unsigned min_partition_order,
2491
3784
        unsigned max_partition_order,
2492
 
        FLAC__bool precompute_partition_sums,
2493
3785
        FLAC__bool do_escape_coding,
2494
3786
        unsigned rice_parameter_search_dist,
2495
3787
        FLAC__Subframe *subframe,
2497
3789
)
2498
3790
{
2499
3791
        FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
2500
 
        unsigned i, residual_bits;
 
3792
        unsigned i, residual_bits, estimate;
2501
3793
        int quantization, ret;
2502
3794
        const unsigned residual_samples = blocksize - order;
2503
3795
 
2530
3822
                find_best_partition_order_(
2531
3823
                        encoder->private_,
2532
3824
                        residual,
2533
 
                        abs_residual,
2534
3825
                        abs_residual_partition_sums,
2535
3826
                        raw_bits_per_partition,
2536
3827
                        residual_samples,
2538
3829
                        rice_parameter,
2539
3830
                        min_partition_order,
2540
3831
                        max_partition_order,
2541
 
                        precompute_partition_sums,
2542
3832
                        do_escape_coding,
2543
3833
                        rice_parameter_search_dist,
2544
 
                        &subframe->data.fixed.entropy_coding_method.data.partitioned_rice
 
3834
                        &subframe->data.lpc.entropy_coding_method.data.partitioned_rice
2545
3835
                );
2546
3836
 
2547
3837
        subframe->data.lpc.order = order;
2551
3841
        for(i = 0; i < order; i++)
2552
3842
                subframe->data.lpc.warmup[i] = signal[i];
2553
3843
 
2554
 
        return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
 
3844
        estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
 
3845
 
 
3846
#if SPOTCHECK_ESTIMATE
 
3847
        spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
 
3848
#endif
 
3849
 
 
3850
        return estimate;
2555
3851
}
2556
3852
#endif
2557
3853
 
2558
3854
unsigned evaluate_verbatim_subframe_(
 
3855
        FLAC__StreamEncoder *encoder,
2559
3856
        const FLAC__int32 signal[],
2560
3857
        unsigned blocksize,
2561
3858
        unsigned subframe_bps,
2562
3859
        FLAC__Subframe *subframe
2563
3860
)
2564
3861
{
 
3862
        unsigned estimate;
 
3863
 
2565
3864
        subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
2566
3865
 
2567
3866
        subframe->data.verbatim.data = signal;
2568
3867
 
2569
 
        return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (blocksize * subframe_bps);
 
3868
        estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
 
3869
 
 
3870
#if SPOTCHECK_ESTIMATE
 
3871
        spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
 
3872
#else
 
3873
        (void)encoder;
 
3874
#endif
 
3875
 
 
3876
        return estimate;
2570
3877
}
2571
3878
 
2572
3879
unsigned find_best_partition_order_(
2573
3880
        FLAC__StreamEncoderPrivate *private_,
2574
3881
        const FLAC__int32 residual[],
2575
 
        FLAC__uint32 abs_residual[],
2576
3882
        FLAC__uint64 abs_residual_partition_sums[],
2577
3883
        unsigned raw_bits_per_partition[],
2578
3884
        unsigned residual_samples,
2580
3886
        unsigned rice_parameter,
2581
3887
        unsigned min_partition_order,
2582
3888
        unsigned max_partition_order,
2583
 
        FLAC__bool precompute_partition_sums,
2584
3889
        FLAC__bool do_escape_coding,
2585
3890
        unsigned rice_parameter_search_dist,
2586
3891
        FLAC__EntropyCodingMethod_PartitionedRice *best_partitioned_rice
2587
3892
)
2588
3893
{
2589
 
        FLAC__int32 r;
2590
3894
        unsigned residual_bits, best_residual_bits = 0;
2591
 
        unsigned residual_sample;
2592
3895
        unsigned best_parameters_index = 0;
2593
3896
        const unsigned blocksize = residual_samples + predictor_order;
2594
3897
 
2595
 
        /* compute abs(residual) for use later */
2596
 
        for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
2597
 
                r = residual[residual_sample];
2598
 
                abs_residual[residual_sample] = (FLAC__uint32)(r<0? -r : r);
2599
 
        }
2600
 
 
2601
3898
        max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
2602
3899
        min_partition_order = min(min_partition_order, max_partition_order);
2603
3900
 
2604
 
        if(precompute_partition_sums) {
 
3901
        precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
 
3902
 
 
3903
        if(do_escape_coding)
 
3904
                precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
 
3905
 
 
3906
        {
2605
3907
                int partition_order;
2606
3908
                unsigned sum;
2607
3909
 
2608
 
                precompute_partition_info_sums_(abs_residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order);
2609
 
 
2610
 
                if(do_escape_coding)
2611
 
                        precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
2612
 
 
2613
3910
                for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
2614
 
#ifdef DONT_ESTIMATE_RICE_BITS
2615
3911
                        if(!
2616
 
                                set_partitioned_rice_with_precompute_(
 
3912
                                set_partitioned_rice_(
 
3913
#ifdef EXACT_RICE_BITS_CALCULATION
2617
3914
                                        residual,
2618
 
                                        abs_residual_partition_sums+sum,
2619
 
                                        raw_bits_per_partition+sum,
2620
 
                                        residual_samples,
2621
 
                                        predictor_order,
2622
 
                                        rice_parameter,
2623
 
                                        rice_parameter_search_dist,
2624
 
                                        (unsigned)partition_order,
2625
 
                                        do_escape_coding,
2626
 
                                        &private_->partitioned_rice_contents_extra[!best_parameters_index],
2627
 
                                        &residual_bits
2628
 
                                )
2629
 
                        )
2630
 
#else
2631
 
                        if(!
2632
 
                                set_partitioned_rice_with_precompute_(
2633
 
                                        abs_residual,
2634
 
                                        abs_residual_partition_sums+sum,
2635
 
                                        raw_bits_per_partition+sum,
2636
 
                                        residual_samples,
2637
 
                                        predictor_order,
2638
 
                                        rice_parameter,
2639
 
                                        rice_parameter_search_dist,
2640
 
                                        (unsigned)partition_order,
2641
 
                                        do_escape_coding,
2642
 
                                        &private_->partitioned_rice_contents_extra[!best_parameters_index],
2643
 
                                        &residual_bits
2644
 
                                )
2645
 
                        )
2646
3915
#endif
 
3916
                                        abs_residual_partition_sums+sum,
 
3917
                                        raw_bits_per_partition+sum,
 
3918
                                        residual_samples,
 
3919
                                        predictor_order,
 
3920
                                        rice_parameter,
 
3921
                                        rice_parameter_search_dist,
 
3922
                                        (unsigned)partition_order,
 
3923
                                        do_escape_coding,
 
3924
                                        &private_->partitioned_rice_contents_extra[!best_parameters_index],
 
3925
                                        &residual_bits
 
3926
                                )
 
3927
                        )
2647
3928
                        {
2648
3929
                                FLAC__ASSERT(best_residual_bits != 0);
2649
3930
                                break;
2656
3937
                        }
2657
3938
                }
2658
3939
        }
2659
 
        else {
2660
 
                unsigned partition_order;
2661
 
                for(partition_order = min_partition_order; partition_order <= max_partition_order; partition_order++) {
2662
 
#ifdef DONT_ESTIMATE_RICE_BITS
2663
 
                        if(!
2664
 
                                set_partitioned_rice_(
2665
 
                                        abs_residual,
2666
 
                                        residual,
2667
 
                                        residual_samples,
2668
 
                                        predictor_order,
2669
 
                                        rice_parameter,
2670
 
                                        rice_parameter_search_dist,
2671
 
                                        partition_order,
2672
 
                                        &private_->partitioned_rice_contents_extra[!best_parameters_index],
2673
 
                                        &residual_bits
2674
 
                                )
2675
 
                        )
2676
 
#else
2677
 
                        if(!
2678
 
                                set_partitioned_rice_(
2679
 
                                        abs_residual,
2680
 
                                        residual_samples,
2681
 
                                        predictor_order,
2682
 
                                        rice_parameter,
2683
 
                                        rice_parameter_search_dist,
2684
 
                                        partition_order,
2685
 
                                        &private_->partitioned_rice_contents_extra[!best_parameters_index],
2686
 
                                        &residual_bits
2687
 
                                )
2688
 
                        )
2689
 
#endif
2690
 
                        {
2691
 
                                FLAC__ASSERT(best_residual_bits != 0);
2692
 
                                break;
2693
 
                        }
2694
 
                        if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
2695
 
                                best_residual_bits = residual_bits;
2696
 
                                best_parameters_index = !best_parameters_index;
2697
 
                                best_partitioned_rice->order = partition_order;
2698
 
                        }
2699
 
                }
2700
 
        }
2701
3940
 
2702
3941
        /*
2703
3942
         * We are allowed to de-const the pointer based on our special knowledge;
2714
3953
}
2715
3954
 
2716
3955
void precompute_partition_info_sums_(
2717
 
        const FLAC__uint32 abs_residual[],
 
3956
        const FLAC__int32 residual[],
2718
3957
        FLAC__uint64 abs_residual_partition_sums[],
2719
3958
        unsigned residual_samples,
2720
3959
        unsigned predictor_order,
2728
3967
 
2729
3968
        /* first do max_partition_order */
2730
3969
        for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
2731
 
                FLAC__uint64 abs_residual_partition_sum;
2732
 
                FLAC__uint32 abs_r;
 
3970
                FLAC__uint64 abs_residual_partition_sum; /* OPT: can reasonably be FLAC__uint32 for bps <= 17 and maybe higher */
2733
3971
                unsigned partition, partition_sample, partition_samples, residual_sample;
2734
3972
                const unsigned partitions = 1u << partition_order;
2735
3973
                const unsigned default_partition_samples = blocksize >> partition_order;
2741
3979
                        if(partition == 0)
2742
3980
                                partition_samples -= predictor_order;
2743
3981
                        abs_residual_partition_sum = 0;
2744
 
                        for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
2745
 
                                abs_r = abs_residual[residual_sample];
2746
 
                                abs_residual_partition_sum += abs_r;
2747
 
                                residual_sample++;
 
3982
                        for(partition_sample = 0; partition_sample < partition_samples; partition_sample++, residual_sample++) {
 
3983
#if defined _MSC_VER && _MSC_VER <= 1200
 
3984
                                /* OPT: abs() may be faster for some compilers */
 
3985
                                abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
 
3986
#else
 
3987
                                const FLAC__int32 r = residual[residual_sample];
 
3988
                                if(r < 0)
 
3989
                                        abs_residual_partition_sum -= r;
 
3990
                                else
 
3991
                                        abs_residual_partition_sum += r;
 
3992
#endif
2748
3993
                        }
2749
3994
                        abs_residual_partition_sums[partition] = abs_residual_partition_sum;
2750
3995
                }
2782
4027
 
2783
4028
        /* first do max_partition_order */
2784
4029
        for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
2785
 
                FLAC__int32 r, residual_partition_min, residual_partition_max;
2786
 
                unsigned silog2_min, silog2_max;
 
4030
                FLAC__int32 r;
 
4031
                FLAC__uint32 rmax;
2787
4032
                unsigned partition, partition_sample, partition_samples, residual_sample;
2788
4033
                const unsigned partitions = 1u << partition_order;
2789
4034
                const unsigned default_partition_samples = blocksize >> partition_order;
2794
4039
                        partition_samples = default_partition_samples;
2795
4040
                        if(partition == 0)
2796
4041
                                partition_samples -= predictor_order;
2797
 
                        residual_partition_min = residual_partition_max = 0;
 
4042
                        rmax = 0;
2798
4043
                        for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
2799
 
                                r = residual[residual_sample];
2800
 
                                if(r < residual_partition_min)
2801
 
                                        residual_partition_min = r;
2802
 
                                else if(r > residual_partition_max)
2803
 
                                        residual_partition_max = r;
2804
 
                                residual_sample++;
 
4044
                                r = residual[residual_sample++];
 
4045
                                if(r < 0)
 
4046
                                        rmax |= ~r;
 
4047
                                else
 
4048
                                        rmax |= r;
2805
4049
                        }
2806
 
                        silog2_min = FLAC__bitmath_silog2(residual_partition_min);
2807
 
                        silog2_max = FLAC__bitmath_silog2(residual_partition_max);
2808
 
                        raw_bits_per_partition[partition] = max(silog2_min, silog2_max);
 
4050
                        /* now we know all residual values are in the range [-rmax-1,rmax] */
 
4051
                        raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
2809
4052
                }
2810
4053
                to_partition = partitions;
2811
 
                break;
 
4054
                break; /*@@@ yuck, should remove the 'for' loop instead */
2812
4055
        }
2813
4056
 
2814
4057
        /* now merge partitions for lower orders */
2826
4069
        }
2827
4070
}
2828
4071
 
2829
 
#ifdef VARIABLE_RICE_BITS
2830
 
#undef VARIABLE_RICE_BITS
2831
 
#endif
2832
 
#ifndef DONT_ESTIMATE_RICE_BITS
2833
 
#define VARIABLE_RICE_BITS(value, parameter) ((value) >> (parameter))
2834
 
#endif
2835
 
 
2836
 
#ifdef DONT_ESTIMATE_RICE_BITS
2837
 
FLAC__bool set_partitioned_rice_(
2838
 
        const FLAC__uint32 abs_residual[],
2839
 
        const FLAC__int32 residual[],
2840
 
        const unsigned residual_samples,
2841
 
        const unsigned predictor_order,
2842
 
        const unsigned suggested_rice_parameter,
2843
 
        const unsigned rice_parameter_search_dist,
2844
 
        const unsigned partition_order,
2845
 
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
2846
 
        unsigned *bits
2847
 
)
2848
 
#else
2849
 
FLAC__bool set_partitioned_rice_(
2850
 
        const FLAC__uint32 abs_residual[],
2851
 
        const unsigned residual_samples,
2852
 
        const unsigned predictor_order,
2853
 
        const unsigned suggested_rice_parameter,
2854
 
        const unsigned rice_parameter_search_dist,
2855
 
        const unsigned partition_order,
2856
 
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
2857
 
        unsigned *bits
2858
 
)
2859
 
#endif
2860
 
{
2861
 
        unsigned rice_parameter, partition_bits;
2862
 
#ifndef NO_RICE_SEARCH
2863
 
        unsigned best_partition_bits;
2864
 
        unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
2865
 
#endif
2866
 
        unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
2867
 
        unsigned *parameters;
2868
 
 
2869
 
        FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
2870
 
 
2871
 
        FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
2872
 
        parameters = partitioned_rice_contents->parameters;
2873
 
 
2874
 
        if(partition_order == 0) {
2875
 
                unsigned i;
2876
 
 
2877
 
#ifndef NO_RICE_SEARCH
2878
 
                if(rice_parameter_search_dist) {
2879
 
                        if(suggested_rice_parameter < rice_parameter_search_dist)
2880
 
                                min_rice_parameter = 0;
2881
 
                        else
2882
 
                                min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
2883
 
                        max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
2884
 
                        if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2885
 
#ifdef DEBUG_VERBOSE
2886
 
                                fprintf(stderr, "clipping rice_parameter (%u -> %u) @2\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2887
 
#endif
2888
 
                                max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2889
 
                        }
2890
 
                }
2891
 
                else
2892
 
                        min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
2893
 
 
2894
 
                best_partition_bits = 0xffffffff;
2895
 
                for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
2896
 
#endif
2897
 
#ifdef VARIABLE_RICE_BITS
2898
 
#ifdef FLAC__SYMMETRIC_RICE
2899
 
                        partition_bits = (2+rice_parameter) * residual_samples;
2900
 
#else
2901
 
                        const unsigned rice_parameter_estimate = rice_parameter-1;
2902
 
                        partition_bits = (1+rice_parameter) * residual_samples;
2903
 
#endif
2904
 
#else
2905
 
                        partition_bits = 0;
2906
 
#endif
2907
 
                        partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
2908
 
                        for(i = 0; i < residual_samples; i++) {
2909
 
#ifdef VARIABLE_RICE_BITS
2910
 
#ifdef FLAC__SYMMETRIC_RICE
2911
 
                                partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter);
2912
 
#else
2913
 
                                partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
2914
 
#endif
2915
 
#else
2916
 
                                partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
2917
 
#endif
2918
 
                        }
2919
 
#ifndef NO_RICE_SEARCH
2920
 
                        if(partition_bits < best_partition_bits) {
2921
 
                                best_rice_parameter = rice_parameter;
2922
 
                                best_partition_bits = partition_bits;
2923
 
                        }
2924
 
                }
2925
 
#endif
2926
 
                parameters[0] = best_rice_parameter;
2927
 
                bits_ += best_partition_bits;
2928
 
        }
2929
 
        else {
2930
 
                unsigned partition, residual_sample, save_residual_sample, partition_sample;
2931
 
                unsigned partition_samples;
2932
 
                FLAC__uint64 mean, k;
2933
 
                const unsigned partitions = 1u << partition_order;
2934
 
                for(partition = residual_sample = 0; partition < partitions; partition++) {
2935
 
                        partition_samples = (residual_samples+predictor_order) >> partition_order;
2936
 
                        if(partition == 0) {
2937
 
                                if(partition_samples <= predictor_order)
2938
 
                                        return false;
2939
 
                                else
2940
 
                                        partition_samples -= predictor_order;
2941
 
                        }
2942
 
                        mean = 0;
2943
 
                        save_residual_sample = residual_sample;
2944
 
                        for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++)
2945
 
                                mean += abs_residual[residual_sample];
2946
 
                        residual_sample = save_residual_sample;
2947
 
#ifdef FLAC__SYMMETRIC_RICE
2948
 
                        mean += partition_samples >> 1; /* for rounding effect */
2949
 
                        mean /= partition_samples;
2950
 
 
2951
 
                        /* calc rice_parameter = floor(log2(mean)) */
2952
 
                        rice_parameter = 0;
2953
 
                        mean>>=1;
2954
 
                        while(mean) {
2955
 
                                rice_parameter++;
2956
 
                                mean >>= 1;
2957
 
                        }
2958
 
#else
2959
 
                        /* we are basically calculating the size in bits of the
2960
 
                         * average residual magnitude in the partition:
2961
 
                         *   rice_parameter = floor(log2(mean/partition_samples))
2962
 
                         * 'mean' is not a good name for the variable, it is
2963
 
                         * actually the sum of magnitudes of all residual values
2964
 
                         * in the partition, so the actual mean is
2965
 
                         * mean/partition_samples
2966
 
                         */
2967
 
                        for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
2968
 
                                ;
2969
 
#endif
2970
 
                        if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2971
 
#ifdef DEBUG_VERBOSE
2972
 
                                fprintf(stderr, "clipping rice_parameter (%u -> %u) @3\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2973
 
#endif
2974
 
                                rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2975
 
                        }
2976
 
 
2977
 
#ifndef NO_RICE_SEARCH
2978
 
                        if(rice_parameter_search_dist) {
2979
 
                                if(rice_parameter < rice_parameter_search_dist)
2980
 
                                        min_rice_parameter = 0;
2981
 
                                else
2982
 
                                        min_rice_parameter = rice_parameter - rice_parameter_search_dist;
2983
 
                                max_rice_parameter = rice_parameter + rice_parameter_search_dist;
2984
 
                                if(max_rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
2985
 
#ifdef DEBUG_VERBOSE
2986
 
                                        fprintf(stderr, "clipping rice_parameter (%u -> %u) @4\n", max_rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
2987
 
#endif
2988
 
                                        max_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
2989
 
                                }
2990
 
                        }
2991
 
                        else
2992
 
                                min_rice_parameter = max_rice_parameter = rice_parameter;
2993
 
 
2994
 
                        best_partition_bits = 0xffffffff;
2995
 
                        for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
2996
 
#endif
2997
 
#ifdef VARIABLE_RICE_BITS
2998
 
#ifdef FLAC__SYMMETRIC_RICE
2999
 
                                partition_bits = (2+rice_parameter) * partition_samples;
3000
 
#else
3001
 
                                const unsigned rice_parameter_estimate = rice_parameter-1;
3002
 
                                partition_bits = (1+rice_parameter) * partition_samples;
3003
 
#endif
3004
 
#else
3005
 
                                partition_bits = 0;
3006
 
#endif
3007
 
                                partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3008
 
                                save_residual_sample = residual_sample;
3009
 
                                for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
3010
 
#ifdef VARIABLE_RICE_BITS
3011
 
#ifdef FLAC__SYMMETRIC_RICE
3012
 
                                        partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter);
3013
 
#else
3014
 
                                        partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
3015
 
#endif
3016
 
#else
3017
 
                                        partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] in addition to abs_residual[] */
3018
 
#endif
3019
 
                                }
3020
 
#ifndef NO_RICE_SEARCH
3021
 
                                if(rice_parameter != max_rice_parameter)
3022
 
                                        residual_sample = save_residual_sample;
3023
 
                                if(partition_bits < best_partition_bits) {
3024
 
                                        best_rice_parameter = rice_parameter;
3025
 
                                        best_partition_bits = partition_bits;
3026
 
                                }
3027
 
                        }
3028
 
#endif
3029
 
                        parameters[partition] = best_rice_parameter;
3030
 
                        bits_ += best_partition_bits;
3031
 
                }
3032
 
        }
3033
 
 
3034
 
        *bits = bits_;
3035
 
        return true;
3036
 
}
3037
 
 
3038
 
#ifdef DONT_ESTIMATE_RICE_BITS
3039
 
FLAC__bool set_partitioned_rice_with_precompute_(
3040
 
        const FLAC__int32 residual[],
3041
 
        const FLAC__uint64 abs_residual_partition_sums[],
3042
 
        const unsigned raw_bits_per_partition[],
3043
 
        const unsigned residual_samples,
3044
 
        const unsigned predictor_order,
3045
 
        const unsigned suggested_rice_parameter,
3046
 
        const unsigned rice_parameter_search_dist,
3047
 
        const unsigned partition_order,
3048
 
        const FLAC__bool search_for_escapes,
3049
 
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3050
 
        unsigned *bits
3051
 
)
3052
 
#else
3053
 
FLAC__bool set_partitioned_rice_with_precompute_(
3054
 
        const FLAC__uint32 abs_residual[],
3055
 
        const FLAC__uint64 abs_residual_partition_sums[],
3056
 
        const unsigned raw_bits_per_partition[],
3057
 
        const unsigned residual_samples,
3058
 
        const unsigned predictor_order,
3059
 
        const unsigned suggested_rice_parameter,
3060
 
        const unsigned rice_parameter_search_dist,
3061
 
        const unsigned partition_order,
3062
 
        const FLAC__bool search_for_escapes,
3063
 
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3064
 
        unsigned *bits
3065
 
)
3066
 
#endif
3067
 
{
3068
 
        unsigned rice_parameter, partition_bits;
3069
 
#ifndef NO_RICE_SEARCH
3070
 
        unsigned best_partition_bits;
3071
 
        unsigned min_rice_parameter, max_rice_parameter, best_rice_parameter = 0;
3072
 
#endif
3073
 
        unsigned flat_bits;
 
4072
#ifdef EXACT_RICE_BITS_CALCULATION
 
4073
static __inline unsigned count_rice_bits_in_partition_(
 
4074
        const unsigned rice_parameter,
 
4075
        const unsigned partition_samples,
 
4076
        const FLAC__int32 *residual
 
4077
)
 
4078
{
 
4079
        unsigned i, partition_bits =
 
4080
                FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
 
4081
                (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
 
4082
        ;
 
4083
        for(i = 0; i < partition_samples; i++)
 
4084
                partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
 
4085
        return partition_bits;
 
4086
}
 
4087
#else
 
4088
static __inline unsigned count_rice_bits_in_partition_(
 
4089
        const unsigned rice_parameter,
 
4090
        const unsigned partition_samples,
 
4091
        const FLAC__uint64 abs_residual_partition_sum
 
4092
)
 
4093
{
 
4094
        return
 
4095
                FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN +
 
4096
                (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
 
4097
                (
 
4098
                        rice_parameter?
 
4099
                                (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
 
4100
                                : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
 
4101
                )
 
4102
                - (partition_samples >> 1)
 
4103
                /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
 
4104
                 * The actual number of bits used is closer to the sum for all i in the partition of  abs(residual[i])>>(rice_parameter-1)
 
4105
                 * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
 
4106
                 * So the subtraction term tries to guess how many extra bits were contributed.
 
4107
                 * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
 
4108
                 */
 
4109
        ;
 
4110
}
 
4111
#endif
 
4112
 
 
4113
FLAC__bool set_partitioned_rice_(
 
4114
#ifdef EXACT_RICE_BITS_CALCULATION
 
4115
        const FLAC__int32 residual[],
 
4116
#endif
 
4117
        const FLAC__uint64 abs_residual_partition_sums[],
 
4118
        const unsigned raw_bits_per_partition[],
 
4119
        const unsigned residual_samples,
 
4120
        const unsigned predictor_order,
 
4121
        const unsigned suggested_rice_parameter,
 
4122
        const unsigned rice_parameter_search_dist,
 
4123
        const unsigned partition_order,
 
4124
        const FLAC__bool search_for_escapes,
 
4125
        FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
 
4126
        unsigned *bits
 
4127
)
 
4128
{
 
4129
        unsigned rice_parameter, partition_bits;
 
4130
        unsigned best_partition_bits, best_rice_parameter = 0;
3074
4131
        unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3075
4132
        unsigned *parameters, *raw_bits;
 
4133
#ifdef ENABLE_RICE_PARAMETER_SEARCH
 
4134
        unsigned min_rice_parameter, max_rice_parameter;
 
4135
#else
 
4136
        (void)rice_parameter_search_dist;
 
4137
#endif
3076
4138
 
3077
4139
        FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER);
3078
4140
 
3081
4143
        raw_bits = partitioned_rice_contents->raw_bits;
3082
4144
 
3083
4145
        if(partition_order == 0) {
3084
 
                unsigned i;
3085
 
 
3086
 
#ifndef NO_RICE_SEARCH
 
4146
                best_partition_bits = 0xffffffff;
 
4147
#ifdef ENABLE_RICE_PARAMETER_SEARCH
3087
4148
                if(rice_parameter_search_dist) {
3088
4149
                        if(suggested_rice_parameter < rice_parameter_search_dist)
3089
4150
                                min_rice_parameter = 0;
3100
4161
                else
3101
4162
                        min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3102
4163
 
3103
 
                best_partition_bits = 0xffffffff;
3104
4164
                for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3105
 
#endif
3106
 
#ifdef VARIABLE_RICE_BITS
3107
 
#ifdef FLAC__SYMMETRIC_RICE
3108
 
                        partition_bits = (2+rice_parameter) * residual_samples;
3109
 
#else
3110
 
                        const unsigned rice_parameter_estimate = rice_parameter-1;
3111
 
                        partition_bits = (1+rice_parameter) * residual_samples;
3112
 
#endif
3113
 
#else
3114
 
                        partition_bits = 0;
3115
 
#endif
3116
 
                        partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3117
 
                        for(i = 0; i < residual_samples; i++) {
3118
 
#ifdef VARIABLE_RICE_BITS
3119
 
#ifdef FLAC__SYMMETRIC_RICE
3120
 
                                partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter);
3121
 
#else
3122
 
                                partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
3123
 
#endif
3124
 
#else
3125
 
                                partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
3126
 
#endif
3127
 
                        }
3128
 
#ifndef NO_RICE_SEARCH
 
4165
#else
 
4166
                        rice_parameter = suggested_rice_parameter;
 
4167
#endif
 
4168
#ifdef EXACT_RICE_BITS_CALCULATION
 
4169
                        partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
 
4170
#else
 
4171
                        partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
 
4172
#endif
3129
4173
                        if(partition_bits < best_partition_bits) {
3130
4174
                                best_rice_parameter = rice_parameter;
3131
4175
                                best_partition_bits = partition_bits;
3132
4176
                        }
 
4177
#ifdef ENABLE_RICE_PARAMETER_SEARCH
3133
4178
                }
3134
4179
#endif
3135
4180
                if(search_for_escapes) {
3136
 
                        flat_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
3137
 
                        if(flat_bits <= best_partition_bits) {
 
4181
                        partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[0] * residual_samples;
 
4182
                        if(partition_bits <= best_partition_bits) {
3138
4183
                                raw_bits[0] = raw_bits_per_partition[0];
3139
4184
                                best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3140
 
                                best_partition_bits = flat_bits;
 
4185
                                best_partition_bits = partition_bits;
3141
4186
                        }
3142
4187
                }
3143
4188
                parameters[0] = best_rice_parameter;
3144
4189
                bits_ += best_partition_bits;
3145
4190
        }
3146
4191
        else {
3147
 
                unsigned partition, residual_sample, save_residual_sample, partition_sample;
 
4192
                unsigned partition, residual_sample;
3148
4193
                unsigned partition_samples;
3149
4194
                FLAC__uint64 mean, k;
3150
4195
                const unsigned partitions = 1u << partition_order;
3157
4202
                                        partition_samples -= predictor_order;
3158
4203
                        }
3159
4204
                        mean = abs_residual_partition_sums[partition];
3160
 
#ifdef FLAC__SYMMETRIC_RICE
3161
 
                        mean += partition_samples >> 1; /* for rounding effect */
3162
 
                        mean /= partition_samples;
3163
 
 
3164
 
                        /* calc rice_parameter = floor(log2(mean)) */
3165
 
                        rice_parameter = 0;
3166
 
                        mean>>=1;
3167
 
                        while(mean) {
3168
 
                                rice_parameter++;
3169
 
                                mean >>= 1;
3170
 
                        }
3171
 
#else
3172
4205
                        /* we are basically calculating the size in bits of the
3173
4206
                         * average residual magnitude in the partition:
3174
4207
                         *   rice_parameter = floor(log2(mean/partition_samples))
3179
4212
                         */
3180
4213
                        for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
3181
4214
                                ;
3182
 
#endif
3183
4215
                        if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3184
4216
#ifdef DEBUG_VERBOSE
3185
4217
                                fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1);
3187
4219
                                rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
3188
4220
                        }
3189
4221
 
3190
 
#ifndef NO_RICE_SEARCH
 
4222
                        best_partition_bits = 0xffffffff;
 
4223
#ifdef ENABLE_RICE_PARAMETER_SEARCH
3191
4224
                        if(rice_parameter_search_dist) {
3192
4225
                                if(rice_parameter < rice_parameter_search_dist)
3193
4226
                                        min_rice_parameter = 0;
3204
4237
                        else
3205
4238
                                min_rice_parameter = max_rice_parameter = rice_parameter;
3206
4239
 
3207
 
                        best_partition_bits = 0xffffffff;
3208
4240
                        for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3209
4241
#endif
3210
 
#ifdef VARIABLE_RICE_BITS
3211
 
#ifdef FLAC__SYMMETRIC_RICE
3212
 
                                partition_bits = (2+rice_parameter) * partition_samples;
3213
 
#else
3214
 
                                const unsigned rice_parameter_estimate = rice_parameter-1;
3215
 
                                partition_bits = (1+rice_parameter) * partition_samples;
3216
 
#endif
3217
 
#else
3218
 
                                partition_bits = 0;
3219
 
#endif
3220
 
                                partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
3221
 
                                save_residual_sample = residual_sample;
3222
 
                                for(partition_sample = 0; partition_sample < partition_samples; residual_sample++, partition_sample++) {
3223
 
#ifdef VARIABLE_RICE_BITS
3224
 
#ifdef FLAC__SYMMETRIC_RICE
3225
 
                                        partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter);
3226
 
#else
3227
 
                                        partition_bits += VARIABLE_RICE_BITS(abs_residual[residual_sample], rice_parameter_estimate);
3228
 
#endif
3229
 
#else
3230
 
                                        partition_bits += FLAC__bitbuffer_rice_bits(residual[residual_sample], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
3231
 
#endif
3232
 
                                }
3233
 
#ifndef NO_RICE_SEARCH
3234
 
                                if(rice_parameter != max_rice_parameter)
3235
 
                                        residual_sample = save_residual_sample;
 
4242
#ifdef EXACT_RICE_BITS_CALCULATION
 
4243
                                partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
 
4244
#else
 
4245
                                partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
 
4246
#endif
3236
4247
                                if(partition_bits < best_partition_bits) {
3237
4248
                                        best_rice_parameter = rice_parameter;
3238
4249
                                        best_partition_bits = partition_bits;
3239
4250
                                }
 
4251
#ifdef ENABLE_RICE_PARAMETER_SEARCH
3240
4252
                        }
3241
4253
#endif
3242
4254
                        if(search_for_escapes) {
3243
 
                                flat_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
3244
 
                                if(flat_bits <= best_partition_bits) {
 
4255
                                partition_bits = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN + raw_bits_per_partition[partition] * partition_samples;
 
4256
                                if(partition_bits <= best_partition_bits) {
3245
4257
                                        raw_bits[partition] = raw_bits_per_partition[partition];
3246
4258
                                        best_rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
3247
 
                                        best_partition_bits = flat_bits;
 
4259
                                        best_partition_bits = partition_bits;
3248
4260
                                }
3249
4261
                        }
3250
4262
                        parameters[partition] = best_rice_parameter;
3251
4263
                        bits_ += best_partition_bits;
 
4264
                        residual_sample += partition_samples;
3252
4265
                }
3253
4266
        }
3254
4267
 
3309
4322
        FLAC__ASSERT(fifo->tail <= fifo->size);
3310
4323
}
3311
4324
 
3312
 
FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
 
4325
FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
3313
4326
{
3314
4327
        FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
3315
 
        const unsigned encoded_bytes = encoder->private_->verify.output.bytes;
 
4328
        const size_t encoded_bytes = encoder->private_->verify.output.bytes;
3316
4329
        (void)decoder;
3317
4330
 
3318
4331
        if(encoder->private_->verify.needs_magic_hack) {
3344
4357
{
3345
4358
        FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
3346
4359
        unsigned channel;
3347
 
        const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
 
4360
        const unsigned channels = frame->header.channels;
3348
4361
        const unsigned blocksize = frame->header.blocksize;
3349
4362
        const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
3350
4363
 
 
4364
        (void)decoder;
 
4365
 
3351
4366
        for(channel = 0; channel < channels; channel++) {
3352
4367
                if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
3353
4368
                        unsigned i, sample = 0;
3374
4389
                }
3375
4390
        }
3376
4391
        /* dequeue the frame from the fifo */
3377
 
        for(channel = 0; channel < channels; channel++) {
3378
 
                memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail - blocksize);
3379
 
        }
3380
4392
        encoder->private_->verify.input_fifo.tail -= blocksize;
 
4393
        FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
 
4394
        for(channel = 0; channel < channels; channel++)
 
4395
                memmove(&encoder->private_->verify.input_fifo.data[channel][0], &encoder->private_->verify.input_fifo.data[channel][blocksize], encoder->private_->verify.input_fifo.tail * sizeof(encoder->private_->verify.input_fifo.data[0][0]));
3381
4396
        return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
3382
4397
}
3383
4398
 
3392
4407
        (void)decoder, (void)status;
3393
4408
        encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
3394
4409
}
 
4410
 
 
4411
FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
 
4412
{
 
4413
        (void)client_data;
 
4414
 
 
4415
        *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
 
4416
        if (*bytes == 0) {
 
4417
                if (feof(encoder->private_->file))
 
4418
                        return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
 
4419
                else if (ferror(encoder->private_->file))
 
4420
                        return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
 
4421
        }
 
4422
        return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
 
4423
}
 
4424
 
 
4425
FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
 
4426
{
 
4427
        (void)client_data;
 
4428
 
 
4429
        if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
 
4430
                return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
 
4431
        else
 
4432
                return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
 
4433
}
 
4434
 
 
4435
FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
 
4436
{
 
4437
        off_t offset;
 
4438
 
 
4439
        (void)client_data;
 
4440
 
 
4441
        offset = ftello(encoder->private_->file);
 
4442
 
 
4443
        if(offset < 0) {
 
4444
                return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
 
4445
        }
 
4446
        else {
 
4447
                *absolute_byte_offset = (FLAC__uint64)offset;
 
4448
                return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
 
4449
        }
 
4450
}
 
4451
 
 
4452
#ifdef FLAC__VALGRIND_TESTING
 
4453
static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
 
4454
{
 
4455
        size_t ret = fwrite(ptr, size, nmemb, stream);
 
4456
        if(!ferror(stream))
 
4457
                fflush(stream);
 
4458
        return ret;
 
4459
}
 
4460
#else
 
4461
#define local__fwrite fwrite
 
4462
#endif
 
4463
 
 
4464
FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
 
4465
{
 
4466
        (void)client_data, (void)current_frame;
 
4467
 
 
4468
        if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
 
4469
                FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
 
4470
#if FLAC__HAS_OGG
 
4471
                        /* We would like to be able to use 'samples > 0' in the
 
4472
                         * clause here but currently because of the nature of our
 
4473
                         * Ogg writing implementation, 'samples' is always 0 (see
 
4474
                         * ogg_encoder_aspect.c).  The downside is extra progress
 
4475
                         * callbacks.
 
4476
                         */
 
4477
                        encoder->private_->is_ogg? true :
 
4478
#endif
 
4479
                        samples > 0
 
4480
                );
 
4481
                if(call_it) {
 
4482
                        /* NOTE: We have to add +bytes, +samples, and +1 to the stats
 
4483
                         * because at this point in the callback chain, the stats
 
4484
                         * have not been updated.  Only after we return and control
 
4485
                         * gets back to write_frame_() are the stats updated
 
4486
                         */
 
4487
                        encoder->private_->progress_callback(encoder, encoder->private_->bytes_written+bytes, encoder->private_->samples_written+samples, encoder->private_->frames_written+(samples?1:0), encoder->private_->total_frames_estimate, encoder->private_->client_data);
 
4488
                }
 
4489
                return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
 
4490
        }
 
4491
        else
 
4492
                return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
 
4493
}
 
4494
 
 
4495
/*
 
4496
 * This will forcibly set stdout to binary mode (for OSes that require it)
 
4497
 */
 
4498
FILE *get_binary_stdout_(void)
 
4499
{
 
4500
        /* if something breaks here it is probably due to the presence or
 
4501
         * absence of an underscore before the identifiers 'setmode',
 
4502
         * 'fileno', and/or 'O_BINARY'; check your system header files.
 
4503
         */
 
4504
#if defined _MSC_VER || defined __MINGW32__
 
4505
        _setmode(_fileno(stdout), _O_BINARY);
 
4506
#elif defined __CYGWIN__
 
4507
        /* almost certainly not needed for any modern Cygwin, but let's be safe... */
 
4508
        setmode(_fileno(stdout), _O_BINARY);
 
4509
#elif defined __EMX__
 
4510
        setmode(fileno(stdout), O_BINARY);
 
4511
#endif
 
4512
 
 
4513
        return stdout;
 
4514
}