blob: 1b32eb3bdc6a51e8aec01b8093f7a5e87863980a [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"
25#include "private/bitbuffer.h"
26#include "private/encoder_framing.h"
27#include "private/fixed.h"
28#include "private/lpc.h"
Josh Coalsonfa37f1c2001-01-12 23:55:11 +000029#include "private/md5.h"
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000030
31#ifdef min
32#undef min
33#endif
34#define min(x,y) ((x)<(y)?(x):(y))
35
36#ifdef max
37#undef max
38#endif
39#define max(x,y) ((x)>(y)?(x):(y))
40
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000041typedef struct FLAC__EncoderPrivate {
42 unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
43 int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
44 int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
45 real *real_signal[FLAC__MAX_CHANNELS]; /* the floating-point version of the input signal */
46 real *real_signal_mid_side[2]; /* the floating-point version of the mid-side input signal (stereo only) */
Josh Coalson94e02cd2001-01-25 10:41:06 +000047 int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
48 int32 *residual_workspace_mid_side[2][2];
49 FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
50 FLAC__Subframe subframe_workspace_mid_side[2][2];
51 FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
52 FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
53 unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index into the above workspaces */
54 unsigned best_subframe_mid_side[2];
55 unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
56 unsigned best_subframe_bits_mid_side[2];
Josh Coalsone77287e2001-01-20 01:27:55 +000057 uint32 *abs_residual; /* workspace where the abs(candidate residual) is stored */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000058 FLAC__BitBuffer frame; /* the current frame being worked on */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000059 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 +000060 double loose_mid_side_stereo_frames_exact; /* exact number of frames the encoder will use before trying both independent and mid/side frames again */
61 unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
62 unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
63 FLAC__ChannelAssignment last_channel_assignment;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000064 FLAC__StreamMetaData metadata;
65 unsigned current_sample_number;
66 unsigned current_frame_number;
Josh Coalsonfa37f1c2001-01-12 23:55:11 +000067 struct MD5Context md5context;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000068 FLAC__EncoderWriteStatus (*write_callback)(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
69 void (*metadata_callback)(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
70 void *client_data;
71} FLAC__EncoderPrivate;
72
73static bool encoder_resize_buffers_(FLAC__Encoder *encoder, unsigned new_size);
74static bool encoder_process_frame_(FLAC__Encoder *encoder, bool is_last_frame);
Josh Coalson94e02cd2001-01-25 10:41:06 +000075static bool encoder_process_subframes_(FLAC__Encoder *encoder, bool is_last_frame);
Josh Coalsonb5e60e52001-01-28 09:27:27 +000076static bool encoder_process_subframe_(FLAC__Encoder *encoder, unsigned max_partition_order, bool verbatim_only, const FLAC__FrameHeader *frame_header, unsigned bits_per_sample, const int32 integer_signal[], const real real_signal[], FLAC__Subframe *subframe[2], int32 *residual[2], unsigned *best_subframe, unsigned *best_bits);
77static bool encoder_add_subframe_(FLAC__Encoder *encoder, const FLAC__FrameHeader *frame_header, unsigned bits_per_sample, const FLAC__Subframe *subframe, FLAC__BitBuffer *frame);
Josh Coalson6dcea512001-01-23 23:07:36 +000078static unsigned encoder_evaluate_constant_subframe_(const int32 signal, unsigned bits_per_sample, FLAC__Subframe *subframe);
79static unsigned encoder_evaluate_fixed_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], unsigned blocksize, unsigned bits_per_sample, unsigned order, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe);
80static unsigned encoder_evaluate_lpc_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], const real lp_coeff[], unsigned blocksize, unsigned bits_per_sample, unsigned order, unsigned qlp_coeff_precision, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe);
Josh Coalson94e02cd2001-01-25 10:41:06 +000081static unsigned encoder_evaluate_verbatim_subframe_(const int32 signal[], unsigned blocksize, unsigned bits_per_sample, FLAC__Subframe *subframe);
Josh Coalsone77287e2001-01-20 01:27:55 +000082static unsigned encoder_find_best_partition_order_(const int32 residual[], uint32 abs_residual[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned max_partition_order, unsigned *best_partition_order, unsigned best_parameters[]);
Josh Coalsone77287e2001-01-20 01:27:55 +000083static bool encoder_set_partitioned_rice_(const uint32 abs_residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameter, const unsigned partition_order, unsigned parameters[], unsigned *bits);
Josh Coalsonbb7f6b92000-12-10 04:09:52 +000084
Josh Coalsoncbf595f2000-12-22 22:35:33 +000085const char *FLAC__EncoderWriteStatusString[] = {
86 "FLAC__ENCODER_WRITE_OK",
87 "FLAC__ENCODER_WRITE_FATAL_ERROR"
88};
89
90const char *FLAC__EncoderStateString[] = {
91 "FLAC__ENCODER_OK",
92 "FLAC__ENCODER_UNINITIALIZED",
93 "FLAC__ENCODER_INVALID_NUMBER_OF_CHANNELS",
94 "FLAC__ENCODER_INVALID_BITS_PER_SAMPLE",
95 "FLAC__ENCODER_INVALID_SAMPLE_RATE",
96 "FLAC__ENCODER_INVALID_BLOCK_SIZE",
97 "FLAC__ENCODER_INVALID_QLP_COEFF_PRECISION",
98 "FLAC__ENCODER_MID_SIDE_CHANNELS_MISMATCH",
99 "FLAC__ENCODER_MID_SIDE_SAMPLE_SIZE_MISMATCH",
Josh Coalson69f1ee02001-01-24 00:54:43 +0000100 "FLAC__ENCODER_ILLEGAL_MID_SIDE_FORCE",
Josh Coalsoncbf595f2000-12-22 22:35:33 +0000101 "FLAC__ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
102 "FLAC__ENCODER_NOT_STREAMABLE",
103 "FLAC__ENCODER_FRAMING_ERROR",
104 "FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING",
105 "FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING",
106 "FLAC__ENCODER_MEMORY_ALLOCATION_ERROR"
107};
108
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000109
110bool encoder_resize_buffers_(FLAC__Encoder *encoder, unsigned new_size)
111{
112 bool ok;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000113 unsigned i, channel;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000114 int32 *previous_is, *current_is;
115 real *previous_rs, *current_rs;
116 int32 *residual;
Josh Coalsone77287e2001-01-20 01:27:55 +0000117 uint32 *abs_residual;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000118
119 assert(new_size > 0);
120 assert(encoder->state == FLAC__ENCODER_OK);
121 assert(encoder->guts->current_sample_number == 0);
122
123 /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
124 if(new_size <= encoder->guts->input_capacity)
125 return true;
126
127 ok = 1;
128 if(ok) {
129 for(i = 0; ok && i < encoder->channels; i++) {
130 /* integer version of the signal */
131 previous_is = encoder->guts->integer_signal[i];
132 current_is = (int32*)malloc(sizeof(int32) * new_size);
133 if(0 == current_is) {
134 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
135 ok = 0;
136 }
137 else {
138 encoder->guts->integer_signal[i] = current_is;
139 if(previous_is != 0)
140 free(previous_is);
141 }
142 /* real version of the signal */
143 previous_rs = encoder->guts->real_signal[i];
144 current_rs = (real*)malloc(sizeof(real) * new_size);
145 if(0 == current_rs) {
146 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
147 ok = 0;
148 }
149 else {
150 encoder->guts->real_signal[i] = current_rs;
151 if(previous_rs != 0)
152 free(previous_rs);
153 }
154 }
155 }
156 if(ok) {
157 for(i = 0; ok && i < 2; i++) {
158 /* integer version of the signal */
159 previous_is = encoder->guts->integer_signal_mid_side[i];
160 current_is = (int32*)malloc(sizeof(int32) * new_size);
161 if(0 == current_is) {
162 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
163 ok = 0;
164 }
165 else {
166 encoder->guts->integer_signal_mid_side[i] = current_is;
167 if(previous_is != 0)
168 free(previous_is);
169 }
170 /* real version of the signal */
171 previous_rs = encoder->guts->real_signal_mid_side[i];
172 current_rs = (real*)malloc(sizeof(real) * new_size);
173 if(0 == current_rs) {
174 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
175 ok = 0;
176 }
177 else {
178 encoder->guts->real_signal_mid_side[i] = current_rs;
179 if(previous_rs != 0)
180 free(previous_rs);
181 }
182 }
183 }
184 if(ok) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000185 for(channel = 0; channel < encoder->channels; channel++) {
186 for(i = 0; i < 2; i++) {
187 residual = (int32*)malloc(sizeof(int32) * new_size);
188 if(0 == residual) {
189 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
190 ok = 0;
191 }
192 else {
193 if(encoder->guts->residual_workspace[channel][i] != 0)
194 free(encoder->guts->residual_workspace[channel][i]);
195 encoder->guts->residual_workspace[channel][i] = residual;
196 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000197 }
Josh Coalson94e02cd2001-01-25 10:41:06 +0000198 }
199 for(channel = 0; channel < 2; channel++) {
200 for(i = 0; i < 2; i++) {
201 residual = (int32*)malloc(sizeof(int32) * new_size);
202 if(0 == residual) {
203 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
204 ok = 0;
205 }
206 else {
207 if(encoder->guts->residual_workspace_mid_side[channel][i] != 0)
208 free(encoder->guts->residual_workspace_mid_side[channel][i]);
209 encoder->guts->residual_workspace_mid_side[channel][i] = residual;
210 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000211 }
212 }
Josh Coalsone77287e2001-01-20 01:27:55 +0000213 abs_residual = (uint32*)malloc(sizeof(uint32) * new_size);
214 if(0 == residual) {
215 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
216 ok = 0;
217 }
218 else {
219 if(encoder->guts->abs_residual != 0)
220 free(encoder->guts->abs_residual);
221 encoder->guts->abs_residual = abs_residual;
222 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000223 }
224 if(ok)
225 encoder->guts->input_capacity = new_size;
226
227 return ok;
228}
229
230FLAC__Encoder *FLAC__encoder_get_new_instance()
231{
232 FLAC__Encoder *encoder = (FLAC__Encoder*)malloc(sizeof(FLAC__Encoder));
233 if(encoder != 0) {
234 encoder->state = FLAC__ENCODER_UNINITIALIZED;
235 encoder->guts = 0;
236 }
237 return encoder;
238}
239
240void FLAC__encoder_free_instance(FLAC__Encoder *encoder)
241{
242 assert(encoder != 0);
243 free(encoder);
244}
245
246FLAC__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)
247{
248 unsigned i;
249
250 assert(sizeof(int) >= 4); /* we want to die right away if this is not true */
251 assert(encoder != 0);
252 assert(write_callback != 0);
253 assert(metadata_callback != 0);
254 assert(encoder->state == FLAC__ENCODER_UNINITIALIZED);
255 assert(encoder->guts == 0);
256
257 encoder->state = FLAC__ENCODER_OK;
258
259 if(encoder->channels == 0 || encoder->channels > FLAC__MAX_CHANNELS)
260 return encoder->state = FLAC__ENCODER_INVALID_NUMBER_OF_CHANNELS;
261
262 if(encoder->do_mid_side_stereo && encoder->channels != 2)
263 return encoder->state = FLAC__ENCODER_MID_SIDE_CHANNELS_MISMATCH;
264
265 if(encoder->do_mid_side_stereo && encoder->bits_per_sample > 16)
266 return encoder->state = FLAC__ENCODER_MID_SIDE_SAMPLE_SIZE_MISMATCH;
267
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000268 if(encoder->loose_mid_side_stereo && !encoder->do_mid_side_stereo)
Josh Coalson69f1ee02001-01-24 00:54:43 +0000269 return encoder->state = FLAC__ENCODER_ILLEGAL_MID_SIDE_FORCE;
270
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000271 if(encoder->bits_per_sample == 0 || encoder->bits_per_sample > FLAC__MAX_BITS_PER_SAMPLE)
272 return encoder->state = FLAC__ENCODER_INVALID_BITS_PER_SAMPLE;
273
274 if(encoder->sample_rate == 0 || encoder->sample_rate > FLAC__MAX_SAMPLE_RATE)
275 return encoder->state = FLAC__ENCODER_INVALID_SAMPLE_RATE;
276
277 if(encoder->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->blocksize > FLAC__MAX_BLOCK_SIZE)
278 return encoder->state = FLAC__ENCODER_INVALID_BLOCK_SIZE;
279
280 if(encoder->blocksize < encoder->max_lpc_order)
281 return encoder->state = FLAC__ENCODER_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
282
283 if(encoder->qlp_coeff_precision == 0) {
284 if(encoder->bits_per_sample < 16) {
285 /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
286 /* @@@ until then we'll make a guess */
287 encoder->qlp_coeff_precision = max(5, 2 + encoder->bits_per_sample / 2);
288 }
289 else if(encoder->bits_per_sample == 16) {
290 if(encoder->blocksize <= 192)
291 encoder->qlp_coeff_precision = 7;
292 else if(encoder->blocksize <= 384)
293 encoder->qlp_coeff_precision = 8;
294 else if(encoder->blocksize <= 576)
295 encoder->qlp_coeff_precision = 9;
296 else if(encoder->blocksize <= 1152)
297 encoder->qlp_coeff_precision = 10;
298 else if(encoder->blocksize <= 2304)
299 encoder->qlp_coeff_precision = 11;
300 else if(encoder->blocksize <= 4608)
301 encoder->qlp_coeff_precision = 12;
302 else
303 encoder->qlp_coeff_precision = 13;
304 }
305 else {
306 encoder->qlp_coeff_precision = min(13, 8*sizeof(int32) - encoder->bits_per_sample - 1);
307 }
308 }
309 else if(encoder->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->qlp_coeff_precision + encoder->bits_per_sample >= 8*sizeof(uint32))
310 return encoder->state = FLAC__ENCODER_INVALID_QLP_COEFF_PRECISION;
311
312 if(encoder->streamable_subset) {
313 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)
314 return encoder->state = FLAC__ENCODER_NOT_STREAMABLE;
315 if(encoder->sample_rate > 655350)
316 return encoder->state = FLAC__ENCODER_NOT_STREAMABLE;
317 }
318
319 if(encoder->rice_optimization_level >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
320 encoder->rice_optimization_level = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
321
322 encoder->guts = (FLAC__EncoderPrivate*)malloc(sizeof(FLAC__EncoderPrivate));
323 if(encoder->guts == 0)
324 return encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
325
326 encoder->guts->input_capacity = 0;
327 for(i = 0; i < encoder->channels; i++) {
328 encoder->guts->integer_signal[i] = 0;
329 encoder->guts->real_signal[i] = 0;
330 }
331 for(i = 0; i < 2; i++) {
332 encoder->guts->integer_signal_mid_side[i] = 0;
333 encoder->guts->real_signal_mid_side[i] = 0;
334 }
Josh Coalson94e02cd2001-01-25 10:41:06 +0000335 for(i = 0; i < encoder->channels; i++) {
336 encoder->guts->residual_workspace[i][0] = encoder->guts->residual_workspace[i][1] = 0;
337 encoder->guts->best_subframe[i] = 0;
338 }
339 for(i = 0; i < 2; i++) {
340 encoder->guts->residual_workspace_mid_side[i][0] = encoder->guts->residual_workspace_mid_side[i][1] = 0;
341 encoder->guts->best_subframe_mid_side[i] = 0;
342 }
343 for(i = 0; i < encoder->channels; i++) {
344 encoder->guts->subframe_workspace_ptr[i][0] = &encoder->guts->subframe_workspace[i][0];
345 encoder->guts->subframe_workspace_ptr[i][1] = &encoder->guts->subframe_workspace[i][1];
346 }
347 for(i = 0; i < 2; i++) {
348 encoder->guts->subframe_workspace_ptr_mid_side[i][0] = &encoder->guts->subframe_workspace_mid_side[i][0];
349 encoder->guts->subframe_workspace_ptr_mid_side[i][1] = &encoder->guts->subframe_workspace_mid_side[i][1];
350 }
Josh Coalsone77287e2001-01-20 01:27:55 +0000351 encoder->guts->abs_residual = 0;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000352 encoder->guts->current_frame_can_do_mid_side = true;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000353 encoder->guts->loose_mid_side_stereo_frames_exact = (double)encoder->sample_rate * 0.4 / (double)encoder->blocksize;
354 encoder->guts->loose_mid_side_stereo_frames = (unsigned)(encoder->guts->loose_mid_side_stereo_frames_exact + 0.5);
355 if(encoder->guts->loose_mid_side_stereo_frames == 0)
356 encoder->guts->loose_mid_side_stereo_frames = 1;
357 encoder->guts->loose_mid_side_stereo_frame_count = 0;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000358 encoder->guts->current_sample_number = 0;
359 encoder->guts->current_frame_number = 0;
360
361 if(!encoder_resize_buffers_(encoder, encoder->blocksize)) {
362 /* the above function sets the state for us in case of an error */
363 return encoder->state;
364 }
365 FLAC__bitbuffer_init(&encoder->guts->frame);
366 encoder->guts->write_callback = write_callback;
367 encoder->guts->metadata_callback = metadata_callback;
368 encoder->guts->client_data = client_data;
369
370 /*
371 * write the stream header
372 */
373 if(!FLAC__bitbuffer_clear(&encoder->guts->frame))
374 return encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
375
376 if(!FLAC__bitbuffer_write_raw_uint32(&encoder->guts->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN))
377 return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
378
379 encoder->guts->metadata.type = FLAC__METADATA_TYPE_ENCODING;
380 encoder->guts->metadata.is_last = true;
381 encoder->guts->metadata.length = FLAC__STREAM_METADATA_ENCODING_LENGTH;
382 encoder->guts->metadata.data.encoding.min_blocksize = encoder->blocksize; /* this encoder uses the same blocksize for the whole stream */
383 encoder->guts->metadata.data.encoding.max_blocksize = encoder->blocksize;
384 encoder->guts->metadata.data.encoding.min_framesize = 0; /* we don't know this yet; have to fill it in later */
385 encoder->guts->metadata.data.encoding.max_framesize = 0; /* we don't know this yet; have to fill it in later */
386 encoder->guts->metadata.data.encoding.sample_rate = encoder->sample_rate;
387 encoder->guts->metadata.data.encoding.channels = encoder->channels;
388 encoder->guts->metadata.data.encoding.bits_per_sample = encoder->bits_per_sample;
Josh Coalsoncbbbb5f2001-01-23 00:41:48 +0000389 encoder->guts->metadata.data.encoding.total_samples = encoder->total_samples_estimate; /* we will replace this later with the real total */
Josh Coalsonfa37f1c2001-01-12 23:55:11 +0000390 memset(encoder->guts->metadata.data.encoding.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
391 MD5Init(&encoder->guts->md5context);
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000392 if(!FLAC__add_metadata_block(&encoder->guts->metadata, &encoder->guts->frame))
393 return encoder->state = FLAC__ENCODER_FRAMING_ERROR;
394
395 assert(encoder->guts->frame.bits == 0); /* assert that we're byte-aligned before writing */
396 assert(encoder->guts->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
397 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)
398 return encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING;
399
Josh Coalsoncbbbb5f2001-01-23 00:41:48 +0000400 /* now that the metadata block is written, we can init this to an absurdly-high value... */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000401 encoder->guts->metadata.data.encoding.min_framesize = (1u << FLAC__STREAM_METADATA_ENCODING_MIN_FRAME_SIZE_LEN) - 1;
Josh Coalsoncbbbb5f2001-01-23 00:41:48 +0000402 /* ... and clear this to 0 */
403 encoder->guts->metadata.data.encoding.total_samples = 0;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000404
405 return encoder->state;
406}
407
408void FLAC__encoder_finish(FLAC__Encoder *encoder)
409{
Josh Coalson94e02cd2001-01-25 10:41:06 +0000410 unsigned i, channel;
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000411
412 assert(encoder != 0);
413 if(encoder->state == FLAC__ENCODER_UNINITIALIZED)
414 return;
415 if(encoder->guts->current_sample_number != 0) {
416 encoder->blocksize = encoder->guts->current_sample_number;
417 encoder_process_frame_(encoder, true); /* true => is last frame */
418 }
Josh Coalsonfa37f1c2001-01-12 23:55:11 +0000419 MD5Final(encoder->guts->metadata.data.encoding.md5sum, &encoder->guts->md5context);
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000420 encoder->guts->metadata_callback(encoder, &encoder->guts->metadata, encoder->guts->client_data);
421 if(encoder->guts != 0) {
422 for(i = 0; i < encoder->channels; i++) {
423 if(encoder->guts->integer_signal[i] != 0) {
424 free(encoder->guts->integer_signal[i]);
425 encoder->guts->integer_signal[i] = 0;
426 }
427 if(encoder->guts->real_signal[i] != 0) {
428 free(encoder->guts->real_signal[i]);
429 encoder->guts->real_signal[i] = 0;
430 }
431 }
432 for(i = 0; i < 2; i++) {
433 if(encoder->guts->integer_signal_mid_side[i] != 0) {
434 free(encoder->guts->integer_signal_mid_side[i]);
435 encoder->guts->integer_signal_mid_side[i] = 0;
436 }
437 if(encoder->guts->real_signal_mid_side[i] != 0) {
438 free(encoder->guts->real_signal_mid_side[i]);
439 encoder->guts->real_signal_mid_side[i] = 0;
440 }
441 }
Josh Coalson94e02cd2001-01-25 10:41:06 +0000442 for(channel = 0; channel < encoder->channels; channel++) {
443 for(i = 0; i < 2; i++) {
444 if(encoder->guts->residual_workspace[channel][i] != 0) {
445 free(encoder->guts->residual_workspace[channel][i]);
446 encoder->guts->residual_workspace[channel][i] = 0;
447 }
448 }
449 }
450 for(channel = 0; channel < 2; channel++) {
451 for(i = 0; i < 2; i++) {
452 if(encoder->guts->residual_workspace_mid_side[channel][i] != 0) {
453 free(encoder->guts->residual_workspace_mid_side[channel][i]);
454 encoder->guts->residual_workspace_mid_side[channel][i] = 0;
455 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000456 }
457 }
Josh Coalsone77287e2001-01-20 01:27:55 +0000458 if(encoder->guts->abs_residual != 0) {
459 free(encoder->guts->abs_residual);
460 encoder->guts->abs_residual = 0;
461 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000462 FLAC__bitbuffer_free(&encoder->guts->frame);
463 free(encoder->guts);
464 encoder->guts = 0;
465 }
466 encoder->state = FLAC__ENCODER_UNINITIALIZED;
467}
468
469bool FLAC__encoder_process(FLAC__Encoder *encoder, const int32 *buf[], unsigned samples)
470{
471 unsigned i, j, channel;
472 int32 x, mid, side;
473 const bool ms = encoder->do_mid_side_stereo && encoder->channels == 2;
474 const int32 min_side = -((int64)1 << (encoder->bits_per_sample-1));
475 const int32 max_side = ((int64)1 << (encoder->bits_per_sample-1)) - 1;
476
477 assert(encoder != 0);
478 assert(encoder->state == FLAC__ENCODER_OK);
479
480 j = 0;
481 do {
482 for(i = encoder->guts->current_sample_number; i < encoder->blocksize && j < samples; i++, j++) {
483 for(channel = 0; channel < encoder->channels; channel++) {
484 x = buf[channel][j];
485 encoder->guts->integer_signal[channel][i] = x;
486 encoder->guts->real_signal[channel][i] = (real)x;
487 }
488 if(ms && encoder->guts->current_frame_can_do_mid_side) {
489 side = buf[0][j] - buf[1][j];
490 if(side < min_side || side > max_side) {
491 encoder->guts->current_frame_can_do_mid_side = false;
492 }
493 else {
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000494 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 +0000495 encoder->guts->integer_signal_mid_side[0][i] = mid;
496 encoder->guts->integer_signal_mid_side[1][i] = side;
497 encoder->guts->real_signal_mid_side[0][i] = (real)mid;
498 encoder->guts->real_signal_mid_side[1][i] = (real)side;
499 }
500 }
501 encoder->guts->current_sample_number++;
502 }
503 if(i == encoder->blocksize) {
504 if(!encoder_process_frame_(encoder, false)) /* false => not last frame */
505 return false;
506 }
507 } while(j < samples);
508
509 return true;
510}
511
512/* 'samples' is channel-wide samples, e.g. for 1 second at 44100Hz, 'samples' = 44100 regardless of the number of channels */
513bool FLAC__encoder_process_interleaved(FLAC__Encoder *encoder, const int32 buf[], unsigned samples)
514{
515 unsigned i, j, k, channel;
516 int32 x, left = 0, mid, side;
517 const bool ms = encoder->do_mid_side_stereo && encoder->channels == 2;
518 const int32 min_side = -((int64)1 << (encoder->bits_per_sample-1));
519 const int32 max_side = ((int64)1 << (encoder->bits_per_sample-1)) - 1;
520
521 assert(encoder != 0);
522 assert(encoder->state == FLAC__ENCODER_OK);
523
524 j = k = 0;
525 do {
526 for(i = encoder->guts->current_sample_number; i < encoder->blocksize && j < samples; i++, j++, k++) {
527 for(channel = 0; channel < encoder->channels; channel++, k++) {
528 x = buf[k];
529 encoder->guts->integer_signal[channel][i] = x;
530 encoder->guts->real_signal[channel][i] = (real)x;
531 if(ms && encoder->guts->current_frame_can_do_mid_side) {
532 if(channel == 0) {
533 left = x;
534 }
535 else {
536 side = left - x;
537 if(side < min_side || side > max_side) {
538 encoder->guts->current_frame_can_do_mid_side = false;
539 }
540 else {
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000541 mid = (left + x) >> 1; /* NOTE: not the same as 'mid = (left + x) / 2' ! */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000542 encoder->guts->integer_signal_mid_side[0][i] = mid;
543 encoder->guts->integer_signal_mid_side[1][i] = side;
544 encoder->guts->real_signal_mid_side[0][i] = (real)mid;
545 encoder->guts->real_signal_mid_side[1][i] = (real)side;
546 }
547 }
548 }
549 }
550 encoder->guts->current_sample_number++;
551 }
552 if(i == encoder->blocksize) {
553 if(!encoder_process_frame_(encoder, false)) /* false => not last frame */
554 return false;
555 }
556 } while(j < samples);
557
558 return true;
559}
560
561bool encoder_process_frame_(FLAC__Encoder *encoder, bool is_last_frame)
562{
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000563 assert(encoder->state == FLAC__ENCODER_OK);
564
565 /*
Josh Coalsonfa37f1c2001-01-12 23:55:11 +0000566 * Accumulate raw signal to the MD5 signature
567 */
568 if(!FLAC__MD5Accumulate(&encoder->guts->md5context, encoder->guts->integer_signal, encoder->channels, encoder->blocksize, (encoder->bits_per_sample+7) / 8)) {
569 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
570 return false;
571 }
572
573 /*
Josh Coalson94e02cd2001-01-25 10:41:06 +0000574 * Process the frame header and subframes into the frame bitbuffer
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000575 */
Josh Coalson94e02cd2001-01-25 10:41:06 +0000576 if(!encoder_process_subframes_(encoder, is_last_frame)) {
577 /* the above function sets the state for us in case of an error */
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000578 return false;
579 }
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000580
581 /*
582 * Zero-pad the frame to a byte_boundary
583 */
Josh Coalson94e02cd2001-01-25 10:41:06 +0000584 if(!FLAC__bitbuffer_zero_pad_to_byte_boundary(&encoder->guts->frame)) {
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000585 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
586 return false;
587 }
588
589 /*
590 * Write it
591 */
Josh Coalson94e02cd2001-01-25 10:41:06 +0000592 assert(encoder->guts->frame.bits == 0); /* assert that we're byte-aligned before writing */
593 assert(encoder->guts->frame.total_consumed_bits == 0); /* assert that no reading of the buffer was done */
594 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 +0000595 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_WRITING;
596 return false;
597 }
598
599 /*
600 * Get ready for the next frame
601 */
602 encoder->guts->current_frame_can_do_mid_side = true;
603 encoder->guts->current_sample_number = 0;
604 encoder->guts->current_frame_number++;
605 encoder->guts->metadata.data.encoding.total_samples += (uint64)encoder->blocksize;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000606 encoder->guts->metadata.data.encoding.min_framesize = min(encoder->guts->frame.bytes, encoder->guts->metadata.data.encoding.min_framesize);
607 encoder->guts->metadata.data.encoding.max_framesize = max(encoder->guts->frame.bytes, encoder->guts->metadata.data.encoding.max_framesize);
Josh Coalsonbb7f6b92000-12-10 04:09:52 +0000608
609 return true;
610}
611
Josh Coalson94e02cd2001-01-25 10:41:06 +0000612bool encoder_process_subframes_(FLAC__Encoder *encoder, bool is_last_frame)
613{
614 FLAC__FrameHeader frame_header;
615 unsigned channel, max_partition_order;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000616 bool do_independent, do_mid_side;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000617
618 /*
619 * Calculate the max Rice partition order
620 */
621 if(is_last_frame) {
622 max_partition_order = 0;
623 }
624 else {
625 unsigned limit = 0, b = encoder->blocksize;
626 while(!(b & 1)) {
627 limit++;
628 b >>= 1;
629 }
630 max_partition_order = min(encoder->rice_optimization_level, limit);
631 }
632
633 /*
634 * Setup the frame
635 */
636 if(!FLAC__bitbuffer_clear(&encoder->guts->frame)) {
637 encoder->state = FLAC__ENCODER_MEMORY_ALLOCATION_ERROR;
638 return false;
639 }
640 frame_header.blocksize = encoder->blocksize;
641 frame_header.sample_rate = encoder->sample_rate;
642 frame_header.channels = encoder->channels;
643 frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
644 frame_header.bits_per_sample = encoder->bits_per_sample;
645 frame_header.number.frame_number = encoder->guts->current_frame_number;
646
647 /*
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000648 * Figure out what channel assignments to try
649 */
650 if(encoder->do_mid_side_stereo) {
651 if(encoder->loose_mid_side_stereo) {
652 if(encoder->guts->loose_mid_side_stereo_frame_count == 0) {
653 do_independent = true;
654 do_mid_side = true;
655 }
656 else {
657 do_independent = (encoder->guts->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
658 do_mid_side = !do_independent;
659 }
660 }
661 else {
662 do_independent = true;
663 do_mid_side = true;
664 }
665 }
666 else {
667 do_independent = true;
668 do_mid_side = false;
669 }
670 if(do_mid_side && !encoder->guts->current_frame_can_do_mid_side) {
671 do_independent = true;
672 do_mid_side = false;
673 }
674
675 assert(do_independent || do_mid_side);
676
677 /*
Josh Coalson94e02cd2001-01-25 10:41:06 +0000678 * First do a normal encoding pass of each independent channel
679 */
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000680 if(do_independent) {
681 for(channel = 0; channel < encoder->channels; channel++) {
682 if(!encoder_process_subframe_(encoder, max_partition_order, false, &frame_header, encoder->bits_per_sample, 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))
683 return false;
684 }
Josh Coalson94e02cd2001-01-25 10:41:06 +0000685 }
686
687 /*
688 * Now do mid and side channels if requested
689 */
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000690 if(do_mid_side) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000691 assert(encoder->channels == 2);
692
693 for(channel = 0; channel < 2; channel++) {
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000694 if(!encoder_process_subframe_(encoder, max_partition_order, false, &frame_header, encoder->bits_per_sample+(channel==0? 0:1), 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 +0000695 return false;
696 }
697 }
698
699 /*
700 * Compose the frame bitbuffer
701 */
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000702 if(do_mid_side) {
703 FLAC__ChannelAssignment channel_assignment;
704
Josh Coalson94e02cd2001-01-25 10:41:06 +0000705 assert(encoder->channels == 2);
706
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000707 if(encoder->loose_mid_side_stereo && encoder->guts->loose_mid_side_stereo_frame_count > 0) {
708 channel_assignment = (encoder->guts->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
709 }
710 else {
711 unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
712 unsigned min_bits;
713 FLAC__ChannelAssignment ca;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000714
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000715 assert(do_independent && do_mid_side);
716
717 /* We have to figure out which channel assignent results in the smallest frame */
718 bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->guts->best_subframe_bits [0] + encoder->guts->best_subframe_bits [1];
719 bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->guts->best_subframe_bits [0] + encoder->guts->best_subframe_bits_mid_side[1];
720 bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->guts->best_subframe_bits [1] + encoder->guts->best_subframe_bits_mid_side[1];
721 bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->guts->best_subframe_bits_mid_side[0] + encoder->guts->best_subframe_bits_mid_side[1];
722
723 for(channel_assignment = 0, min_bits = bits[0], ca = 1; ca <= 3; ca++) {
724 if(bits[ca] < min_bits) {
725 min_bits = bits[ca];
726 channel_assignment = ca;
727 }
Josh Coalson94e02cd2001-01-25 10:41:06 +0000728 }
729 }
730
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000731 frame_header.channel_assignment = channel_assignment;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000732
733 if(!FLAC__frame_add_header(&frame_header, encoder->streamable_subset, is_last_frame, &encoder->guts->frame)) {
734 encoder->state = FLAC__ENCODER_FRAMING_ERROR;
735 return false;
736 }
737
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000738 switch(channel_assignment) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000739 /* note that encoder_add_subframe_ sets the state for us in case of an error */
740 case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000741 if(!encoder_add_subframe_(encoder, &frame_header, encoder->bits_per_sample , &encoder->guts->subframe_workspace [0][encoder->guts->best_subframe [0]], &encoder->guts->frame))
Josh Coalson94e02cd2001-01-25 10:41:06 +0000742 return false;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000743 if(!encoder_add_subframe_(encoder, &frame_header, encoder->bits_per_sample , &encoder->guts->subframe_workspace [1][encoder->guts->best_subframe [1]], &encoder->guts->frame))
Josh Coalson94e02cd2001-01-25 10:41:06 +0000744 return false;
745 break;
746 case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000747 if(!encoder_add_subframe_(encoder, &frame_header, encoder->bits_per_sample , &encoder->guts->subframe_workspace [0][encoder->guts->best_subframe [0]], &encoder->guts->frame))
Josh Coalson94e02cd2001-01-25 10:41:06 +0000748 return false;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000749 if(!encoder_add_subframe_(encoder, &frame_header, encoder->bits_per_sample+1, &encoder->guts->subframe_workspace_mid_side[1][encoder->guts->best_subframe_mid_side[1]], &encoder->guts->frame))
Josh Coalson94e02cd2001-01-25 10:41:06 +0000750 return false;
751 break;
752 case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000753 if(!encoder_add_subframe_(encoder, &frame_header, encoder->bits_per_sample+1, &encoder->guts->subframe_workspace_mid_side[1][encoder->guts->best_subframe_mid_side[1]], &encoder->guts->frame))
Josh Coalson94e02cd2001-01-25 10:41:06 +0000754 return false;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000755 if(!encoder_add_subframe_(encoder, &frame_header, encoder->bits_per_sample , &encoder->guts->subframe_workspace [1][encoder->guts->best_subframe [1]], &encoder->guts->frame))
Josh Coalson94e02cd2001-01-25 10:41:06 +0000756 return false;
757 break;
758 case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000759 if(!encoder_add_subframe_(encoder, &frame_header, encoder->bits_per_sample , &encoder->guts->subframe_workspace_mid_side[0][encoder->guts->best_subframe_mid_side[0]], &encoder->guts->frame))
Josh Coalson94e02cd2001-01-25 10:41:06 +0000760 return false;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000761 if(!encoder_add_subframe_(encoder, &frame_header, encoder->bits_per_sample+1, &encoder->guts->subframe_workspace_mid_side[1][encoder->guts->best_subframe_mid_side[1]], &encoder->guts->frame))
Josh Coalson94e02cd2001-01-25 10:41:06 +0000762 return false;
763 break;
764 default:
765 assert(0);
766 }
767 }
768 else {
769 if(!FLAC__frame_add_header(&frame_header, encoder->streamable_subset, is_last_frame, &encoder->guts->frame)) {
770 encoder->state = FLAC__ENCODER_FRAMING_ERROR;
771 return false;
772 }
773
774 for(channel = 0; channel < encoder->channels; channel++) {
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000775 if(!encoder_add_subframe_(encoder, &frame_header, encoder->bits_per_sample, &encoder->guts->subframe_workspace[channel][encoder->guts->best_subframe[channel]], &encoder->guts->frame)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000776 /* the above function sets the state for us in case of an error */
777 return false;
778 }
779 }
780 }
781
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000782 if(encoder->loose_mid_side_stereo) {
783 encoder->guts->loose_mid_side_stereo_frame_count++;
784 if(encoder->guts->loose_mid_side_stereo_frame_count >= encoder->guts->loose_mid_side_stereo_frames)
785 encoder->guts->loose_mid_side_stereo_frame_count = 0;
786 }
787
788 encoder->guts->last_channel_assignment = frame_header.channel_assignment;
789
Josh Coalson94e02cd2001-01-25 10:41:06 +0000790 return true;
791}
792
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000793bool encoder_process_subframe_(FLAC__Encoder *encoder, unsigned max_partition_order, bool verbatim_only, const FLAC__FrameHeader *frame_header, unsigned bits_per_sample, 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 +0000794{
795 real fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
796 real lpc_residual_bits_per_sample;
797 real autoc[FLAC__MAX_LPC_ORDER+1];
798 real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER];
799 real lpc_error[FLAC__MAX_LPC_ORDER];
800 unsigned min_lpc_order, max_lpc_order, lpc_order;
801 unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
802 unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
803 unsigned rice_parameter;
804 unsigned _candidate_bits, _best_bits;
805 unsigned _best_subframe;
806
807 /* verbatim subframe is the baseline against which we measure other compressed subframes */
808 _best_subframe = 0;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000809 _best_bits = encoder_evaluate_verbatim_subframe_(integer_signal, frame_header->blocksize, bits_per_sample, subframe[_best_subframe]);
Josh Coalson94e02cd2001-01-25 10:41:06 +0000810
811 if(!verbatim_only && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
812 /* check for constant subframe */
813 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);
814 if(fixed_residual_bits_per_sample[1] == 0.0) {
815 /* the above means integer_signal+FLAC__MAX_FIXED_ORDER is constant, now we just have to check the warmup samples */
816 unsigned i, signal_is_constant = true;
817 for(i = 1; i <= FLAC__MAX_FIXED_ORDER; i++) {
818 if(integer_signal[0] != integer_signal[i]) {
819 signal_is_constant = false;
820 break;
821 }
822 }
823 if(signal_is_constant) {
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000824 _candidate_bits = encoder_evaluate_constant_subframe_(integer_signal[0], bits_per_sample, subframe[!_best_subframe]);
Josh Coalson94e02cd2001-01-25 10:41:06 +0000825 if(_candidate_bits < _best_bits) {
826 _best_subframe = !_best_subframe;
827 _best_bits = _candidate_bits;
828 }
829 }
830 }
831 else {
832 /* encode fixed */
833 if(encoder->do_exhaustive_model_search) {
834 min_fixed_order = 0;
835 max_fixed_order = FLAC__MAX_FIXED_ORDER;
836 }
837 else {
838 min_fixed_order = max_fixed_order = guess_fixed_order;
839 }
840 for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000841 if(fixed_residual_bits_per_sample[fixed_order] >= (real)bits_per_sample)
Josh Coalson94e02cd2001-01-25 10:41:06 +0000842 continue; /* don't even try */
Josh Coalson46f2ae82001-02-08 00:27:21 +0000843 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 */
844 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
Josh Coalson94e02cd2001-01-25 10:41:06 +0000845 if(rice_parameter >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN))
846 rice_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000847 _candidate_bits = encoder_evaluate_fixed_subframe_(integer_signal, residual[!_best_subframe], encoder->guts->abs_residual, frame_header->blocksize, bits_per_sample, fixed_order, rice_parameter, max_partition_order, subframe[!_best_subframe]);
Josh Coalson94e02cd2001-01-25 10:41:06 +0000848 if(_candidate_bits < _best_bits) {
849 _best_subframe = !_best_subframe;
850 _best_bits = _candidate_bits;
851 }
852 }
853
854 /* encode lpc */
855 if(encoder->max_lpc_order > 0) {
856 if(encoder->max_lpc_order >= frame_header->blocksize)
857 max_lpc_order = frame_header->blocksize-1;
858 else
859 max_lpc_order = encoder->max_lpc_order;
860 if(max_lpc_order > 0) {
861 FLAC__lpc_compute_autocorrelation(real_signal, frame_header->blocksize, max_lpc_order+1, autoc);
862 FLAC__lpc_compute_lp_coefficients(autoc, max_lpc_order, lp_coeff, lpc_error);
863 if(encoder->do_exhaustive_model_search) {
864 min_lpc_order = 1;
865 }
866 else {
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000867 unsigned guess_lpc_order = FLAC__lpc_compute_best_order(lpc_error, max_lpc_order, frame_header->blocksize, bits_per_sample);
Josh Coalson94e02cd2001-01-25 10:41:06 +0000868 min_lpc_order = max_lpc_order = guess_lpc_order;
869 }
870 if(encoder->do_qlp_coeff_prec_search) {
871 min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000872 max_qlp_coeff_precision = 32 - bits_per_sample - 1;
Josh Coalson94e02cd2001-01-25 10:41:06 +0000873 }
874 else {
875 min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->qlp_coeff_precision;
876 }
877 for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
Josh Coalson46f2ae82001-02-08 00:27:21 +0000878 lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000879 if(lpc_residual_bits_per_sample >= (real)bits_per_sample)
Josh Coalson94e02cd2001-01-25 10:41:06 +0000880 continue; /* don't even try */
Josh Coalson46f2ae82001-02-08 00:27:21 +0000881 rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
882 rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
Josh Coalson94e02cd2001-01-25 10:41:06 +0000883 if(rice_parameter >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN))
884 rice_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
885 for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000886 _candidate_bits = encoder_evaluate_lpc_subframe_(integer_signal, residual[!_best_subframe], encoder->guts->abs_residual, lp_coeff[lpc_order-1], frame_header->blocksize, bits_per_sample, lpc_order, qlp_coeff_precision, rice_parameter, max_partition_order, subframe[!_best_subframe]);
Josh Coalson94e02cd2001-01-25 10:41:06 +0000887 if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
888 if(_candidate_bits < _best_bits) {
889 _best_subframe = !_best_subframe;
890 _best_bits = _candidate_bits;
891 }
892 }
893 }
894 }
895 }
896 }
897 }
898 }
899
900 *best_subframe = _best_subframe;
901 *best_bits = _best_bits;
902
903 return true;
904}
905
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000906bool encoder_add_subframe_(FLAC__Encoder *encoder, const FLAC__FrameHeader *frame_header, unsigned bits_per_sample, const FLAC__Subframe *subframe, FLAC__BitBuffer *frame)
Josh Coalson94e02cd2001-01-25 10:41:06 +0000907{
908 switch(subframe->type) {
909 case FLAC__SUBFRAME_TYPE_CONSTANT:
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000910 if(!FLAC__subframe_add_constant(&(subframe->data.constant), bits_per_sample, frame)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000911 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
912 return false;
913 }
914 break;
915 case FLAC__SUBFRAME_TYPE_FIXED:
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000916 if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), frame_header->blocksize - subframe->data.fixed.order, bits_per_sample, frame)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000917 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
918 return false;
919 }
920 break;
921 case FLAC__SUBFRAME_TYPE_LPC:
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000922 if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), frame_header->blocksize - subframe->data.lpc.order, bits_per_sample, frame)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000923 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
924 return false;
925 }
926 break;
927 case FLAC__SUBFRAME_TYPE_VERBATIM:
Josh Coalsonb5e60e52001-01-28 09:27:27 +0000928 if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), frame_header->blocksize, bits_per_sample, frame)) {
Josh Coalson94e02cd2001-01-25 10:41:06 +0000929 encoder->state = FLAC__ENCODER_FATAL_ERROR_WHILE_ENCODING;
930 return false;
931 }
932 break;
933 default:
934 assert(0);
935 }
936
937 return true;
938}
939
940unsigned encoder_evaluate_constant_subframe_(const int32 signal, unsigned bits_per_sample, FLAC__Subframe *subframe)
941{
942 subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
943 subframe->data.constant.value = signal;
944
945 return FLAC__SUBFRAME_TYPE_LEN + bits_per_sample;
946}
947
948unsigned encoder_evaluate_fixed_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], unsigned blocksize, unsigned bits_per_sample, unsigned order, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe)
949{
950 unsigned i, residual_bits;
951 const unsigned residual_samples = blocksize - order;
952
953 FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
954
955 subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
956
957 subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
958 subframe->data.fixed.residual = residual;
959
960 residual_bits = encoder_find_best_partition_order_(residual, abs_residual, 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);
961
962 subframe->data.fixed.order = order;
963 for(i = 0; i < order; i++)
964 subframe->data.fixed.warmup[i] = signal[i];
965
966 return FLAC__SUBFRAME_TYPE_LEN + (order * bits_per_sample) + residual_bits;
967}
968
969unsigned encoder_evaluate_lpc_subframe_(const int32 signal[], int32 residual[], uint32 abs_residual[], const real lp_coeff[], unsigned blocksize, unsigned bits_per_sample, unsigned order, unsigned qlp_coeff_precision, unsigned rice_parameter, unsigned max_partition_order, FLAC__Subframe *subframe)
970{
971 int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
972 unsigned i, residual_bits;
973 int quantization, ret;
974 const unsigned residual_samples = blocksize - order;
975
976 ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, bits_per_sample, qlp_coeff, &quantization);
977 if(ret != 0)
978 return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
979
980 FLAC__lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
981
982 subframe->type = FLAC__SUBFRAME_TYPE_LPC;
983
984 subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
985 subframe->data.lpc.residual = residual;
986
987 residual_bits = encoder_find_best_partition_order_(residual, abs_residual, 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);
988
989 subframe->data.lpc.order = order;
990 subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
991 subframe->data.lpc.quantization_level = quantization;
992 memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(int32)*FLAC__MAX_LPC_ORDER);
993 for(i = 0; i < order; i++)
994 subframe->data.lpc.warmup[i] = signal[i];
995
996 return FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN + FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN + (order * (qlp_coeff_precision + bits_per_sample)) + residual_bits;
997}
998
999unsigned encoder_evaluate_verbatim_subframe_(const int32 signal[], unsigned blocksize, unsigned bits_per_sample, FLAC__Subframe *subframe)
1000{
1001 subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
1002
1003 subframe->data.verbatim.data = signal;
1004
1005 return FLAC__SUBFRAME_TYPE_LEN + (blocksize * bits_per_sample);
1006}
1007
1008unsigned encoder_find_best_partition_order_(const int32 residual[], uint32 abs_residual[], unsigned residual_samples, unsigned predictor_order, unsigned rice_parameter, unsigned max_partition_order, unsigned *best_partition_order, unsigned best_parameters[])
1009{
1010 unsigned residual_bits, best_residual_bits = 0;
1011 unsigned i, partition_order;
1012 unsigned best_parameters_index = 0, parameters[2][1 << FLAC__MAX_RICE_PARTITION_ORDER];
1013 int32 r;
1014
1015 /* compute the abs(residual) for use later */
1016 for(i = 0; i < residual_samples; i++) {
1017 r = residual[i];
1018 abs_residual[i] = (uint32)(r<0? -r : r);
1019 }
1020
1021 for(partition_order = 0; partition_order <= max_partition_order; partition_order++) {
1022 if(!encoder_set_partitioned_rice_(abs_residual, residual_samples, predictor_order, rice_parameter, partition_order, parameters[!best_parameters_index], &residual_bits)) {
1023 assert(best_residual_bits != 0);
1024 break;
1025 }
1026 if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
1027 best_residual_bits = residual_bits;
1028 *best_partition_order = partition_order;
1029 best_parameters_index = !best_parameters_index;
1030 }
1031 }
1032 memcpy(best_parameters, parameters[best_parameters_index], sizeof(unsigned)*(1<<(*best_partition_order)));
1033
1034 return best_residual_bits;
1035}
1036
Josh Coalson94e02cd2001-01-25 10:41:06 +00001037#ifdef ESTIMATE_RICE_BITS
1038#undef ESTIMATE_RICE_BITS
1039#endif
1040#define ESTIMATE_RICE_BITS(value, parameter) ((value) >> (parameter))
1041
1042bool encoder_set_partitioned_rice_(const uint32 abs_residual[], const unsigned residual_samples, const unsigned predictor_order, const unsigned rice_parameter, const unsigned partition_order, unsigned parameters[], unsigned *bits)
1043{
1044 unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
1045
1046 if(partition_order == 0) {
1047 unsigned i;
1048#ifdef ESTIMATE_RICE_BITS
1049 const unsigned rice_parameter_estimate = rice_parameter-1;
1050 bits_ += (1+rice_parameter) * residual_samples;
1051#endif
1052 parameters[0] = rice_parameter;
1053 bits_ += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1054 for(i = 0; i < residual_samples; i++)
1055#ifdef ESTIMATE_RICE_BITS
1056 bits_ += ESTIMATE_RICE_BITS(abs_residual[i], rice_parameter_estimate);
1057#else
1058 bits_ += FLAC__bitbuffer_rice_bits(residual[i], rice_parameter);
1059#endif
1060 }
1061 else {
1062 unsigned i, j, k = 0, k_last = 0;
1063 unsigned mean, parameter, partition_samples;
1064 const unsigned max_parameter = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN) - 1;
1065 for(i = 0; i < (1u<<partition_order); i++) {
1066 partition_samples = (residual_samples+predictor_order) >> partition_order;
1067 if(i == 0) {
1068 if(partition_samples <= predictor_order)
1069 return false;
1070 else
1071 partition_samples -= predictor_order;
1072 }
1073 mean = partition_samples >> 1;
1074 for(j = 0; j < partition_samples; j++, k++)
1075 mean += abs_residual[k];
1076 mean /= partition_samples;
1077 /* calc parameter = floor(log2(mean)) + 1 */
1078 parameter = 0;
1079 while(mean) {
1080 parameter++;
1081 mean >>= 1;
1082 }
1083 if(parameter > max_parameter)
1084 parameter = max_parameter;
1085 parameters[i] = parameter;
1086 bits_ += FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
1087#ifdef ESTIMATE_RICE_BITS
1088 bits_ += (1+parameter) * partition_samples;
1089 --parameter;
1090#endif
1091 for(j = k_last; j < k; j++)
1092#ifdef ESTIMATE_RICE_BITS
1093 bits_ += ESTIMATE_RICE_BITS(abs_residual[j], parameter);
1094#else
1095 bits_ += FLAC__bitbuffer_rice_bits(residual[j], parameter);
1096#endif
1097 k_last = k;
1098 }
1099 }
1100
1101 *bits = bits_;
1102 return true;
1103}