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