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