blob: e12d556bd619f61d2f704e1b7078345a420afad0 [file] [log] [blame]
Josh Coalson26560dd2001-02-08 00:38:41 +00001/* libFLAC - Free Lossless Audio Codec library
Josh Coalson70118f62001-01-16 20:17:53 +00002 * Copyright (C) 2000,2001 Josh Coalson
Josh Coalsonbb7f6b92000-12-10 04:09:52 +00003 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
13 *
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 */
19
20#include <assert.h>
21#include <stdio.h>
22#include <stdlib.h> /* for malloc() */
23#include <string.h> /* for memcpy() */
24#include "FLAC/encoder.h"
Josh Coalson0a72e182001-04-13 19:17:16 +000025#include "FLAC/seek_table.h"
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000026#include "private/bitbuffer.h"
Josh Coalsoneef56702001-03-30 00:45:22 +000027#include "private/bitmath.h"
Josh Coalson215af572001-03-27 01:15:58 +000028#include "private/crc.h"
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000029#include "private/encoder_framing.h"
30#include "private/fixed.h"
31#include "private/lpc.h"
Josh Coalsonfa37f1c2001-01-12 23:55:11 +000032#include "private/md5.h"
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000033
34#ifdef min
35#undef min
36#endif
37#define min(x,y) ((x)<(y)?(x):(y))
38
39#ifdef max
40#undef max
41#endif
42#define max(x,y) ((x)>(y)?(x):(y))
43
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000044typedef struct FLAC__EncoderPrivate {
45 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
46 int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
47 int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
48 real *real_signal[FLAC__MAX_CHANNELS]; /* the floating-point version of the input signal */
49 real *real_signal_mid_side[2]; /* the floating-point version of the mid-side input signal (stereo only) */
Josh Coalson82b73242001-03-28 22:17:05 +000050 unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
Josh Coalsonac4c1582001-03-28 23:10:22 +000051 unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
Josh Coalson94e02cd2001-01-25 10:41:06 +000052 int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
53 int32 *residual_workspace_mid_side[2][2];
54 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
55 FLAC__Subframe subframe_workspace_mid_side[2][2];
56 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
57 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
58 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index into the above workspaces */
59 unsigned best_subframe_mid_side[2];
60 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
61 unsigned best_subframe_bits_mid_side[2];
Josh Coalson2051dd42001-04-12 22:22:34 +000062 uint32 *abs_residual; /* workspace where abs(candidate residual) is stored */
Josh Coalsond4e0ddb2001-04-18 02:20:52 +000063 uint32 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
Josh Coalson2051dd42001-04-12 22:22:34 +000064 unsigned *bits_per_residual_sample; /* workspace where silog2(candidate residual) is stored */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000065 FLAC__BitBuffer frame; /* the current frame being worked on */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000066 bool current_frame_can_do_mid_side; /* encoder sets this false when any given sample of a frame's side channel exceeds 16 bits */
Josh Coalsonb5e60e52001-01-28 09:27:27 +000067 double loose_mid_side_stereo_frames_exact; /* exact number of frames the encoder will use before trying both independent and mid/side frames again */
68 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
69 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
70 FLAC__ChannelAssignment last_channel_assignment;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000071 FLAC__StreamMetaData metadata;
72 unsigned current_sample_number;
73 unsigned current_frame_number;
Josh Coalsonfa37f1c2001-01-12 23:55:11 +000074 struct MD5Context md5context;
Josh Coalsoneef56702001-03-30 00:45:22 +000075 bool use_slow; /* use slow 64-bit versions of some functions */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000076 FLAC__EncoderWriteStatus (*write_callback)(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
77 void (*metadata_callback)(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
78 void *client_data;
79} FLAC__EncoderPrivate;
80
81static bool encoder_resize_buffers_(FLAC__Encoder *encoder, unsigned new_size);
82static bool encoder_process_frame_(FLAC__Encoder *encoder, bool is_last_frame);
Josh Coalson94e02cd2001-01-25 10:41:06 +000083static bool encoder_process_subframes_(FLAC__Encoder *encoder, bool is_last_frame);
Josh Coalson82b73242001-03-28 22:17:05 +000084static bool encoder_process_subframe_(FLAC__Encoder *encoder, unsigned max_partition_order, bool verbatim_only, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const int32 integer_signal[], const real real_signal[], FLAC__Subframe *subframe[2], int32 *residual[2], unsigned *best_subframe, unsigned *best_bits);
85static bool encoder_add_subframe_(FLAC__Encoder *encoder, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const FLAC__Subframe *subframe, FLAC__BitBuffer *frame);
86static unsigned encoder_evaluate_constant_subframe_(const int32 signal, unsigned subframe_bps, FLAC__Subframe *subframe);
Josh Coalsond4e0ddb2001-04-18 02:20:52 +000087static unsigned encoder_evaluate_fixed_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned bits_per_residual_sample[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe);
88static unsigned encoder_evaluate_lpc_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned bits_per_residual_sample[], const real lp_coeff[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned qlp_coeff_precision, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe);
Josh Coalson82b73242001-03-28 22:17:05 +000089static unsigned encoder_evaluate_verbatim_subframe_(const int32 signal[], unsigned blocksize, unsigned subframe_bps, FLAC__Subframe *subframe);
Josh Coalsond4e0ddb2001-04-18 02:20:52 +000090static unsigned encoder_find_best_partition_order_(const int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned bits_per_residual_sample[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned max_partition_order, unsigned *best_partition_order, unsigned best_parameters[], unsigned best_raw_bits[]);
91static bool encoder_set_partitioned_rice_(const uint32 abs_residual[], const uint32 abs_residual_partition_sums[], const unsigned bits_per_residual_sample[], const unsigned residual_samples, const unsigned predictor_order, unsigned rice_parameter, const unsigned partition_order, unsigned parameters[], unsigned raw_bits[], unsigned *bits);
Josh Coalson859bc542001-03-27 22:22:27 +000092static unsigned encoder_get_wasted_bits_(int32 signal[], unsigned samples);
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000093
Josh Coalsoncbf595f2000-12-22 22:35:33 +000094const char *FLAC__EncoderWriteStatusString[] = {
95 "FLAC__ENCODER_WRITE_OK",
96 "FLAC__ENCODER_WRITE_FATAL_ERROR"
97};
98
99const char *FLAC__EncoderStateString[] = {
100 "FLAC__ENCODER_OK",
101 "FLAC__ENCODER_UNINITIALIZED",
102 "FLAC__ENCODER_INVALID_NUMBER_OF_CHANNELS",
103 "FLAC__ENCODER_INVALID_BITS_PER_SAMPLE",
104 "FLAC__ENCODER_INVALID_SAMPLE_RATE",
105 "FLAC__ENCODER_INVALID_BLOCK_SIZE",
106 "FLAC__ENCODER_INVALID_QLP_COEFF_PRECISION",
107 "FLAC__ENCODER_MID_SIDE_CHANNELS_MISMATCH",
108 "FLAC__ENCODER_MID_SIDE_SAMPLE_SIZE_MISMATCH",
Josh Coalson69f1ee02001-01-24 00:54:43 +0000109 "FLAC__ENCODER_ILLEGAL_MID_SIDE_FORCE",
Josh Coalsoncbf595f2000-12-22 22:35:33 +0000110 "FLAC__ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
111 "FLAC__ENCODER_NOT_STREAMABLE",
112 "FLAC__ENCODER_FRAMING_ERROR",
113 "FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING",
114 "FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING",
115 "FLAC__ENCODER_MEMORY_ALLOCATION_ERROR"
116};
117
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000118
119bool encoder_resize_buffers_(FLAC__Encoder *encoder, unsigned new_size)
120{
121 bool ok;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000122 unsigned i, channel;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000123 int32 *previous_is, *current_is;
124 real *previous_rs, *current_rs;
125 int32 *residual;
Josh Coalsone77287e2001-01-20 01:27:55 +0000126 uint32 *abs_residual;
Josh Coalson2051dd42001-04-12 22:22:34 +0000127 unsigned *bits_per_residual_sample;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000128
129 assert(new_size > 0);
130 assert(encoder->state == FLAC__ENCODER_OK);
131 assert(encoder->guts->current_sample_number == 0);
132
133 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
134 if(new_size <= encoder->guts->input_capacity)
135 return true;
136
137 ok = 1;
138 if(ok) {
139 for(i = 0; ok && i < encoder->channels; i++) {
140 /* integer version of the signal */
141 previous_is = encoder->guts->integer_signal[i];
142 current_is = (int32*)malloc(sizeof(int32) * new_size);
143 if(0 == current_is) {
144 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
145 ok = 0;
146 }
147 else {
148 encoder->guts->integer_signal[i] = current_is;
149 if(previous_is != 0)
150 free(previous_is);
151 }
152 /* real version of the signal */
153 previous_rs = encoder->guts->real_signal[i];
154 current_rs = (real*)malloc(sizeof(real) * new_size);
155 if(0 == current_rs) {
156 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
157 ok = 0;
158 }
159 else {
160 encoder->guts->real_signal[i] = current_rs;
161 if(previous_rs != 0)
162 free(previous_rs);
163 }
164 }
165 }
166 if(ok) {
167 for(i = 0; ok && i < 2; i++) {
168 /* integer version of the signal */
169 previous_is = encoder->guts->integer_signal_mid_side[i];
170 current_is = (int32*)malloc(sizeof(int32) * new_size);
171 if(0 == current_is) {
172 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
173 ok = 0;
174 }
175 else {
176 encoder->guts->integer_signal_mid_side[i] = current_is;
177 if(previous_is != 0)
178 free(previous_is);
179 }
180 /* real version of the signal */
181 previous_rs = encoder->guts->real_signal_mid_side[i];
182 current_rs = (real*)malloc(sizeof(real) * new_size);
183 if(0 == current_rs) {
184 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
185 ok = 0;
186 }
187 else {
188 encoder->guts->real_signal_mid_side[i] = current_rs;
189 if(previous_rs != 0)
190 free(previous_rs);
191 }
192 }
193 }
194 if(ok) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000195 for(channel = 0; channel < encoder->channels; channel++) {
196 for(i = 0; i < 2; i++) {
197 residual = (int32*)malloc(sizeof(int32) * new_size);
198 if(0 == residual) {
199 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
200 ok = 0;
201 }
202 else {
203 if(encoder->guts->residual_workspace[channel][i] != 0)
204 free(encoder->guts->residual_workspace[channel][i]);
205 encoder->guts->residual_workspace[channel][i] = residual;
206 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000207 }
Josh Coalson94e02cd2001-01-25 10:41:06 +0000208 }
209 for(channel = 0; channel < 2; channel++) {
210 for(i = 0; i < 2; i++) {
211 residual = (int32*)malloc(sizeof(int32) * new_size);
212 if(0 == residual) {
213 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
214 ok = 0;
215 }
216 else {
217 if(encoder->guts->residual_workspace_mid_side[channel][i] != 0)
218 free(encoder->guts->residual_workspace_mid_side[channel][i]);
219 encoder->guts->residual_workspace_mid_side[channel][i] = residual;
220 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000221 }
222 }
Josh Coalsone77287e2001-01-20 01:27:55 +0000223 abs_residual = (uint32*)malloc(sizeof(uint32) * new_size);
Josh Coalsond4e0ddb2001-04-18 02:20:52 +0000224 if(0 == abs_residual) {
Josh Coalsone77287e2001-01-20 01:27:55 +0000225 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
226 ok = 0;
227 }
228 else {
229 if(encoder->guts->abs_residual != 0)
230 free(encoder->guts->abs_residual);
231 encoder->guts->abs_residual = abs_residual;
232 }
Josh Coalsond4e0ddb2001-04-18 02:20:52 +0000233 abs_residual = (uint32*)malloc(sizeof(uint32) * (new_size * 2));
234 if(0 == abs_residual) {
235 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
236 ok = 0;
237 }
238 else {
239 if(encoder->guts->abs_residual_partition_sums != 0)
240 free(encoder->guts->abs_residual_partition_sums);
241 encoder->guts->abs_residual_partition_sums = abs_residual;
242 }
Josh Coalson2051dd42001-04-12 22:22:34 +0000243 bits_per_residual_sample = (unsigned*)malloc(sizeof(unsigned) * new_size);
Josh Coalsond4e0ddb2001-04-18 02:20:52 +0000244 if(0 == bits_per_residual_sample) {
Josh Coalson2051dd42001-04-12 22:22:34 +0000245 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
246 ok = 0;
247 }
248 else {
249 if(encoder->guts->bits_per_residual_sample != 0)
250 free(encoder->guts->bits_per_residual_sample);
251 encoder->guts->bits_per_residual_sample = bits_per_residual_sample;
252 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000253 }
254 if(ok)
255 encoder->guts->input_capacity = new_size;
256
257 return ok;
258}
259
260FLAC__Encoder *FLAC__encoder_get_new_instance()
261{
262 FLAC__Encoder *encoder = (FLAC__Encoder*)malloc(sizeof(FLAC__Encoder));
263 if(encoder != 0) {
264 encoder->state = FLAC__ENCODER_UNINITIALIZED;
265 encoder->guts = 0;
266 }
267 return encoder;
268}
269
270void FLAC__encoder_free_instance(FLAC__Encoder *encoder)
271{
272 assert(encoder != 0);
273 free(encoder);
274}
275
276FLAC__EncoderState FLAC__encoder_init(FLAC__Encoder *encoder, FLAC__EncoderWriteStatus (*write_callback)(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data), void (*metadata_callback)(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data), void *client_data)
277{
278 unsigned i;
Josh Coalsonc692d382001-02-23 21:05:05 +0000279 FLAC__StreamMetaData padding;
Josh Coalson0a72e182001-04-13 19:17:16 +0000280 FLAC__StreamMetaData seek_table;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000281
282 assert(sizeof(int) >= 4); /* we want to die right away if this is not true */
283 assert(encoder != 0);
284 assert(write_callback != 0);
285 assert(metadata_callback != 0);
286 assert(encoder->state == FLAC__ENCODER_UNINITIALIZED);
287 assert(encoder->guts == 0);
288
289 encoder->state = FLAC__ENCODER_OK;
290
291 if(encoder->channels == 0 || encoder->channels > FLAC__MAX_CHANNELS)
292 return encoder->state = FLAC__ENCODER_INVALID_NUMBER_OF_CHANNELS;
293
294 if(encoder->do_mid_side_stereo && encoder->channels != 2)
295 return encoder->state = FLAC__ENCODER_MID_SIDE_CHANNELS_MISMATCH;
296
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000297 if(encoder->loose_mid_side_stereo && !encoder->do_mid_side_stereo)
Josh Coalson69f1ee02001-01-24 00:54:43 +0000298 return encoder->state = FLAC__ENCODER_ILLEGAL_MID_SIDE_FORCE;
299
Josh Coalson82b73242001-03-28 22:17:05 +0000300 if(encoder->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->bits_per_sample > FLAC__MAX_BITS_PER_SAMPLE)
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000301 return encoder->state = FLAC__ENCODER_INVALID_BITS_PER_SAMPLE;
302
303 if(encoder->sample_rate == 0 || encoder->sample_rate > FLAC__MAX_SAMPLE_RATE)
304 return encoder->state = FLAC__ENCODER_INVALID_SAMPLE_RATE;
305
306 if(encoder->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->blocksize > FLAC__MAX_BLOCK_SIZE)
307 return encoder->state = FLAC__ENCODER_INVALID_BLOCK_SIZE;
308
309 if(encoder->blocksize < encoder->max_lpc_order)
310 return encoder->state = FLAC__ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
311
312 if(encoder->qlp_coeff_precision == 0) {
313 if(encoder->bits_per_sample < 16) {
314 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
315 /* @@@ until then we'll make a guess */
316 encoder->qlp_coeff_precision = max(5, 2 + encoder->bits_per_sample / 2);
317 }
318 else if(encoder->bits_per_sample == 16) {
319 if(encoder->blocksize <= 192)
320 encoder->qlp_coeff_precision = 7;
321 else if(encoder->blocksize <= 384)
322 encoder->qlp_coeff_precision = 8;
323 else if(encoder->blocksize <= 576)
324 encoder->qlp_coeff_precision = 9;
325 else if(encoder->blocksize <= 1152)
326 encoder->qlp_coeff_precision = 10;
327 else if(encoder->blocksize <= 2304)
328 encoder->qlp_coeff_precision = 11;
329 else if(encoder->blocksize <= 4608)
330 encoder->qlp_coeff_precision = 12;
331 else
332 encoder->qlp_coeff_precision = 13;
333 }
334 else {
335 encoder->qlp_coeff_precision = min(13, 8*sizeof(int32) - encoder->bits_per_sample - 1);
336 }
337 }
Josh Coalson0552fdf2001-02-26 20:29:56 +0000338 else if(encoder->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->qlp_coeff_precision + encoder->bits_per_sample >= 8*sizeof(uint32) || encoder->qlp_coeff_precision >= (1u<<FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000339 return encoder->state = FLAC__ENCODER_INVALID_QLP_COEFF_PRECISION;
340
341 if(encoder->streamable_subset) {
Josh Coalsond4e0ddb2001-04-18 02:20:52 +0000342 //@@@ add check for blocksize here
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000343 if(encoder->bits_per_sample != 8 && encoder->bits_per_sample != 12 && encoder->bits_per_sample != 16 && encoder->bits_per_sample != 20 && encoder->bits_per_sample != 24)
344 return encoder->state = FLAC__ENCODER_NOT_STREAMABLE;
345 if(encoder->sample_rate > 655350)
346 return encoder->state = FLAC__ENCODER_NOT_STREAMABLE;
347 }
348
349 if(encoder->rice_optimization_level >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
350 encoder->rice_optimization_level = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
351
352 encoder->guts = (FLAC__EncoderPrivate*)malloc(sizeof(FLAC__EncoderPrivate));
353 if(encoder->guts == 0)
354 return encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
355
356 encoder->guts->input_capacity = 0;
357 for(i = 0; i < encoder->channels; i++) {
358 encoder->guts->integer_signal[i] = 0;
359 encoder->guts->real_signal[i] = 0;
360 }
361 for(i = 0; i < 2; i++) {
362 encoder->guts->integer_signal_mid_side[i] = 0;
363 encoder->guts->real_signal_mid_side[i] = 0;
364 }
Josh Coalson94e02cd2001-01-25 10:41:06 +0000365 for(i = 0; i < encoder->channels; i++) {
366 encoder->guts->residual_workspace[i][0] = encoder->guts->residual_workspace[i][1] = 0;
367 encoder->guts->best_subframe[i] = 0;
368 }
369 for(i = 0; i < 2; i++) {
370 encoder->guts->residual_workspace_mid_side[i][0] = encoder->guts->residual_workspace_mid_side[i][1] = 0;
371 encoder->guts->best_subframe_mid_side[i] = 0;
372 }
373 for(i = 0; i < encoder->channels; i++) {
374 encoder->guts->subframe_workspace_ptr[i][0] = &encoder->guts->subframe_workspace[i][0];
375 encoder->guts->subframe_workspace_ptr[i][1] = &encoder->guts->subframe_workspace[i][1];
376 }
377 for(i = 0; i < 2; i++) {
378 encoder->guts->subframe_workspace_ptr_mid_side[i][0] = &encoder->guts->subframe_workspace_mid_side[i][0];
379 encoder->guts->subframe_workspace_ptr_mid_side[i][1] = &encoder->guts->subframe_workspace_mid_side[i][1];
380 }
Josh Coalsone77287e2001-01-20 01:27:55 +0000381 encoder->guts->abs_residual = 0;
Josh Coalsond4e0ddb2001-04-18 02:20:52 +0000382 encoder->guts->abs_residual_partition_sums = 0;
Josh Coalson2051dd42001-04-12 22:22:34 +0000383 encoder->guts->bits_per_residual_sample = 0;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000384 encoder->guts->current_frame_can_do_mid_side = true;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000385 encoder->guts->loose_mid_side_stereo_frames_exact = (double)encoder->sample_rate * 0.4 / (double)encoder->blocksize;
386 encoder->guts->loose_mid_side_stereo_frames = (unsigned)(encoder->guts->loose_mid_side_stereo_frames_exact + 0.5);
387 if(encoder->guts->loose_mid_side_stereo_frames == 0)
388 encoder->guts->loose_mid_side_stereo_frames = 1;
389 encoder->guts->loose_mid_side_stereo_frame_count = 0;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000390 encoder->guts->current_sample_number = 0;
391 encoder->guts->current_frame_number = 0;
392
Josh Coalsoneef56702001-03-30 00:45:22 +0000393 if(encoder->bits_per_sample + FLAC__bitmath_ilog2(encoder->blocksize)+1 > 30)
394 encoder->guts->use_slow = true;
395 else
396 encoder->guts->use_slow = false;
397
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000398 if(!encoder_resize_buffers_(encoder, encoder->blocksize)) {
399 /* the above function sets the state for us in case of an error */
400 return encoder->state;
401 }
402 FLAC__bitbuffer_init(&encoder->guts->frame);
403 encoder->guts->write_callback = write_callback;
404 encoder->guts->metadata_callback = metadata_callback;
405 encoder->guts->client_data = client_data;
406
407 /*
408 * write the stream header
409 */
410 if(!FLAC__bitbuffer_clear(&encoder->guts->frame))
411 return encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
412
413 if(!FLAC__bitbuffer_write_raw_uint32(&encoder->guts->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN))
414 return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
415
Josh Coalsonc692d382001-02-23 21:05:05 +0000416 encoder->guts->metadata.type = FLAC__METADATA_TYPE_STREAMINFO;
Josh Coalson0a72e182001-04-13 19:17:16 +0000417 encoder->guts->metadata.is_last = (encoder->seek_table == 0 && encoder->padding == 0);
Josh Coalsonc692d382001-02-23 21:05:05 +0000418 encoder->guts->metadata.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
419 encoder->guts->metadata.data.stream_info.min_blocksize = encoder->blocksize; /* this encoder uses the same blocksize for the whole stream */
420 encoder->guts->metadata.data.stream_info.max_blocksize = encoder->blocksize;
421 encoder->guts->metadata.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
422 encoder->guts->metadata.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
423 encoder->guts->metadata.data.stream_info.sample_rate = encoder->sample_rate;
424 encoder->guts->metadata.data.stream_info.channels = encoder->channels;
425 encoder->guts->metadata.data.stream_info.bits_per_sample = encoder->bits_per_sample;
426 encoder->guts->metadata.data.stream_info.total_samples = encoder->total_samples_estimate; /* we will replace this later with the real total */
427 memset(encoder->guts->metadata.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
Josh Coalsonfa37f1c2001-01-12 23:55:11 +0000428 MD5Init(&encoder->guts->md5context);
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000429 if(!FLAC__add_metadata_block(&encoder->guts->metadata, &encoder->guts->frame))
430 return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
431
Josh Coalson0a72e182001-04-13 19:17:16 +0000432 if(0 != encoder->seek_table) {
433 if(!FLAC__seek_table_is_valid(encoder->seek_table))
434 return encoder->state = FLAC__ENCODER_INVALID_SEEK_TABLE;
435 seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
436 seek_table.is_last = (encoder->padding == 0);
437 seek_table.length = encoder->seek_table->num_points * FLAC__STREAM_METADATA_SEEKPOINT_LEN;
438 seek_table.data.seek_table = *encoder->seek_table;
439 if(!FLAC__add_metadata_block(&seek_table, &encoder->guts->frame))
440 return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
441 }
442
Josh Coalsonc692d382001-02-23 21:05:05 +0000443 /* add a PADDING block if requested */
444 if(encoder->padding > 0) {
445 padding.type = FLAC__METADATA_TYPE_PADDING;
446 padding.is_last = true;
447 padding.length = encoder->padding;
448 if(!FLAC__add_metadata_block(&padding, &encoder->guts->frame))
449 return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
450 }
451
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000452 assert(encoder->guts->frame.bits == 0); /* assert that we're byte-aligned before writing */
453 assert(encoder->guts->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
454 if(encoder->guts->write_callback(encoder, encoder->guts->frame.buffer, encoder->guts->frame.bytes, 0, encoder->guts->current_frame_number, encoder->guts->client_data) != FLAC__ENCODER_WRITE_OK)
455 return encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING;
456
Josh Coalsoncbbbb5f2001-01-23 00:41:48 +0000457 /* now that the metadata block is written, we can init this to an absurdly-high value... */
Josh Coalsonc692d382001-02-23 21:05:05 +0000458 encoder->guts->metadata.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
Josh Coalsoncbbbb5f2001-01-23 00:41:48 +0000459 /* ... and clear this to 0 */
Josh Coalsonc692d382001-02-23 21:05:05 +0000460 encoder->guts->metadata.data.stream_info.total_samples = 0;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000461
462 return encoder->state;
463}
464
465void FLAC__encoder_finish(FLAC__Encoder *encoder)
466{
Josh Coalson94e02cd2001-01-25 10:41:06 +0000467 unsigned i, channel;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000468
469 assert(encoder != 0);
470 if(encoder->state == FLAC__ENCODER_UNINITIALIZED)
471 return;
472 if(encoder->guts->current_sample_number != 0) {
473 encoder->blocksize = encoder->guts->current_sample_number;
474 encoder_process_frame_(encoder, true); /* true => is last frame */
475 }
Josh Coalsonc692d382001-02-23 21:05:05 +0000476 MD5Final(encoder->guts->metadata.data.stream_info.md5sum, &encoder->guts->md5context);
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000477 encoder->guts->metadata_callback(encoder, &encoder->guts->metadata, encoder->guts->client_data);
478 if(encoder->guts != 0) {
479 for(i = 0; i < encoder->channels; i++) {
480 if(encoder->guts->integer_signal[i] != 0) {
481 free(encoder->guts->integer_signal[i]);
482 encoder->guts->integer_signal[i] = 0;
483 }
484 if(encoder->guts->real_signal[i] != 0) {
485 free(encoder->guts->real_signal[i]);
486 encoder->guts->real_signal[i] = 0;
487 }
488 }
489 for(i = 0; i < 2; i++) {
490 if(encoder->guts->integer_signal_mid_side[i] != 0) {
491 free(encoder->guts->integer_signal_mid_side[i]);
492 encoder->guts->integer_signal_mid_side[i] = 0;
493 }
494 if(encoder->guts->real_signal_mid_side[i] != 0) {
495 free(encoder->guts->real_signal_mid_side[i]);
496 encoder->guts->real_signal_mid_side[i] = 0;
497 }
498 }
Josh Coalson94e02cd2001-01-25 10:41:06 +0000499 for(channel = 0; channel < encoder->channels; channel++) {
500 for(i = 0; i < 2; i++) {
501 if(encoder->guts->residual_workspace[channel][i] != 0) {
502 free(encoder->guts->residual_workspace[channel][i]);
503 encoder->guts->residual_workspace[channel][i] = 0;
504 }
505 }
506 }
507 for(channel = 0; channel < 2; channel++) {
508 for(i = 0; i < 2; i++) {
509 if(encoder->guts->residual_workspace_mid_side[channel][i] != 0) {
510 free(encoder->guts->residual_workspace_mid_side[channel][i]);
511 encoder->guts->residual_workspace_mid_side[channel][i] = 0;
512 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000513 }
514 }
Josh Coalsone77287e2001-01-20 01:27:55 +0000515 if(encoder->guts->abs_residual != 0) {
516 free(encoder->guts->abs_residual);
517 encoder->guts->abs_residual = 0;
518 }
Josh Coalsond4e0ddb2001-04-18 02:20:52 +0000519 if(encoder->guts->abs_residual_partition_sums != 0) {
520 free(encoder->guts->abs_residual_partition_sums);
521 encoder->guts->abs_residual_partition_sums = 0;
522 }
Josh Coalson2051dd42001-04-12 22:22:34 +0000523 if(encoder->guts->bits_per_residual_sample != 0) {
524 free(encoder->guts->bits_per_residual_sample);
525 encoder->guts->bits_per_residual_sample = 0;
526 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000527 FLAC__bitbuffer_free(&encoder->guts->frame);
528 free(encoder->guts);
529 encoder->guts = 0;
530 }
531 encoder->state = FLAC__ENCODER_UNINITIALIZED;
532}
533
534bool FLAC__encoder_process(FLAC__Encoder *encoder, const int32 *buf[], unsigned samples)
535{
536 unsigned i, j, channel;
537 int32 x, mid, side;
538 const bool ms = encoder->do_mid_side_stereo && encoder->channels == 2;
539 const int32 min_side = -((int64)1 << (encoder->bits_per_sample-1));
540 const int32 max_side = ((int64)1 << (encoder->bits_per_sample-1)) - 1;
541
542 assert(encoder != 0);
543 assert(encoder->state == FLAC__ENCODER_OK);
544
545 j = 0;
546 do {
547 for(i = encoder->guts->current_sample_number; i < encoder->blocksize && j < samples; i++, j++) {
548 for(channel = 0; channel < encoder->channels; channel++) {
549 x = buf[channel][j];
550 encoder->guts->integer_signal[channel][i] = x;
551 encoder->guts->real_signal[channel][i] = (real)x;
552 }
553 if(ms && encoder->guts->current_frame_can_do_mid_side) {
554 side = buf[0][j] - buf[1][j];
555 if(side < min_side || side > max_side) {
556 encoder->guts->current_frame_can_do_mid_side = false;
557 }
558 else {
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000559 mid = (buf[0][j] + buf[1][j]) >> 1; /* NOTE: not the same as 'mid = (buf[0][j] + buf[1][j]) / 2' ! */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000560 encoder->guts->integer_signal_mid_side[0][i] = mid;
561 encoder->guts->integer_signal_mid_side[1][i] = side;
562 encoder->guts->real_signal_mid_side[0][i] = (real)mid;
563 encoder->guts->real_signal_mid_side[1][i] = (real)side;
564 }
565 }
566 encoder->guts->current_sample_number++;
567 }
568 if(i == encoder->blocksize) {
569 if(!encoder_process_frame_(encoder, false)) /* false => not last frame */
570 return false;
571 }
572 } while(j < samples);
573
574 return true;
575}
576
577/* 'samples' is channel-wide samples, e.g. for 1 second at 44100Hz, 'samples' = 44100 regardless of the number of channels */
578bool FLAC__encoder_process_interleaved(FLAC__Encoder *encoder, const int32 buf[], unsigned samples)
579{
580 unsigned i, j, k, channel;
581 int32 x, left = 0, mid, side;
582 const bool ms = encoder->do_mid_side_stereo && encoder->channels == 2;
583 const int32 min_side = -((int64)1 << (encoder->bits_per_sample-1));
584 const int32 max_side = ((int64)1 << (encoder->bits_per_sample-1)) - 1;
585
586 assert(encoder != 0);
587 assert(encoder->state == FLAC__ENCODER_OK);
588
589 j = k = 0;
590 do {
591 for(i = encoder->guts->current_sample_number; i < encoder->blocksize && j < samples; i++, j++, k++) {
592 for(channel = 0; channel < encoder->channels; channel++, k++) {
593 x = buf[k];
594 encoder->guts->integer_signal[channel][i] = x;
595 encoder->guts->real_signal[channel][i] = (real)x;
596 if(ms && encoder->guts->current_frame_can_do_mid_side) {
597 if(channel == 0) {
598 left = x;
599 }
600 else {
601 side = left - x;
602 if(side < min_side || side > max_side) {
603 encoder->guts->current_frame_can_do_mid_side = false;
604 }
605 else {
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000606 mid = (left + x) >> 1; /* NOTE: not the same as 'mid = (left + x) / 2' ! */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000607 encoder->guts->integer_signal_mid_side[0][i] = mid;
608 encoder->guts->integer_signal_mid_side[1][i] = side;
609 encoder->guts->real_signal_mid_side[0][i] = (real)mid;
610 encoder->guts->real_signal_mid_side[1][i] = (real)side;
611 }
612 }
613 }
614 }
615 encoder->guts->current_sample_number++;
616 }
617 if(i == encoder->blocksize) {
618 if(!encoder_process_frame_(encoder, false)) /* false => not last frame */
619 return false;
620 }
621 } while(j < samples);
622
623 return true;
624}
625
626bool encoder_process_frame_(FLAC__Encoder *encoder, bool is_last_frame)
627{
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000628 assert(encoder->state == FLAC__ENCODER_OK);
629
630 /*
Josh Coalsonfa37f1c2001-01-12 23:55:11 +0000631 * Accumulate raw signal to the MD5 signature
632 */
Josh Coalsoneae4dde2001-04-16 05:33:22 +0000633 /* NOTE: some versions of GCC can't figure out const-ness right and will give you an 'incompatible pointer type' warning on arg 2 here: */
Josh Coalsonfa37f1c2001-01-12 23:55:11 +0000634 if(!FLAC__MD5Accumulate(&encoder->guts->md5context, encoder->guts->integer_signal, encoder->channels, encoder->blocksize, (encoder->bits_per_sample+7) / 8)) {
635 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
636 return false;
637 }
638
639 /*
Josh Coalson94e02cd2001-01-25 10:41:06 +0000640 * Process the frame header and subframes into the frame bitbuffer
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000641 */
Josh Coalson94e02cd2001-01-25 10:41:06 +0000642 if(!encoder_process_subframes_(encoder, is_last_frame)) {
643 /* the above function sets the state for us in case of an error */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000644 return false;
645 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000646
647 /*
648 * Zero-pad the frame to a byte_boundary
649 */
Josh Coalson94e02cd2001-01-25 10:41:06 +0000650 if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(&encoder->guts->frame)) {
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000651 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
652 return false;
653 }
654
655 /*
Josh Coalson215af572001-03-27 01:15:58 +0000656 * CRC-16 the whole thing
657 */
658 assert(encoder->guts->frame.bits == 0); /* assert that we're byte-aligned */
659 assert(encoder->guts->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
660 FLAC__bitbuffer_write_raw_uint32(&encoder->guts->frame, FLAC__crc16(encoder->guts->frame.buffer, encoder->guts->frame.bytes), FLAC__FRAME_FOOTER_CRC_LEN);
661
662 /*
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000663 * Write it
664 */
Josh Coalson94e02cd2001-01-25 10:41:06 +0000665 if(encoder->guts->write_callback(encoder, encoder->guts->frame.buffer, encoder->guts->frame.bytes, encoder->blocksize, encoder->guts->current_frame_number, encoder->guts->client_data) != FLAC__ENCODER_WRITE_OK) {
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000666 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING;
667 return false;
668 }
669
670 /*
671 * Get ready for the next frame
672 */
673 encoder->guts->current_frame_can_do_mid_side = true;
674 encoder->guts->current_sample_number = 0;
675 encoder->guts->current_frame_number++;
Josh Coalsonc692d382001-02-23 21:05:05 +0000676 encoder->guts->metadata.data.stream_info.total_samples += (uint64)encoder->blocksize;
677 encoder->guts->metadata.data.stream_info.min_framesize = min(encoder->guts->frame.bytes, encoder->guts->metadata.data.stream_info.min_framesize);
678 encoder->guts->metadata.data.stream_info.max_framesize = max(encoder->guts->frame.bytes, encoder->guts->metadata.data.stream_info.max_framesize);
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000679
680 return true;
681}
682
Josh Coalson94e02cd2001-01-25 10:41:06 +0000683bool encoder_process_subframes_(FLAC__Encoder *encoder, bool is_last_frame)
684{
685 FLAC__FrameHeader frame_header;
686 unsigned channel, max_partition_order;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000687 bool do_independent, do_mid_side;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000688
689 /*
690 * Calculate the max Rice partition order
691 */
692 if(is_last_frame) {
693 max_partition_order = 0;
694 }
695 else {
696 unsigned limit = 0, b = encoder->blocksize;
697 while(!(b & 1)) {
698 limit++;
699 b >>= 1;
700 }
701 max_partition_order = min(encoder->rice_optimization_level, limit);
702 }
703
704 /*
705 * Setup the frame
706 */
707 if(!FLAC__bitbuffer_clear(&encoder->guts->frame)) {
708 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
709 return false;
710 }
711 frame_header.blocksize = encoder->blocksize;
712 frame_header.sample_rate = encoder->sample_rate;
713 frame_header.channels = encoder->channels;
714 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
715 frame_header.bits_per_sample = encoder->bits_per_sample;
716 frame_header.number.frame_number = encoder->guts->current_frame_number;
717
718 /*
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000719 * Figure out what channel assignments to try
720 */
721 if(encoder->do_mid_side_stereo) {
722 if(encoder->loose_mid_side_stereo) {
723 if(encoder->guts->loose_mid_side_stereo_frame_count == 0) {
724 do_independent = true;
725 do_mid_side = true;
726 }
727 else {
728 do_independent = (encoder->guts->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
729 do_mid_side = !do_independent;
730 }
731 }
732 else {
733 do_independent = true;
734 do_mid_side = true;
735 }
736 }
737 else {
738 do_independent = true;
739 do_mid_side = false;
740 }
741 if(do_mid_side && !encoder->guts->current_frame_can_do_mid_side) {
742 do_independent = true;
743 do_mid_side = false;
744 }
745
746 assert(do_independent || do_mid_side);
747
748 /*
Josh Coalson82b73242001-03-28 22:17:05 +0000749 * Check for wasted bits; set effective bps for each subframe
Josh Coalson859bc542001-03-27 22:22:27 +0000750 */
751 if(do_independent) {
Josh Coalson82b73242001-03-28 22:17:05 +0000752 unsigned w;
753 for(channel = 0; channel < encoder->channels; channel++) {
754 w = encoder_get_wasted_bits_(encoder->guts->integer_signal[channel], encoder->blocksize);
755 encoder->guts->subframe_workspace[channel][0].wasted_bits = encoder->guts->subframe_workspace[channel][1].wasted_bits = w;
756 encoder->guts->subframe_bps[channel] = encoder->bits_per_sample - w;
757 }
Josh Coalson859bc542001-03-27 22:22:27 +0000758 }
759 if(do_mid_side) {
Josh Coalson82b73242001-03-28 22:17:05 +0000760 unsigned w;
Josh Coalson859bc542001-03-27 22:22:27 +0000761 assert(encoder->channels == 2);
Josh Coalson82b73242001-03-28 22:17:05 +0000762 for(channel = 0; channel < 2; channel++) {
763 w = encoder_get_wasted_bits_(encoder->guts->integer_signal_mid_side[channel], encoder->blocksize);
764 encoder->guts->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->guts->subframe_workspace_mid_side[channel][1].wasted_bits = w;
765 encoder->guts->subframe_bps_mid_side[channel] = encoder->bits_per_sample - w + (channel==0? 0:1);
766 }
Josh Coalson859bc542001-03-27 22:22:27 +0000767 }
768
769 /*
Josh Coalson94e02cd2001-01-25 10:41:06 +0000770 * First do a normal encoding pass of each independent channel
771 */
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000772 if(do_independent) {
773 for(channel = 0; channel < encoder->channels; channel++) {
Josh Coalson82b73242001-03-28 22:17:05 +0000774 if(!encoder_process_subframe_(encoder, max_partition_order, false, &frame_header, encoder->guts->subframe_bps[channel], encoder->guts->integer_signal[channel], encoder->guts->real_signal[channel], encoder->guts->subframe_workspace_ptr[channel], encoder->guts->residual_workspace[channel], encoder->guts->best_subframe+channel, encoder->guts->best_subframe_bits+channel))
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000775 return false;
776 }
Josh Coalson94e02cd2001-01-25 10:41:06 +0000777 }
778
779 /*
780 * Now do mid and side channels if requested
781 */
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000782 if(do_mid_side) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000783 assert(encoder->channels == 2);
784
785 for(channel = 0; channel < 2; channel++) {
Josh Coalson82b73242001-03-28 22:17:05 +0000786 if(!encoder_process_subframe_(encoder, max_partition_order, false, &frame_header, encoder->guts->subframe_bps_mid_side[channel], encoder->guts->integer_signal_mid_side[channel], encoder->guts->real_signal_mid_side[channel], encoder->guts->subframe_workspace_ptr_mid_side[channel], encoder->guts->residual_workspace_mid_side[channel], encoder->guts->best_subframe_mid_side+channel, encoder->guts->best_subframe_bits_mid_side+channel))
Josh Coalson94e02cd2001-01-25 10:41:06 +0000787 return false;
788 }
789 }
790
791 /*
792 * Compose the frame bitbuffer
793 */
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000794 if(do_mid_side) {
Josh Coalson82b73242001-03-28 22:17:05 +0000795 unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
796 FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000797 FLAC__ChannelAssignment channel_assignment;
798
Josh Coalson94e02cd2001-01-25 10:41:06 +0000799 assert(encoder->channels == 2);
800
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000801 if(encoder->loose_mid_side_stereo && encoder->guts->loose_mid_side_stereo_frame_count > 0) {
802 channel_assignment = (encoder->guts->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
803 }
804 else {
805 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
806 unsigned min_bits;
807 FLAC__ChannelAssignment ca;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000808
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000809 assert(do_independent && do_mid_side);
810
811 /* We have to figure out which channel assignent results in the smallest frame */
812 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->guts->best_subframe_bits [0] + encoder->guts->best_subframe_bits [1];
813 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->guts->best_subframe_bits [0] + encoder->guts->best_subframe_bits_mid_side[1];
814 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->guts->best_subframe_bits [1] + encoder->guts->best_subframe_bits_mid_side[1];
815 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->guts->best_subframe_bits_mid_side[0] + encoder->guts->best_subframe_bits_mid_side[1];
816
817 for(channel_assignment = 0, min_bits = bits[0], ca = 1; ca <= 3; ca++) {
818 if(bits[ca] < min_bits) {
819 min_bits = bits[ca];
820 channel_assignment = ca;
821 }
Josh Coalson94e02cd2001-01-25 10:41:06 +0000822 }
823 }
824
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000825 frame_header.channel_assignment = channel_assignment;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000826
827 if(!FLAC__frame_add_header(&frame_header, encoder->streamable_subset, is_last_frame, &encoder->guts->frame)) {
828 encoder->state = FLAC__ENCODER_FRAMING_ERROR;
829 return false;
830 }
831
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000832 switch(channel_assignment) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000833 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
Josh Coalson82b73242001-03-28 22:17:05 +0000834 left_subframe = &encoder->guts->subframe_workspace [0][encoder->guts->best_subframe [0]];
835 right_subframe = &encoder->guts->subframe_workspace [1][encoder->guts->best_subframe [1]];
Josh Coalson94e02cd2001-01-25 10:41:06 +0000836 break;
837 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
Josh Coalson82b73242001-03-28 22:17:05 +0000838 left_subframe = &encoder->guts->subframe_workspace [0][encoder->guts->best_subframe [0]];
839 right_subframe = &encoder->guts->subframe_workspace_mid_side[1][encoder->guts->best_subframe_mid_side[1]];
Josh Coalson94e02cd2001-01-25 10:41:06 +0000840 break;
841 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
Josh Coalson82b73242001-03-28 22:17:05 +0000842 left_subframe = &encoder->guts->subframe_workspace_mid_side[1][encoder->guts->best_subframe_mid_side[1]];
843 right_subframe = &encoder->guts->subframe_workspace [1][encoder->guts->best_subframe [1]];
Josh Coalson94e02cd2001-01-25 10:41:06 +0000844 break;
845 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
Josh Coalson82b73242001-03-28 22:17:05 +0000846 left_subframe = &encoder->guts->subframe_workspace_mid_side[0][encoder->guts->best_subframe_mid_side[0]];
847 right_subframe = &encoder->guts->subframe_workspace_mid_side[1][encoder->guts->best_subframe_mid_side[1]];
Josh Coalson94e02cd2001-01-25 10:41:06 +0000848 break;
849 default:
850 assert(0);
851 }
Josh Coalson82b73242001-03-28 22:17:05 +0000852
853 switch(channel_assignment) {
854 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
855 left_bps = encoder->guts->subframe_bps [0];
856 right_bps = encoder->guts->subframe_bps [1];
857 break;
858 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
859 left_bps = encoder->guts->subframe_bps [0];
860 right_bps = encoder->guts->subframe_bps_mid_side[1];
861 break;
862 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
863 left_bps = encoder->guts->subframe_bps_mid_side[1];
864 right_bps = encoder->guts->subframe_bps [1];
865 break;
866 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
867 left_bps = encoder->guts->subframe_bps_mid_side[0];
868 right_bps = encoder->guts->subframe_bps_mid_side[1];
869 break;
870 default:
871 assert(0);
872 }
873
874 /* note that encoder_add_subframe_ sets the state for us in case of an error */
875 if(!encoder_add_subframe_(encoder, &frame_header, left_bps , left_subframe , &encoder->guts->frame))
876 return false;
877 if(!encoder_add_subframe_(encoder, &frame_header, right_bps, right_subframe, &encoder->guts->frame))
878 return false;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000879 }
880 else {
881 if(!FLAC__frame_add_header(&frame_header, encoder->streamable_subset, is_last_frame, &encoder->guts->frame)) {
882 encoder->state = FLAC__ENCODER_FRAMING_ERROR;
883 return false;
884 }
885
886 for(channel = 0; channel < encoder->channels; channel++) {
Josh Coalson82b73242001-03-28 22:17:05 +0000887 if(!encoder_add_subframe_(encoder, &frame_header, encoder->guts->subframe_bps[channel], &encoder->guts->subframe_workspace[channel][encoder->guts->best_subframe[channel]], &encoder->guts->frame)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000888 /* the above function sets the state for us in case of an error */
889 return false;
890 }
891 }
892 }
893
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000894 if(encoder->loose_mid_side_stereo) {
895 encoder->guts->loose_mid_side_stereo_frame_count++;
896 if(encoder->guts->loose_mid_side_stereo_frame_count >= encoder->guts->loose_mid_side_stereo_frames)
897 encoder->guts->loose_mid_side_stereo_frame_count = 0;
898 }
899
900 encoder->guts->last_channel_assignment = frame_header.channel_assignment;
901
Josh Coalson94e02cd2001-01-25 10:41:06 +0000902 return true;
903}
904
Josh Coalson82b73242001-03-28 22:17:05 +0000905bool encoder_process_subframe_(FLAC__Encoder *encoder, unsigned max_partition_order, bool verbatim_only, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const int32 integer_signal[], const real real_signal[], FLAC__Subframe *subframe[2], int32 *residual[2], unsigned *best_subframe, unsigned *best_bits)
Josh Coalson94e02cd2001-01-25 10:41:06 +0000906{
907 real fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
908 real lpc_residual_bits_per_sample;
909 real autoc[FLAC__MAX_LPC_ORDER+1];
910 real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER];
911 real lpc_error[FLAC__MAX_LPC_ORDER];
912 unsigned min_lpc_order, max_lpc_order, lpc_order;
913 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
914 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
915 unsigned rice_parameter;
916 unsigned _candidate_bits, _best_bits;
917 unsigned _best_subframe;
918
919 /* verbatim subframe is the baseline against which we measure other compressed subframes */
920 _best_subframe = 0;
Josh Coalson82b73242001-03-28 22:17:05 +0000921 _best_bits = encoder_evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
Josh Coalson94e02cd2001-01-25 10:41:06 +0000922
923 if(!verbatim_only && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
924 /* check for constant subframe */
Josh Coalsoneef56702001-03-30 00:45:22 +0000925 if(encoder->guts->use_slow)
926 guess_fixed_order = FLAC__fixed_compute_best_predictor_slow(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
927 else
928 guess_fixed_order = FLAC__fixed_compute_best_predictor(integer_signal+FLAC__MAX_FIXED_ORDER, frame_header->blocksize-FLAC__MAX_FIXED_ORDER, fixed_residual_bits_per_sample);
Josh Coalson94e02cd2001-01-25 10:41:06 +0000929 if(fixed_residual_bits_per_sample[1] == 0.0) {
930 /* the above means integer_signal+FLAC__MAX_FIXED_ORDER is constant, now we just have to check the warmup samples */
931 unsigned i, signal_is_constant = true;
932 for(i = 1; i <= FLAC__MAX_FIXED_ORDER; i++) {
933 if(integer_signal[0] != integer_signal[i]) {
934 signal_is_constant = false;
935 break;
936 }
937 }
938 if(signal_is_constant) {
Josh Coalson82b73242001-03-28 22:17:05 +0000939 _candidate_bits = encoder_evaluate_constant_subframe_(integer_signal[0], subframe_bps, subframe[!_best_subframe]);
Josh Coalson94e02cd2001-01-25 10:41:06 +0000940 if(_candidate_bits < _best_bits) {
941 _best_subframe = !_best_subframe;
942 _best_bits = _candidate_bits;
943 }
944 }
945 }
946 else {
947 /* encode fixed */
948 if(encoder->do_exhaustive_model_search) {
949 min_fixed_order = 0;
950 max_fixed_order = FLAC__MAX_FIXED_ORDER;
951 }
952 else {
953 min_fixed_order = max_fixed_order = guess_fixed_order;
954 }
955 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
Josh Coalson82b73242001-03-28 22:17:05 +0000956 if(fixed_residual_bits_per_sample[fixed_order] >= (real)subframe_bps)
Josh Coalson94e02cd2001-01-25 10:41:06 +0000957 continue; /* don't even try */
Josh Coalson46f2ae82001-02-08 00:27:21 +0000958 rice_parameter = (fixed_residual_bits_per_sample[fixed_order] > 0.0)? (unsigned)(fixed_residual_bits_per_sample[fixed_order]+0.5) : 0; /* 0.5 is for rounding */
Josh Coalson352e0f62001-03-20 22:55:50 +0000959#ifndef SYMMETRIC_RICE
Josh Coalson46f2ae82001-02-08 00:27:21 +0000960 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
Josh Coalsonb9433f92001-03-17 01:07:00 +0000961#endif
Josh Coalson94e02cd2001-01-25 10:41:06 +0000962 if(rice_parameter >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN))
963 rice_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
Josh Coalsond4e0ddb2001-04-18 02:20:52 +0000964 _candidate_bits = encoder_evaluate_fixed_subframe_(integer_signal, residual[!_best_subframe], encoder->guts->abs_residual, encoder->guts->abs_residual_partition_sums, encoder->guts->bits_per_residual_sample, frame_header->blocksize, subframe_bps, fixed_order, rice_parameter, max_partition_order, subframe[!_best_subframe]);
Josh Coalson94e02cd2001-01-25 10:41:06 +0000965 if(_candidate_bits < _best_bits) {
966 _best_subframe = !_best_subframe;
967 _best_bits = _candidate_bits;
968 }
969 }
970
971 /* encode lpc */
972 if(encoder->max_lpc_order > 0) {
973 if(encoder->max_lpc_order >= frame_header->blocksize)
974 max_lpc_order = frame_header->blocksize-1;
975 else
976 max_lpc_order = encoder->max_lpc_order;
977 if(max_lpc_order > 0) {
978 FLAC__lpc_compute_autocorrelation(real_signal, frame_header->blocksize, max_lpc_order+1, autoc);
Josh Coalsonf4ce50b2001-02-28 23:45:15 +0000979 /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
980 if(autoc[0] != 0.0) {
981 FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, lp_coeff, lpc_error);
982 if(encoder->do_exhaustive_model_search) {
983 min_lpc_order = 1;
984 }
985 else {
Josh Coalson82b73242001-03-28 22:17:05 +0000986 unsigned guess_lpc_order = FLAC__lpc_compute_best_order(lpc_error, max_lpc_order, frame_header->blocksize, subframe_bps);
Josh Coalsonf4ce50b2001-02-28 23:45:15 +0000987 min_lpc_order = max_lpc_order = guess_lpc_order;
988 }
989 if(encoder->do_qlp_coeff_prec_search) {
990 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
Josh Coalson82b73242001-03-28 22:17:05 +0000991 max_qlp_coeff_precision = min(32 - subframe_bps - 1, (1u<<FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN)-1);
Josh Coalsonf4ce50b2001-02-28 23:45:15 +0000992 }
993 else {
994 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->qlp_coeff_precision;
995 }
996 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
997 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
Josh Coalson82b73242001-03-28 22:17:05 +0000998 if(lpc_residual_bits_per_sample >= (real)subframe_bps)
Josh Coalsonf4ce50b2001-02-28 23:45:15 +0000999 continue; /* don't even try */
1000 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
Josh Coalson352e0f62001-03-20 22:55:50 +00001001#ifndef SYMMETRIC_RICE
Josh Coalsonf4ce50b2001-02-28 23:45:15 +00001002 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
Josh Coalsonb9433f92001-03-17 01:07:00 +00001003#endif
Josh Coalsonf4ce50b2001-02-28 23:45:15 +00001004 if(rice_parameter >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN))
1005 rice_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
1006 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001007 _candidate_bits = encoder_evaluate_lpc_subframe_(integer_signal, residual[!_best_subframe], encoder->guts->abs_residual, encoder->guts->abs_residual_partition_sums, encoder->guts->bits_per_residual_sample, lp_coeff[lpc_order-1], frame_header->blocksize, subframe_bps, lpc_order, qlp_coeff_precision, rice_parameter, max_partition_order, subframe[!_best_subframe]);
Josh Coalsonf4ce50b2001-02-28 23:45:15 +00001008 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
1009 if(_candidate_bits < _best_bits) {
1010 _best_subframe = !_best_subframe;
1011 _best_bits = _candidate_bits;
1012 }
Josh Coalson94e02cd2001-01-25 10:41:06 +00001013 }
1014 }
1015 }
1016 }
1017 }
1018 }
1019 }
1020 }
1021
1022 *best_subframe = _best_subframe;
1023 *best_bits = _best_bits;
1024
1025 return true;
1026}
1027
Josh Coalson82b73242001-03-28 22:17:05 +00001028bool encoder_add_subframe_(FLAC__Encoder *encoder, const FLAC__FrameHeader *frame_header, unsigned subframe_bps, const FLAC__Subframe *subframe, FLAC__BitBuffer *frame)
Josh Coalson94e02cd2001-01-25 10:41:06 +00001029{
1030 switch(subframe->type) {
1031 case FLAC__SUBFRAME_TYPE_CONSTANT:
Josh Coalson82b73242001-03-28 22:17:05 +00001032 if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +00001033 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
1034 return false;
1035 }
1036 break;
1037 case FLAC__SUBFRAME_TYPE_FIXED:
Josh Coalson82b73242001-03-28 22:17:05 +00001038 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), frame_header->blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +00001039 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
1040 return false;
1041 }
1042 break;
1043 case FLAC__SUBFRAME_TYPE_LPC:
Josh Coalson82b73242001-03-28 22:17:05 +00001044 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), frame_header->blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +00001045 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
1046 return false;
1047 }
1048 break;
1049 case FLAC__SUBFRAME_TYPE_VERBATIM:
Josh Coalson82b73242001-03-28 22:17:05 +00001050 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), frame_header->blocksize, subframe_bps, subframe->wasted_bits, frame)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +00001051 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
1052 return false;
1053 }
1054 break;
1055 default:
1056 assert(0);
1057 }
1058
1059 return true;
1060}
1061
Josh Coalson82b73242001-03-28 22:17:05 +00001062unsigned encoder_evaluate_constant_subframe_(const int32 signal, unsigned subframe_bps, FLAC__Subframe *subframe)
Josh Coalson94e02cd2001-01-25 10:41:06 +00001063{
1064 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
1065 subframe->data.constant.value = signal;
1066
Josh Coalson82b73242001-03-28 22:17:05 +00001067 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe_bps;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001068}
1069
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001070unsigned encoder_evaluate_fixed_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned bits_per_residual_sample[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe)
Josh Coalson94e02cd2001-01-25 10:41:06 +00001071{
1072 unsigned i, residual_bits;
1073 const unsigned residual_samples = blocksize - order;
1074
1075 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
1076
1077 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
1078
1079 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
1080 subframe->data.fixed.residual = residual;
1081
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001082 residual_bits = encoder_find_best_partition_order_(residual, abs_residual, abs_residual_partition_sums, bits_per_residual_sample, residual_samples, order, rice_parameter, max_partition_order, &subframe->data.fixed.entropy_coding_method.data.partitioned_rice.order, subframe->data.fixed.entropy_coding_method.data.partitioned_rice.parameters, subframe->data.fixed.entropy_coding_method.data.partitioned_rice.raw_bits);
Josh Coalson94e02cd2001-01-25 10:41:06 +00001083
1084 subframe->data.fixed.order = order;
1085 for(i = 0; i < order; i++)
1086 subframe->data.fixed.warmup[i] = signal[i];
1087
Josh Coalson82b73242001-03-28 22:17:05 +00001088 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (order * subframe_bps) + residual_bits;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001089}
1090
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001091unsigned encoder_evaluate_lpc_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned bits_per_residual_sample[], const real lp_coeff[], unsigned blocksize, unsigned subframe_bps, unsigned order, unsigned qlp_coeff_precision, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe)
Josh Coalson94e02cd2001-01-25 10:41:06 +00001092{
1093 int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
1094 unsigned i, residual_bits;
1095 int quantization, ret;
1096 const unsigned residual_samples = blocksize - order;
1097
Josh Coalson82b73242001-03-28 22:17:05 +00001098 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, subframe_bps, qlp_coeff, &quantization);
Josh Coalson94e02cd2001-01-25 10:41:06 +00001099 if(ret != 0)
1100 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
1101
1102 FLAC__lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
1103
1104 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
1105
1106 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
1107 subframe->data.lpc.residual = residual;
1108
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001109 residual_bits = encoder_find_best_partition_order_(residual, abs_residual, abs_residual_partition_sums, bits_per_residual_sample, residual_samples, order, rice_parameter, max_partition_order, &subframe->data.lpc.entropy_coding_method.data.partitioned_rice.order, subframe->data.lpc.entropy_coding_method.data.partitioned_rice.parameters, subframe->data.lpc.entropy_coding_method.data.partitioned_rice.raw_bits);
Josh Coalson94e02cd2001-01-25 10:41:06 +00001110
1111 subframe->data.lpc.order = order;
1112 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
1113 subframe->data.lpc.quantization_level = quantization;
1114 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(int32)*FLAC__MAX_LPC_ORDER);
1115 for(i = 0; i < order; i++)
1116 subframe->data.lpc.warmup[i] = signal[i];
1117
Josh Coalson82b73242001-03-28 22:17:05 +00001118 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + subframe_bps)) + residual_bits;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001119}
1120
Josh Coalson82b73242001-03-28 22:17:05 +00001121unsigned encoder_evaluate_verbatim_subframe_(const int32 signal[], unsigned blocksize, unsigned subframe_bps, FLAC__Subframe *subframe)
Josh Coalson94e02cd2001-01-25 10:41:06 +00001122{
1123 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
1124
1125 subframe->data.verbatim.data = signal;
1126
Josh Coalson82b73242001-03-28 22:17:05 +00001127 return FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + (blocksize * subframe_bps);
Josh Coalson94e02cd2001-01-25 10:41:06 +00001128}
1129
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001130unsigned encoder_find_best_partition_order_(const int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned bits_per_residual_sample[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned max_partition_order, unsigned *best_partition_order, unsigned best_parameters[], unsigned best_raw_bits[])
Josh Coalson94e02cd2001-01-25 10:41:06 +00001131{
Josh Coalson94e02cd2001-01-25 10:41:06 +00001132 int32 r;
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001133 int partition_order;
1134 unsigned residual_bits, best_residual_bits = 0;
1135 unsigned residual_sample, sum, merged_sum = 0;
1136 unsigned best_parameters_index = 0, parameters[2][1 << FLAC__MAX_RICE_PARTITION_ORDER], raw_bits[2][1 << FLAC__MAX_RICE_PARTITION_ORDER];
1137 const unsigned blocksize = residual_samples + predictor_order;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001138
Josh Coalson2051dd42001-04-12 22:22:34 +00001139 /* compute abs(residual) for use later */
1140 for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
1141 r = residual[residual_sample];
1142 abs_residual[residual_sample] = (uint32)(r<0? -r : r);
1143 }
1144
1145 /* compute silog2(residual) for use later */
1146 for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
1147 bits_per_residual_sample[residual_sample] = FLAC__bitmath_silog2(residual[residual_sample]);
Josh Coalson94e02cd2001-01-25 10:41:06 +00001148 }
1149
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001150 max_partition_order = encoder_precompute_partition_sums(abs_residual, abs_residual_partition_sums, residual_samples, predictor_order, max_partition_order);
1151
1152 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= 0; partition_order--) {
1153 if(!encoder_set_partitioned_rice_(abs_residual, abs_residual_partition_sums+sum, bits_per_residual_sample, residual_samples, predictor_order, rice_parameter, (unsigned)partition_order, parameters[!best_parameters_index], raw_bits[!best_parameters_index], &residual_bits)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +00001154 assert(best_residual_bits != 0);
1155 break;
1156 }
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001157 sum += 1u << partition_order;
1158 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
1159 best_residual_bits = residual_bits;
1160 *best_partition_order = partition_order;
1161 best_parameters_index = !best_parameters_index;
1162 }
1163 }
1164 memcpy(best_parameters, parameters[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
1165 memcpy(best_raw_bits, raw_bits[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
1166
1167 return best_residual_bits;
1168}
1169
1170unsigned encoder_find_best_partition_order_(const int32 residual[], uint32 abs_residual[], uint32 abs_residual_partition_sums[], unsigned bits_per_residual_sample[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned max_partition_order, unsigned *best_partition_order, unsigned best_parameters[], unsigned best_raw_bits[])
1171{
1172 int32 r;
1173 int partition_order;
1174 unsigned residual_bits, best_residual_bits = 0;
1175 unsigned residual_sample, sum, merged_sum = 0;
1176 unsigned best_parameters_index = 0, parameters[2][1 << FLAC__MAX_RICE_PARTITION_ORDER], raw_bits[2][1 << FLAC__MAX_RICE_PARTITION_ORDER];
1177 const unsigned blocksize = residual_samples + predictor_order;
1178
1179 /* compute abs(residual) for use later */
1180 for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
1181 r = residual[residual_sample];
1182 abs_residual[residual_sample] = (uint32)(r<0? -r : r);
1183 }
1184
1185 /* compute silog2(residual) for use later */
1186 for(residual_sample = 0; residual_sample < residual_samples; residual_sample++) {
1187 bits_per_residual_sample[residual_sample] = FLAC__bitmath_silog2(residual[residual_sample]);
1188 }
1189
1190 /* pre-compute partition sums */
1191 for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
1192 unsigned partition, partition_sample, partition_samples, residual_sample;
1193 uint32 abs_residual_partition_sum;
1194 const unsigned partitions = 1u << partition_order;
1195 const unsigned default_partition_samples = blocksize >> partition_order;
1196
1197 if(default_partition_samples <= predictor_order) {
1198 assert(max_partition_order > 0);
1199 max_partition_order--;
1200 }
1201 else {
1202 for(partition = residual_sample = 0; partition < partitions; partition++) {
1203 partition_samples = default_partition_samples;
1204 if(partition == 0)
1205 partition_samples -= predictor_order;
1206 abs_residual_partition_sum = 0;
1207 for(partition_sample = 0; partition_sample < partition_samples; partition_sample++)
1208 abs_residual_partition_sum += abs_residual[residual_sample++]; /* @@@ this can overflow with small max_partition_order and (large blocksizes or bits-per-sample), FIX! */
1209 abs_residual_partition_sums[partition] = abs_residual_partition_sum;
1210 }
1211 merged_sum = partitions;
1212 break;
1213 }
1214 }
1215 for(sum = 0; partition_order > 0; partition_order--) {
1216 unsigned i;
1217 uint32 s;
1218 const unsigned partitions = 1u << partition_order;
1219 for(i = 0; i < partitions; i++) {
1220 s = abs_residual_partition_sums[sum++];
1221 s += abs_residual_partition_sums[sum++];
1222 abs_residual_partition_sums[merged_sum++] = s;
1223 }
1224 }
1225
1226 for(partition_order = (int)max_partition_order, sum = 0; partition_order >= 0; partition_order--) {
1227 if(!encoder_set_partitioned_rice_(abs_residual, abs_residual_partition_sums+sum, bits_per_residual_sample, residual_samples, predictor_order, rice_parameter, (unsigned)partition_order, parameters[!best_parameters_index], raw_bits[!best_parameters_index], &residual_bits)) {
1228 assert(best_residual_bits != 0);
1229 break;
1230 }
1231 sum += 1u << partition_order;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001232 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
1233 best_residual_bits = residual_bits;
1234 *best_partition_order = partition_order;
1235 best_parameters_index = !best_parameters_index;
1236 }
1237 }
1238 memcpy(best_parameters, parameters[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
Josh Coalson2051dd42001-04-12 22:22:34 +00001239 memcpy(best_raw_bits, raw_bits[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
Josh Coalson94e02cd2001-01-25 10:41:06 +00001240
1241 return best_residual_bits;
1242}
1243
Josh Coalson352e0f62001-03-20 22:55:50 +00001244#ifdef VARIABLE_RICE_BITS
1245#undef VARIABLE_RICE_BITS
1246#endif
1247#define VARIABLE_RICE_BITS(value, parameter) ((value) >> (parameter))
1248
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001249bool encoder_set_partitioned_rice_(const uint32 abs_residual[], const uint32 abs_residual_partition_sums[], const unsigned bits_per_residual_sample[], const unsigned residual_samples, const unsigned predictor_order, unsigned rice_parameter, const unsigned partition_order, unsigned parameters[], unsigned raw_bits[], unsigned *bits)
Josh Coalson94e02cd2001-01-25 10:41:06 +00001250{
Josh Coalson2051dd42001-04-12 22:22:34 +00001251 unsigned partition_bits, flat_bits, partition_max_bits_per_residual_sample;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001252 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
1253
Josh Coalson2051dd42001-04-12 22:22:34 +00001254 if(rice_parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER)
1255 rice_parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
1256
Josh Coalson94e02cd2001-01-25 10:41:06 +00001257 if(partition_order == 0) {
1258 unsigned i;
Josh Coalson352e0f62001-03-20 22:55:50 +00001259
Josh Coalson2051dd42001-04-12 22:22:34 +00001260 partition_bits = 0;
1261
Josh Coalson352e0f62001-03-20 22:55:50 +00001262 {
1263#ifdef VARIABLE_RICE_BITS
1264#ifdef SYMMETRIC_RICE
Josh Coalson2051dd42001-04-12 22:22:34 +00001265 partition_bits += (2+rice_parameter) * residual_samples;
Josh Coalsonb9433f92001-03-17 01:07:00 +00001266#else
Josh Coalson352e0f62001-03-20 22:55:50 +00001267 const unsigned rice_parameter_estimate = rice_parameter-1;
Josh Coalson2051dd42001-04-12 22:22:34 +00001268 partition_bits += (1+rice_parameter) * residual_samples;
Josh Coalsonb9433f92001-03-17 01:07:00 +00001269#endif
Josh Coalson94e02cd2001-01-25 10:41:06 +00001270#endif
Josh Coalson352e0f62001-03-20 22:55:50 +00001271 parameters[0] = rice_parameter;
Josh Coalson2051dd42001-04-12 22:22:34 +00001272 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1273 partition_max_bits_per_residual_sample = 0;
Josh Coalson352e0f62001-03-20 22:55:50 +00001274 for(i = 0; i < residual_samples; i++) {
1275#ifdef VARIABLE_RICE_BITS
1276#ifdef SYMMETRIC_RICE
Josh Coalson2051dd42001-04-12 22:22:34 +00001277 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter);
Josh Coalson94e02cd2001-01-25 10:41:06 +00001278#else
Josh Coalson2051dd42001-04-12 22:22:34 +00001279 partition_bits += VARIABLE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
Josh Coalsonb9433f92001-03-17 01:07:00 +00001280#endif
1281#else
Josh Coalson2051dd42001-04-12 22:22:34 +00001282 partition_bits += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
Josh Coalson94e02cd2001-01-25 10:41:06 +00001283#endif
Josh Coalson2051dd42001-04-12 22:22:34 +00001284 if(bits_per_residual_sample[i] > partition_max_bits_per_residual_sample)
1285 partition_max_bits_per_residual_sample = bits_per_residual_sample[i];
1286 }
1287 flat_bits = partition_max_bits_per_residual_sample * residual_samples + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN;
1288 if(flat_bits < partition_bits) {
1289 parameters[0] = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
1290 raw_bits[0] = partition_max_bits_per_residual_sample;
1291 partition_bits = flat_bits;
Josh Coalson352e0f62001-03-20 22:55:50 +00001292 }
1293 }
Josh Coalson2051dd42001-04-12 22:22:34 +00001294 bits_ += partition_bits;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001295 }
1296 else {
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001297 unsigned i, j, k;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001298 unsigned mean, parameter, partition_samples;
1299 const unsigned max_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001300 const unsigned partitions = 1u << partition_order;
1301 for(i = j = 0; i < partitions; i++) {
Josh Coalson2051dd42001-04-12 22:22:34 +00001302 partition_bits = 0;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001303 partition_samples = (residual_samples+predictor_order) >> partition_order;
1304 if(i == 0) {
1305 if(partition_samples <= predictor_order)
1306 return false;
1307 else
1308 partition_samples -= predictor_order;
1309 }
1310 mean = partition_samples >> 1;
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001311 mean += abs_residual_partition_sums[i];
Josh Coalson94e02cd2001-01-25 10:41:06 +00001312 mean /= partition_samples;
Josh Coalson352e0f62001-03-20 22:55:50 +00001313#ifdef SYMMETRIC_RICE
1314 /* calc parameter = floor(log2(mean)) */
Josh Coalsonb9433f92001-03-17 01:07:00 +00001315 parameter = 0;
1316mean>>=1;
1317 while(mean) {
1318 parameter++;
1319 mean >>= 1;
1320 }
Josh Coalsonb9433f92001-03-17 01:07:00 +00001321#else
Josh Coalson352e0f62001-03-20 22:55:50 +00001322 /* calc parameter = floor(log2(mean)) + 1 */
1323 parameter = 0;
1324 while(mean) {
1325 parameter++;
1326 mean >>= 1;
1327 }
Josh Coalsonb9433f92001-03-17 01:07:00 +00001328#endif
Josh Coalson94e02cd2001-01-25 10:41:06 +00001329 if(parameter > max_parameter)
1330 parameter = max_parameter;
Josh Coalson2051dd42001-04-12 22:22:34 +00001331 if(parameter >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER)
1332 parameter = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER - 1;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001333 parameters[i] = parameter;
Josh Coalson2051dd42001-04-12 22:22:34 +00001334 partition_bits += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
Josh Coalson352e0f62001-03-20 22:55:50 +00001335#ifdef VARIABLE_RICE_BITS
1336#ifdef SYMMETRIC_RICE
Josh Coalson2051dd42001-04-12 22:22:34 +00001337 partition_bits += (2+parameter) * partition_samples;
Josh Coalsonb9433f92001-03-17 01:07:00 +00001338#else
Josh Coalson2051dd42001-04-12 22:22:34 +00001339 partition_bits += (1+parameter) * partition_samples;
Josh Coalson352e0f62001-03-20 22:55:50 +00001340 --parameter;
Josh Coalsonb9433f92001-03-17 01:07:00 +00001341#endif
Josh Coalson94e02cd2001-01-25 10:41:06 +00001342#endif
Josh Coalson2051dd42001-04-12 22:22:34 +00001343 partition_max_bits_per_residual_sample = 0;
Josh Coalsond4e0ddb2001-04-18 02:20:52 +00001344 for(k = 0; k < partition_samples; j++, k++) {
Josh Coalson352e0f62001-03-20 22:55:50 +00001345#ifdef VARIABLE_RICE_BITS
1346#ifdef SYMMETRIC_RICE
Josh Coalson2051dd42001-04-12 22:22:34 +00001347 partition_bits += VARIABLE_RICE_BITS(abs_residual[j], parameter);
Josh Coalson94e02cd2001-01-25 10:41:06 +00001348#else
Josh Coalson2051dd42001-04-12 22:22:34 +00001349 partition_bits += VARIABLE_RICE_BITS(abs_residual[j], parameter);
Josh Coalsonb9433f92001-03-17 01:07:00 +00001350#endif
1351#else
Josh Coalson2051dd42001-04-12 22:22:34 +00001352 partition_bits += FLAC__bitbuffer_rice_bits(residual[j], parameter); /* NOTE: we will need to pass in residual[] instead of abs_residual[] */
Josh Coalson94e02cd2001-01-25 10:41:06 +00001353#endif
Josh Coalson2051dd42001-04-12 22:22:34 +00001354 if(bits_per_residual_sample[j] > partition_max_bits_per_residual_sample)
1355 partition_max_bits_per_residual_sample = bits_per_residual_sample[j];
1356 }
Josh Coalson2051dd42001-04-12 22:22:34 +00001357 flat_bits = partition_max_bits_per_residual_sample * partition_samples + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN;
1358 if(flat_bits < partition_bits) {
1359 parameters[i] = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
1360 raw_bits[i] = partition_max_bits_per_residual_sample;
1361 partition_bits = flat_bits;
1362 }
1363 bits_ += partition_bits;
Josh Coalson94e02cd2001-01-25 10:41:06 +00001364 }
1365 }
1366
1367 *bits = bits_;
1368 return true;
1369}
Josh Coalson859bc542001-03-27 22:22:27 +00001370
1371static unsigned encoder_get_wasted_bits_(int32 signal[], unsigned samples)
1372{
1373 unsigned i, shift;
1374 int32 x = 0;
1375
1376 for(i = 0; i < samples && !(x&1); i++)
1377 x |= signal[i];
1378
1379 if(x == 0) {
1380 shift = 0;
1381 }
1382 else {
1383 for(shift = 0; !(x&1); shift++)
1384 x >>= 1;
1385 }
1386
1387 if(shift > 0) {
1388 for(i = 0; i < samples; i++)
1389 signal[i] >>= shift;
1390 }
1391
1392 return shift;
1393}