code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
/*
* wrppm.c
*
* Copyright (C) 1991-1996, Thomas G. Lane.
* Modified 2009 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains routines to write output images in PPM/PGM format.
* The extended 2-byte-per-sample raw PPM/PGM formats are supported.
* The PBMPLUS library is NOT required to compile this software
* (but it is highly useful as a set of PPM image manipulation programs).
*
* These routines may need modification for non-Unix environments or
* specialized applications. As they stand, they assume output to
* an ordinary stdio stream.
*/
#include "lcd.h"
#include "usart.h"
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#ifdef PPM_SUPPORTED
/*
* For 12-bit JPEG data, we either downscale the values to 8 bits
* (to write standard byte-per-sample PPM/PGM files), or output
* nonstandard word-per-sample PPM/PGM files. Downscaling is done
* if PPM_NORAWWORD is defined (this can be done in the Makefile
* or in jconfig.h).
* (When the core library supports data precision reduction, a cleaner
* implementation will be to ask for that instead.)
*/
#if BITS_IN_JSAMPLE == 8
#define PUTPPMSAMPLE(ptr,v) *ptr++ = (char) (v)
#define BYTESPERSAMPLE 1
#define PPM_MAXVAL 255
#else
#ifdef PPM_NORAWWORD
#define PUTPPMSAMPLE(ptr,v) *ptr++ = (char) ((v) >> (BITS_IN_JSAMPLE-8))
#define BYTESPERSAMPLE 1
#define PPM_MAXVAL 255
#else
/* The word-per-sample format always puts the MSB first. */
#define PUTPPMSAMPLE(ptr,v) \
{ register int val_ = v; \
*ptr++ = (char) ((val_ >> 8) & 0xFF); \
*ptr++ = (char) (val_ & 0xFF); \
}
#define BYTESPERSAMPLE 2
#define PPM_MAXVAL ((1<<BITS_IN_JSAMPLE)-1)
#endif
#endif
/*
* When JSAMPLE is the same size as char, we can just fwrite() the
* decompressed data to the PPM or PGM file. On PCs, in order to make this
* work the output buffer must be allocated in near data space, because we are
* assuming small-data memory model wherein fwrite() can't reach far memory.
* If you need to process very wide images on a PC, you might have to compile
* in large-memory model, or else replace fwrite() with a putc() loop ---
* which will be much slower.
*/
/* Private version of data destination object */
typedef struct {
struct djpeg_dest_struct pub; /* public fields */
/* Usually these two pointers point to the same place: */
char *iobuffer; /* fwrite's I/O buffer */
JSAMPROW pixrow; /* decompressor output buffer */
size_t buffer_width; /* width of I/O buffer */
JDIMENSION samples_per_row; /* JSAMPLEs per output row */
} ppm_dest_struct;
typedef ppm_dest_struct * ppm_dest_ptr;
/*
* Write some pixel data.
* In this module rows_supplied will always be 1.
*
* put_pixel_rows handles the "normal" 8-bit case where the decompressor
* output buffer is physically the same as the fwrite buffer.
*/
METHODDEF(void)
put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied)
{
// ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
// (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
}
/*
* This code is used when we have to copy the data and apply a pixel
* format translation. Typically this only happens in 12-bit mode.
*/
METHODDEF(void)
copy_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied)
{
if(cinfo->useMergedUpsampling) return;
ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
register char * bufferptr;
register JSAMPROW ptr;
register JDIMENSION col;
ptr = dest->pub.buffer[0];
bufferptr = dest->iobuffer;
for (col = dest->samples_per_row; col > 0; col--) {
PUTPPMSAMPLE(bufferptr, GETJSAMPLE(*ptr++));
}
// (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
}
/*
* Write some pixel data when color quantization is in effect.
* We have to demap the color index values to straight data.
*/
METHODDEF(void)
put_demapped_rgb (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied)
{
if(cinfo->useMergedUpsampling) return;
ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
register char * bufferptr;
register int pixval;
register JSAMPROW ptr;
register JSAMPROW color_map0 = cinfo->colormap[0];
register JSAMPROW color_map1 = cinfo->colormap[1];
register JSAMPROW color_map2 = cinfo->colormap[2];
register JDIMENSION col;
ptr = dest->pub.buffer[0];
bufferptr = dest->iobuffer;
for (col = cinfo->output_width; col > 0; col--) {
pixval = GETJSAMPLE(*ptr++);
PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map0[pixval]));
PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map1[pixval]));
PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map2[pixval]));
}
// (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
}
METHODDEF(void)
put_demapped_gray (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied)
{
if(cinfo->useMergedUpsampling) return;
ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
register char * bufferptr;
register JSAMPROW ptr;
register JSAMPROW color_map = cinfo->colormap[0];
register JDIMENSION col;
ptr = dest->pub.buffer[0];
bufferptr = dest->iobuffer;
for (col = cinfo->output_width; col > 0; col--) {
PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map[GETJSAMPLE(*ptr++)]));
}
// (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
}
/*
* Startup: write the file header.
*/
METHODDEF(void)
start_output_ppm (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
{
// ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
//
// /* Emit file header */
// switch (cinfo->out_color_space) {
// case JCS_GRAYSCALE:
// /* emit header for raw PGM format */
///* fprintf(dest->pub.output_file, "P5\n%ld %ld\n%d\n",
// (long) cinfo->output_width, (long) cinfo->output_height,
// PPM_MAXVAL);*/
// break;
// case JCS_RGB:
// /* emit header for raw PPM format */
///* fprintf(dest->pub.output_file, "P6\n%ld %ld\n%d\n",
// (long) cinfo->output_width, (long) cinfo->output_height,
// PPM_MAXVAL);*/
// break;
// default:
// ERREXIT(cinfo, JERR_PPM_COLORSPACE);
// }
}
/*
* Finish up at the end of the file.
*/
METHODDEF(void)
finish_output_ppm (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
{
/* Make sure we wrote the output file OK */
// fflush(dinfo->output_file);
// if (ferror(dinfo->output_file))
// ERREXIT(cinfo, JERR_FILE_WRITE);
}
/*
* The module selection routine for PPM format output.
*/
GLOBAL(djpeg_dest_ptr)
jinit_write_ppm (j_decompress_ptr cinfo)
{
ppm_dest_ptr dest;
/* Create module interface object, fill in method pointers */
dest = (ppm_dest_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(ppm_dest_struct));
dest->pub.start_output = start_output_ppm;
dest->pub.finish_output = finish_output_ppm;
/* Calculate output image dimensions so we can allocate space */
jpeg_calc_output_dimensions(cinfo);
/* Create physical I/O buffer. Note we make this near on a PC. */
dest->samples_per_row = cinfo->output_width * cinfo->out_color_components;
dest->buffer_width = dest->samples_per_row * (BYTESPERSAMPLE * SIZEOF(char));
dest->iobuffer = (char *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo, JPOOL_IMAGE, dest->buffer_width);
if (cinfo->quantize_colors || BITS_IN_JSAMPLE != 8 ||
SIZEOF(JSAMPLE) != SIZEOF(char)) {
/* When quantizing, we need an output buffer for colormap indexes
* that's separate from the physical I/O buffer. We also need a
* separate buffer if pixel format translation must take place.
*/
dest->pub.buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE,
cinfo->output_width * cinfo->output_components, (JDIMENSION) 1);
dest->pub.buffer_height = 1;
if (! cinfo->quantize_colors)
dest->pub.put_pixel_rows = copy_pixel_rows;
else if (cinfo->out_color_space == JCS_GRAYSCALE)
dest->pub.put_pixel_rows = put_demapped_gray;
else
dest->pub.put_pixel_rows = put_demapped_rgb;
} else {
/* We will fwrite() directly from decompressor output buffer. */
/* Synthesize a JSAMPARRAY pointer structure */
/* Cast here implies near->far pointer conversion on PCs */
dest->pixrow = (JSAMPROW) dest->iobuffer;
dest->pub.buffer = & dest->pixrow;
dest->pub.buffer_height = 1;
dest->pub.put_pixel_rows = put_pixel_rows;
}
return (djpeg_dest_ptr) dest;
}
#endif /* PPM_SUPPORTED */
|
1137519-player
|
jpeg-7/wrppm.c
|
C
|
lgpl
| 8,589
|
/*
* jdpostct.c
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains the decompression postprocessing controller.
* This controller manages the upsampling, color conversion, and color
* quantization/reduction steps; specifically, it controls the buffering
* between upsample/color conversion and color quantization/reduction.
*
* If no color quantization/reduction is required, then this module has no
* work to do, and it just hands off to the upsample/color conversion code.
* An integrated upsample/convert/quantize process would replace this module
* entirely.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/* Private buffer controller object */
typedef struct {
struct jpeg_d_post_controller pub; /* public fields */
/* Color quantization source buffer: this holds output data from
* the upsample/color conversion step to be passed to the quantizer.
* For two-pass color quantization, we need a full-image buffer;
* for one-pass operation, a strip buffer is sufficient.
*/
jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
JDIMENSION strip_height; /* buffer size in rows */
/* for two-pass mode only: */
JDIMENSION starting_row; /* row # of first row in current strip */
JDIMENSION next_row; /* index of next row to fill/empty in strip */
} my_post_controller;
typedef my_post_controller * my_post_ptr;
/* Forward declarations */
METHODDEF(void) post_process_1pass
JPP((j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
JDIMENSION in_row_groups_avail,
JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
JDIMENSION out_rows_avail));
#ifdef QUANT_2PASS_SUPPORTED
METHODDEF(void) post_process_prepass
JPP((j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
JDIMENSION in_row_groups_avail,
JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
JDIMENSION out_rows_avail));
METHODDEF(void) post_process_2pass
JPP((j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
JDIMENSION in_row_groups_avail,
JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
JDIMENSION out_rows_avail));
#endif
/*
* Initialize for a processing pass.
*/
METHODDEF(void)
start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
{
my_post_ptr post = (my_post_ptr) cinfo->post;
switch (pass_mode) {
case JBUF_PASS_THRU:
if (cinfo->quantize_colors) {
/* Single-pass processing with color quantization. */
post->pub.post_process_data = post_process_1pass;
/* We could be doing buffered-image output before starting a 2-pass
* color quantization; in that case, jinit_d_post_controller did not
* allocate a strip buffer. Use the virtual-array buffer as workspace.
*/
if (post->buffer == NULL) {
post->buffer = (*cinfo->mem->access_virt_sarray)
((j_common_ptr) cinfo, post->whole_image,
(JDIMENSION) 0, post->strip_height, TRUE);
}
} else {
/* For single-pass processing without color quantization,
* I have no work to do; just call the upsampler directly.
*/
post->pub.post_process_data = cinfo->upsample->upsample;
}
break;
#ifdef QUANT_2PASS_SUPPORTED
case JBUF_SAVE_AND_PASS:
/* First pass of 2-pass quantization */
if (post->whole_image == NULL)
ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
post->pub.post_process_data = post_process_prepass;
break;
case JBUF_CRANK_DEST:
/* Second pass of 2-pass quantization */
if (post->whole_image == NULL)
ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
post->pub.post_process_data = post_process_2pass;
break;
#endif /* QUANT_2PASS_SUPPORTED */
default:
ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
break;
}
post->starting_row = post->next_row = 0;
}
/*
* Process some data in the one-pass (strip buffer) case.
* This is used for color precision reduction as well as one-pass quantization.
*/
METHODDEF(void)
post_process_1pass (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
JDIMENSION in_row_groups_avail,
JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
JDIMENSION out_rows_avail)
{
my_post_ptr post = (my_post_ptr) cinfo->post;
JDIMENSION num_rows, max_rows;
/* Fill the buffer, but not more than what we can dump out in one go. */
/* Note we rely on the upsampler to detect bottom of image. */
max_rows = out_rows_avail - *out_row_ctr;
if (max_rows > post->strip_height)
max_rows = post->strip_height;
num_rows = 0;
(*cinfo->upsample->upsample) (cinfo,
input_buf, in_row_group_ctr, in_row_groups_avail,
post->buffer, &num_rows, max_rows);
/* Quantize and emit data. */
(*cinfo->cquantize->color_quantize) (cinfo,
post->buffer, output_buf + *out_row_ctr, (int) num_rows);
*out_row_ctr += num_rows;
}
#ifdef QUANT_2PASS_SUPPORTED
/*
* Process some data in the first pass of 2-pass quantization.
*/
METHODDEF(void)
post_process_prepass (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
JDIMENSION in_row_groups_avail,
JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
JDIMENSION out_rows_avail)
{
my_post_ptr post = (my_post_ptr) cinfo->post;
JDIMENSION old_next_row, num_rows;
/* Reposition virtual buffer if at start of strip. */
if (post->next_row == 0) {
post->buffer = (*cinfo->mem->access_virt_sarray)
((j_common_ptr) cinfo, post->whole_image,
post->starting_row, post->strip_height, TRUE);
}
/* Upsample some data (up to a strip height's worth). */
old_next_row = post->next_row;
(*cinfo->upsample->upsample) (cinfo,
input_buf, in_row_group_ctr, in_row_groups_avail,
post->buffer, &post->next_row, post->strip_height);
/* Allow quantizer to scan new data. No data is emitted, */
/* but we advance out_row_ctr so outer loop can tell when we're done. */
if (post->next_row > old_next_row) {
num_rows = post->next_row - old_next_row;
(*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
(JSAMPARRAY) NULL, (int) num_rows);
*out_row_ctr += num_rows;
}
/* Advance if we filled the strip. */
if (post->next_row >= post->strip_height) {
post->starting_row += post->strip_height;
post->next_row = 0;
}
}
/*
* Process some data in the second pass of 2-pass quantization.
*/
METHODDEF(void)
post_process_2pass (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
JDIMENSION in_row_groups_avail,
JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
JDIMENSION out_rows_avail)
{
my_post_ptr post = (my_post_ptr) cinfo->post;
JDIMENSION num_rows, max_rows;
/* Reposition virtual buffer if at start of strip. */
if (post->next_row == 0) {
post->buffer = (*cinfo->mem->access_virt_sarray)
((j_common_ptr) cinfo, post->whole_image,
post->starting_row, post->strip_height, FALSE);
}
/* Determine number of rows to emit. */
num_rows = post->strip_height - post->next_row; /* available in strip */
max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
if (num_rows > max_rows)
num_rows = max_rows;
/* We have to check bottom of image here, can't depend on upsampler. */
max_rows = cinfo->output_height - post->starting_row;
if (num_rows > max_rows)
num_rows = max_rows;
/* Quantize and emit data. */
(*cinfo->cquantize->color_quantize) (cinfo,
post->buffer + post->next_row, output_buf + *out_row_ctr,
(int) num_rows);
*out_row_ctr += num_rows;
/* Advance if we filled the strip. */
post->next_row += num_rows;
if (post->next_row >= post->strip_height) {
post->starting_row += post->strip_height;
post->next_row = 0;
}
}
#endif /* QUANT_2PASS_SUPPORTED */
/*
* Initialize postprocessing controller.
*/
GLOBAL(void)
jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
{
my_post_ptr post;
post = (my_post_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(my_post_controller));
cinfo->post = (struct jpeg_d_post_controller *) post;
post->pub.start_pass = start_pass_dpost;
post->whole_image = NULL; /* flag for no virtual arrays */
post->buffer = NULL; /* flag for no strip buffer */
/* Create the quantization buffer, if needed */
if (cinfo->quantize_colors) {
/* The buffer strip height is max_v_samp_factor, which is typically
* an efficient number of rows for upsampling to return.
* (In the presence of output rescaling, we might want to be smarter?)
*/
post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
if (need_full_buffer) {
/* Two-pass color quantization: need full-image storage. */
/* We round up the number of rows to a multiple of the strip height. */
#ifdef QUANT_2PASS_SUPPORTED
post->whole_image = (*cinfo->mem->request_virt_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
cinfo->output_width * cinfo->out_color_components,
(JDIMENSION) jround_up((long) cinfo->output_height,
(long) post->strip_height),
post->strip_height);
#else
ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
#endif /* QUANT_2PASS_SUPPORTED */
} else {
/* One-pass color quantization: just make a strip buffer. */
post->buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE,
cinfo->output_width * cinfo->out_color_components,
post->strip_height);
}
}
}
|
1137519-player
|
jpeg-7/jdpostct.c
|
C
|
lgpl
| 9,723
|
/*
* cjpeg.c
*
* Copyright (C) 1991-1998, Thomas G. Lane.
* Modified 2003-2008 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains a command-line user interface for the JPEG compressor.
* It should work on any system with Unix- or MS-DOS-style command lines.
*
* Two different command line styles are permitted, depending on the
* compile-time switch TWO_FILE_COMMANDLINE:
* cjpeg [options] inputfile outputfile
* cjpeg [options] [inputfile]
* In the second style, output is always to standard output, which you'd
* normally redirect to a file or pipe to some other program. Input is
* either from a named file or from standard input (typically redirected).
* The second style is convenient on Unix but is unhelpful on systems that
* don't support pipes. Also, you MUST use the first style if your system
* doesn't do binary I/O to stdin/stdout.
* To simplify script writing, the "-outfile" switch is provided. The syntax
* cjpeg [options] -outfile outputfile inputfile
* works regardless of which command line style is used.
*/
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#include "jversion.h" /* for version message */
#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
#ifdef __MWERKS__
#include <SIOUX.h> /* Metrowerks needs this */
#include <console.h> /* ... and this */
#endif
#ifdef THINK_C
#include <console.h> /* Think declares it here */
#endif
#endif
/* Create the add-on message string table. */
#define JMESSAGE(code,string) string ,
static const char * const cdjpeg_message_table[] = {
#include "cderror.h"
NULL
};
/*
* This routine determines what format the input file is,
* and selects the appropriate input-reading module.
*
* To determine which family of input formats the file belongs to,
* we may look only at the first byte of the file, since C does not
* guarantee that more than one character can be pushed back with ungetc.
* Looking at additional bytes would require one of these approaches:
* 1) assume we can fseek() the input file (fails for piped input);
* 2) assume we can push back more than one character (works in
* some C implementations, but unportable);
* 3) provide our own buffering (breaks input readers that want to use
* stdio directly, such as the RLE library);
* or 4) don't put back the data, and modify the input_init methods to assume
* they start reading after the start of file (also breaks RLE library).
* #1 is attractive for MS-DOS but is untenable on Unix.
*
* The most portable solution for file types that can't be identified by their
* first byte is to make the user tell us what they are. This is also the
* only approach for "raw" file types that contain only arbitrary values.
* We presently apply this method for Targa files. Most of the time Targa
* files start with 0x00, so we recognize that case. Potentially, however,
* a Targa file could start with any byte value (byte 0 is the length of the
* seldom-used ID field), so we provide a switch to force Targa input mode.
*/
static boolean is_targa; /* records user -targa switch */
LOCAL(cjpeg_source_ptr)
select_file_type (j_compress_ptr cinfo, FILE * infile)
{
int c;
if (is_targa) {
#ifdef TARGA_SUPPORTED
return jinit_read_targa(cinfo);
#else
ERREXIT(cinfo, JERR_TGA_NOTCOMP);
#endif
}
if ((c = getc(infile)) == EOF)
ERREXIT(cinfo, JERR_INPUT_EMPTY);
if (ungetc(c, infile) == EOF)
ERREXIT(cinfo, JERR_UNGETC_FAILED);
switch (c) {
#ifdef BMP_SUPPORTED
case 'B':
return jinit_read_bmp(cinfo);
#endif
#ifdef GIF_SUPPORTED
case 'G':
return jinit_read_gif(cinfo);
#endif
#ifdef PPM_SUPPORTED
case 'P':
return jinit_read_ppm(cinfo);
#endif
#ifdef RLE_SUPPORTED
case 'R':
return jinit_read_rle(cinfo);
#endif
#ifdef TARGA_SUPPORTED
case 0x00:
return jinit_read_targa(cinfo);
#endif
default:
ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);
break;
}
return NULL; /* suppress compiler warnings */
}
/*
* Argument-parsing code.
* The switch parser is designed to be useful with DOS-style command line
* syntax, ie, intermixed switches and file names, where only the switches
* to the left of a given file name affect processing of that file.
* The main program in this file doesn't actually use this capability...
*/
static const char * progname; /* program name for error messages */
static char * outfilename; /* for -outfile switch */
LOCAL(void)
usage (void)
/* complain about bad command line */
{
fprintf(stderr, "usage: %s [switches] ", progname);
#ifdef TWO_FILE_COMMANDLINE
fprintf(stderr, "inputfile outputfile\n");
#else
fprintf(stderr, "[inputfile]\n");
#endif
fprintf(stderr, "Switches (names may be abbreviated):\n");
fprintf(stderr, " -quality N[,...] Compression quality (0..100; 5-95 is useful range)\n");
fprintf(stderr, " -grayscale Create monochrome JPEG file\n");
#ifdef ENTROPY_OPT_SUPPORTED
fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n");
#endif
#ifdef C_PROGRESSIVE_SUPPORTED
fprintf(stderr, " -progressive Create progressive JPEG file\n");
#endif
#ifdef DCT_SCALING_SUPPORTED
fprintf(stderr, " -scale M/N Scale image by fraction M/N, eg, 1/2\n");
#endif
#ifdef TARGA_SUPPORTED
fprintf(stderr, " -targa Input file is Targa format (usually not needed)\n");
#endif
fprintf(stderr, "Switches for advanced users:\n");
#ifdef DCT_ISLOW_SUPPORTED
fprintf(stderr, " -dct int Use integer DCT method%s\n",
(JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
#endif
#ifdef DCT_IFAST_SUPPORTED
fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
(JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
#endif
#ifdef DCT_FLOAT_SUPPORTED
fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
(JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
#endif
fprintf(stderr, " -nosmooth Don't use high-quality downsampling\n");
fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n");
#ifdef INPUT_SMOOTHING_SUPPORTED
fprintf(stderr, " -smooth N Smooth dithered input (N=1..100 is strength)\n");
#endif
fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
fprintf(stderr, " -outfile name Specify name for output file\n");
fprintf(stderr, " -verbose or -debug Emit debug output\n");
fprintf(stderr, "Switches for wizards:\n");
#ifdef C_ARITH_CODING_SUPPORTED
fprintf(stderr, " -arithmetic Use arithmetic coding\n");
#endif
fprintf(stderr, " -baseline Force baseline quantization tables\n");
fprintf(stderr, " -qtables file Use quantization tables given in file\n");
fprintf(stderr, " -qslots N[,...] Set component quantization tables\n");
fprintf(stderr, " -sample HxV[,...] Set component sampling factors\n");
#ifdef C_MULTISCAN_FILES_SUPPORTED
fprintf(stderr, " -scans file Create multi-scan JPEG per script file\n");
#endif
exit(EXIT_FAILURE);
}
LOCAL(int)
parse_switches (j_compress_ptr cinfo, int argc, char **argv,
int last_file_arg_seen, boolean for_real)
/* Parse optional switches.
* Returns argv[] index of first file-name argument (== argc if none).
* Any file names with indexes <= last_file_arg_seen are ignored;
* they have presumably been processed in a previous iteration.
* (Pass 0 for last_file_arg_seen on the first or only iteration.)
* for_real is FALSE on the first (dummy) pass; we may skip any expensive
* processing.
*/
{
int argn;
char * arg;
boolean force_baseline;
boolean simple_progressive;
char * qualityarg = NULL; /* saves -quality parm if any */
char * qtablefile = NULL; /* saves -qtables filename if any */
char * qslotsarg = NULL; /* saves -qslots parm if any */
char * samplearg = NULL; /* saves -sample parm if any */
char * scansarg = NULL; /* saves -scans parm if any */
/* Set up default JPEG parameters. */
force_baseline = FALSE; /* by default, allow 16-bit quantizers */
simple_progressive = FALSE;
is_targa = FALSE;
outfilename = NULL;
cinfo->err->trace_level = 0;
/* Scan command line options, adjust parameters */
for (argn = 1; argn < argc; argn++) {
arg = argv[argn];
if (*arg != '-') {
/* Not a switch, must be a file name argument */
if (argn <= last_file_arg_seen) {
outfilename = NULL; /* -outfile applies to just one input file */
continue; /* ignore this name if previously processed */
}
break; /* else done parsing switches */
}
arg++; /* advance past switch marker character */
if (keymatch(arg, "arithmetic", 1)) {
/* Use arithmetic coding. */
#ifdef C_ARITH_CODING_SUPPORTED
cinfo->arith_code = TRUE;
#else
fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
progname);
exit(EXIT_FAILURE);
#endif
} else if (keymatch(arg, "baseline", 1)) {
/* Force baseline-compatible output (8-bit quantizer values). */
force_baseline = TRUE;
} else if (keymatch(arg, "dct", 2)) {
/* Select DCT algorithm. */
if (++argn >= argc) /* advance to next argument */
usage();
if (keymatch(argv[argn], "int", 1)) {
cinfo->dct_method = JDCT_ISLOW;
} else if (keymatch(argv[argn], "fast", 2)) {
cinfo->dct_method = JDCT_IFAST;
} else if (keymatch(argv[argn], "float", 2)) {
cinfo->dct_method = JDCT_FLOAT;
} else
usage();
} else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
/* Enable debug printouts. */
/* On first -d, print version identification */
static boolean printed_version = FALSE;
if (! printed_version) {
fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n",
JVERSION, JCOPYRIGHT);
printed_version = TRUE;
}
cinfo->err->trace_level++;
} else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
/* Force a monochrome JPEG file to be generated. */
jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
} else if (keymatch(arg, "maxmemory", 3)) {
/* Maximum memory in Kb (or Mb with 'm'). */
long lval;
char ch = 'x';
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
usage();
if (ch == 'm' || ch == 'M')
lval *= 1000L;
cinfo->mem->max_memory_to_use = lval * 1000L;
} else if (keymatch(arg, "nosmooth", 3)) {
/* Suppress fancy downsampling */
cinfo->do_fancy_downsampling = FALSE;
} else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
/* Enable entropy parm optimization. */
#ifdef ENTROPY_OPT_SUPPORTED
cinfo->optimize_coding = TRUE;
#else
fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
progname);
exit(EXIT_FAILURE);
#endif
} else if (keymatch(arg, "outfile", 4)) {
/* Set output file name. */
if (++argn >= argc) /* advance to next argument */
usage();
outfilename = argv[argn]; /* save it away for later use */
} else if (keymatch(arg, "progressive", 1)) {
/* Select simple progressive mode. */
#ifdef C_PROGRESSIVE_SUPPORTED
simple_progressive = TRUE;
/* We must postpone execution until num_components is known. */
#else
fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
progname);
exit(EXIT_FAILURE);
#endif
} else if (keymatch(arg, "quality", 1)) {
/* Quality ratings (quantization table scaling factors). */
if (++argn >= argc) /* advance to next argument */
usage();
qualityarg = argv[argn];
} else if (keymatch(arg, "qslots", 2)) {
/* Quantization table slot numbers. */
if (++argn >= argc) /* advance to next argument */
usage();
qslotsarg = argv[argn];
/* Must delay setting qslots until after we have processed any
* colorspace-determining switches, since jpeg_set_colorspace sets
* default quant table numbers.
*/
} else if (keymatch(arg, "qtables", 2)) {
/* Quantization tables fetched from file. */
if (++argn >= argc) /* advance to next argument */
usage();
qtablefile = argv[argn];
/* We postpone actually reading the file in case -quality comes later. */
} else if (keymatch(arg, "restart", 1)) {
/* Restart interval in MCU rows (or in MCUs with 'b'). */
long lval;
char ch = 'x';
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
usage();
if (lval < 0 || lval > 65535L)
usage();
if (ch == 'b' || ch == 'B') {
cinfo->restart_interval = (unsigned int) lval;
cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
} else {
cinfo->restart_in_rows = (int) lval;
/* restart_interval will be computed during startup */
}
} else if (keymatch(arg, "sample", 2)) {
/* Set sampling factors. */
if (++argn >= argc) /* advance to next argument */
usage();
samplearg = argv[argn];
/* Must delay setting sample factors until after we have processed any
* colorspace-determining switches, since jpeg_set_colorspace sets
* default sampling factors.
*/
} else if (keymatch(arg, "scale", 4)) {
/* Scale the image by a fraction M/N. */
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%d/%d",
&cinfo->scale_num, &cinfo->scale_denom) != 2)
usage();
} else if (keymatch(arg, "scans", 4)) {
/* Set scan script. */
#ifdef C_MULTISCAN_FILES_SUPPORTED
if (++argn >= argc) /* advance to next argument */
usage();
scansarg = argv[argn];
/* We must postpone reading the file in case -progressive appears. */
#else
fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
progname);
exit(EXIT_FAILURE);
#endif
} else if (keymatch(arg, "smooth", 2)) {
/* Set input smoothing factor. */
int val;
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%d", &val) != 1)
usage();
if (val < 0 || val > 100)
usage();
cinfo->smoothing_factor = val;
} else if (keymatch(arg, "targa", 1)) {
/* Input file is Targa format. */
is_targa = TRUE;
} else {
usage(); /* bogus switch */
}
}
/* Post-switch-scanning cleanup */
if (for_real) {
/* Set quantization tables for selected quality. */
/* Some or all may be overridden if -qtables is present. */
if (qualityarg != NULL) /* process -quality if it was present */
if (! set_quality_ratings(cinfo, qualityarg, force_baseline))
usage();
if (qtablefile != NULL) /* process -qtables if it was present */
if (! read_quant_tables(cinfo, qtablefile, force_baseline))
usage();
if (qslotsarg != NULL) /* process -qslots if it was present */
if (! set_quant_slots(cinfo, qslotsarg))
usage();
if (samplearg != NULL) /* process -sample if it was present */
if (! set_sample_factors(cinfo, samplearg))
usage();
#ifdef C_PROGRESSIVE_SUPPORTED
if (simple_progressive) /* process -progressive; -scans can override */
jpeg_simple_progression(cinfo);
#endif
#ifdef C_MULTISCAN_FILES_SUPPORTED
if (scansarg != NULL) /* process -scans if it was present */
if (! read_scan_script(cinfo, scansarg))
usage();
#endif
}
return argn; /* return index of next arg (file name) */
}
/*
* The main program.
*/
int
main (int argc, char **argv)
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
#ifdef PROGRESS_REPORT
struct cdjpeg_progress_mgr progress;
#endif
int file_index;
cjpeg_source_ptr src_mgr;
FILE * input_file;
FILE * output_file;
JDIMENSION num_scanlines;
/* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
argc = ccommand(&argv);
#endif
progname = argv[0];
if (progname == NULL || progname[0] == 0)
progname = "cjpeg"; /* in case C library doesn't provide it */
/* Initialize the JPEG compression object with default error handling. */
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
/* Add some application-specific error messages (from cderror.h) */
jerr.addon_message_table = cdjpeg_message_table;
jerr.first_addon_message = JMSG_FIRSTADDONCODE;
jerr.last_addon_message = JMSG_LASTADDONCODE;
/* Now safe to enable signal catcher. */
#ifdef NEED_SIGNAL_CATCHER
enable_signal_catcher((j_common_ptr) &cinfo);
#endif
/* Initialize JPEG parameters.
* Much of this may be overridden later.
* In particular, we don't yet know the input file's color space,
* but we need to provide some value for jpeg_set_defaults() to work.
*/
cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
jpeg_set_defaults(&cinfo);
/* Scan command line to find file names.
* It is convenient to use just one switch-parsing routine, but the switch
* values read here are ignored; we will rescan the switches after opening
* the input file.
*/
file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
#ifdef TWO_FILE_COMMANDLINE
/* Must have either -outfile switch or explicit output file name */
if (outfilename == NULL) {
if (file_index != argc-2) {
fprintf(stderr, "%s: must name one input and one output file\n",
progname);
usage();
}
outfilename = argv[file_index+1];
} else {
if (file_index != argc-1) {
fprintf(stderr, "%s: must name one input and one output file\n",
progname);
usage();
}
}
#else
/* Unix style: expect zero or one file name */
if (file_index < argc-1) {
fprintf(stderr, "%s: only one input file\n", progname);
usage();
}
#endif /* TWO_FILE_COMMANDLINE */
/* Open the input file. */
if (file_index < argc) {
if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
exit(EXIT_FAILURE);
}
} else {
/* default input file is stdin */
input_file = read_stdin();
}
/* Open the output file. */
if (outfilename != NULL) {
if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
exit(EXIT_FAILURE);
}
} else {
/* default output file is stdout */
output_file = write_stdout();
}
#ifdef PROGRESS_REPORT
start_progress_monitor((j_common_ptr) &cinfo, &progress);
#endif
/* Figure out the input file format, and set up to read it. */
src_mgr = select_file_type(&cinfo, input_file);
src_mgr->input_file = input_file;
/* Read the input file header to obtain file size & colorspace. */
(*src_mgr->start_input) (&cinfo, src_mgr);
/* Now that we know input colorspace, fix colorspace-dependent defaults */
jpeg_default_colorspace(&cinfo);
/* Adjust default compression parameters by re-parsing the options */
file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
/* Specify data destination for compression */
jpeg_stdio_dest(&cinfo, output_file);
/* Start compressor */
jpeg_start_compress(&cinfo, TRUE);
/* Process data */
while (cinfo.next_scanline < cinfo.image_height) {
num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
(void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
}
/* Finish compression and release memory */
(*src_mgr->finish_input) (&cinfo, src_mgr);
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
/* Close files, if we opened them */
if (input_file != stdin)
fclose(input_file);
if (output_file != stdout)
fclose(output_file);
#ifdef PROGRESS_REPORT
end_progress_monitor((j_common_ptr) &cinfo);
#endif
/* All done. */
exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
return 0; /* suppress no-return-value warnings */
}
|
1137519-player
|
jpeg-7/cjpeg.c
|
C
|
lgpl
| 20,115
|
/*
* jdapimin.c
*
* Copyright (C) 1994-1998, Thomas G. Lane.
* Modified 2009 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains application interface code for the decompression half
* of the JPEG library. These are the "minimum" API routines that may be
* needed in either the normal full-decompression case or the
* transcoding-only case.
*
* Most of the routines intended to be called directly by an application
* are in this file or in jdapistd.c. But also see jcomapi.c for routines
* shared by compression and decompression, and jdtrans.c for the transcoding
* case.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
// #define MY_DEBUG
/*
* Initialization of a JPEG decompression object.
* The error manager must already be set up (in case memory manager fails).
*/
GLOBAL(void)
jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
{
int i;
/* Guard against version mismatches between library and caller. */
cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
// if (version != JPEG_LIB_VERSION)
// ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
// if (structsize != SIZEOF(struct jpeg_decompress_struct))
// ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
// (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
/* For debugging purposes, we zero the whole master structure.
* But the application has already set the err pointer, and may have set
* client_data, so we have to save and restore those fields.
* Note: if application hasn't set client_data, tools like Purify may
* complain here.
*/
{
struct jpeg_error_mgr * err = cinfo->err;
void * client_data = cinfo->client_data; /* ignore Purify complaint here */
// MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
cinfo->err = err;
cinfo->client_data = client_data;
}
cinfo->is_decompressor = TRUE;
/* Initialize a memory manager instance for this object */
jinit_memory_mgr((j_common_ptr) cinfo);
/* Zero out pointers to permanent structures. */
cinfo->progress = NULL;
cinfo->src = NULL;
for (i = 0; i < NUM_QUANT_TBLS; i++)
cinfo->quant_tbl_ptrs[i] = NULL;
for (i = 0; i < NUM_HUFF_TBLS; i++) {
cinfo->dc_huff_tbl_ptrs[i] = NULL;
cinfo->ac_huff_tbl_ptrs[i] = NULL;
}
/* Initialize marker processor so application can override methods
* for COM, APPn markers before calling jpeg_read_header.
*/
cinfo->marker_list = NULL;
jinit_marker_reader(cinfo);
/* And initialize the overall input controller. */
jinit_input_controller(cinfo);
/* OK, I'm ready */
cinfo->global_state = DSTATE_START;
}
/*
* Destruction of a JPEG decompression object
*/
GLOBAL(void)
jpeg_destroy_decompress (j_decompress_ptr cinfo)
{
jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
}
/*
* Abort processing of a JPEG decompression operation,
* but don't destroy the object itself.
*/
GLOBAL(void)
jpeg_abort_decompress (j_decompress_ptr cinfo)
{
jpeg_abort((j_common_ptr) cinfo); /* use common routine */
}
/*
* Set default decompression parameters.
*/
LOCAL(void)
default_decompress_parms (j_decompress_ptr cinfo)
{
/* Guess the input colorspace, and set output colorspace accordingly. */
/* (Wish JPEG committee had provided a real way to specify this...) */
/* Note application may override our guesses. */
switch (cinfo->num_components) {
case 1:
cinfo->jpeg_color_space = JCS_GRAYSCALE;
cinfo->out_color_space = JCS_GRAYSCALE;
break;
case 3:
if (cinfo->saw_JFIF_marker) {
cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
} else if (cinfo->saw_Adobe_marker) {
switch (cinfo->Adobe_transform) {
case 0:
cinfo->jpeg_color_space = JCS_RGB;
break;
case 1:
cinfo->jpeg_color_space = JCS_YCbCr;
break;
default:
WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
break;
}
} else {
/* Saw no special markers, try to guess from the component IDs */
int cid0 = cinfo->comp_info[0].component_id;
int cid1 = cinfo->comp_info[1].component_id;
int cid2 = cinfo->comp_info[2].component_id;
if (cid0 == 1 && cid1 == 2 && cid2 == 3)
cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
else {
TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
}
}
/* Always guess RGB is proper output colorspace. */
cinfo->out_color_space = JCS_RGB;
break;
case 4:
if (cinfo->saw_Adobe_marker) {
switch (cinfo->Adobe_transform) {
case 0:
cinfo->jpeg_color_space = JCS_CMYK;
break;
case 2:
cinfo->jpeg_color_space = JCS_YCCK;
break;
default:
WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
break;
}
} else {
/* No special markers, assume straight CMYK. */
cinfo->jpeg_color_space = JCS_CMYK;
}
cinfo->out_color_space = JCS_CMYK;
break;
default:
cinfo->jpeg_color_space = JCS_UNKNOWN;
cinfo->out_color_space = JCS_UNKNOWN;
break;
}
/* Set defaults for other decompression parameters.
cinfo->scale_num = DCTSIZE; 1:1 scaling
cinfo->scale_denom = DCTSIZE;
cinfo->output_gamma = 1.0;
cinfo->buffered_image = FALSE;
cinfo->raw_data_out = FALSE;
cinfo->dct_method = JDCT_IFAST;
cinfo->do_fancy_upsampling = FALSE;
cinfo->do_block_smoothing = TRUE;
cinfo->quantize_colors = FALSE;
We set these in case application only sets quantize_colors.
cinfo->dither_mode = JDITHER_FS;
#ifdef QUANT_2PASS_SUPPORTED
cinfo->two_pass_quantize = TRUE;
#else
cinfo->two_pass_quantize = FALSE;
#endif
cinfo->desired_number_of_colors = 256;
cinfo->colormap = NULL;
Initialize for no mode change in buffered-image mode.
cinfo->enable_1pass_quant = FALSE;
cinfo->enable_external_quant = FALSE;
cinfo->enable_2pass_quant = FALSE;*/
/* Set defaults for other decompression parameters. */
cinfo->scale_num = DCTSIZE; /* 1:1 scaling */
cinfo->scale_denom = DCTSIZE;
cinfo->output_gamma = 1.0;
cinfo->buffered_image = FALSE;
cinfo->raw_data_out = FALSE;
cinfo->dct_method = JDCT_IFAST;
cinfo->do_fancy_upsampling = FALSE;
cinfo->do_block_smoothing = FALSE;
cinfo->quantize_colors = FALSE;
/* We set these in case application only sets quantize_colors. */
cinfo->dither_mode = JDITHER_NONE;
cinfo->two_pass_quantize = FALSE;
cinfo->desired_number_of_colors = 256;
cinfo->colormap = NULL;
/* Initialize for no mode change in buffered-image mode. */
cinfo->enable_1pass_quant = FALSE;
cinfo->enable_external_quant = FALSE;
cinfo->enable_2pass_quant = FALSE;
}
/*
* Decompression startup: read start of JPEG datastream to see what's there.
* Need only initialize JPEG object and supply a data source before calling.
*
* This routine will read as far as the first SOS marker (ie, actual start of
* compressed data), and will save all tables and parameters in the JPEG
* object. It will also initialize the decompression parameters to default
* values, and finally return JPEG_HEADER_OK. On return, the application may
* adjust the decompression parameters and then call jpeg_start_decompress.
* (Or, if the application only wanted to determine the image parameters,
* the data need not be decompressed. In that case, call jpeg_abort or
* jpeg_destroy to release any temporary space.)
* If an abbreviated (tables only) datastream is presented, the routine will
* return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
* re-use the JPEG object to read the abbreviated image datastream(s).
* It is unnecessary (but OK) to call jpeg_abort in this case.
* The JPEG_SUSPENDED return code only occurs if the data source module
* requests suspension of the decompressor. In this case the application
* should load more source data and then re-call jpeg_read_header to resume
* processing.
* If a non-suspending data source is used and require_image is TRUE, then the
* return code need not be inspected since only JPEG_HEADER_OK is possible.
*
* This routine is now just a front end to jpeg_consume_input, with some
* extra error checking.
*/
GLOBAL(int)
jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
{
int retcode;
if (cinfo->global_state != DSTATE_START &&
cinfo->global_state != DSTATE_INHEADER)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
retcode = jpeg_consume_input(cinfo);
switch (retcode) {
case JPEG_REACHED_SOS:
retcode = JPEG_HEADER_OK;
break;
case JPEG_REACHED_EOI:
if (require_image) /* Complain if application wanted an image */
ERREXIT(cinfo, JERR_NO_IMAGE);
/* Reset to start state; it would be safer to require the application to
* call jpeg_abort, but we can't change it now for compatibility reasons.
* A side effect is to free any temporary memory (there shouldn't be any).
*/
jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
retcode = JPEG_HEADER_TABLES_ONLY;
break;
case JPEG_SUSPENDED:
/* no work */
break;
}
return retcode;
}
/*
* Consume data in advance of what the decompressor requires.
* This can be called at any time once the decompressor object has
* been created and a data source has been set up.
*
* This routine is essentially a state machine that handles a couple
* of critical state-transition actions, namely initial setup and
* transition from header scanning to ready-for-start_decompress.
* All the actual input is done via the input controller's consume_input
* method.
*/
GLOBAL(int)
jpeg_consume_input (j_decompress_ptr cinfo)
{
int retcode = JPEG_SUSPENDED;
/* NB: every possible DSTATE value should be listed in this switch */
switch (cinfo->global_state) {
case DSTATE_START:
/* Start-of-datastream actions: reset appropriate modules */
(*cinfo->inputctl->reset_input_controller) (cinfo);
/* Initialize application's data source module */
(*cinfo->src->init_source) (cinfo);
cinfo->global_state = DSTATE_INHEADER;
/*FALLTHROUGH*/
case DSTATE_INHEADER:
retcode = (*cinfo->inputctl->consume_input) (cinfo);
if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
/* Set up default parameters based on header data */
default_decompress_parms(cinfo);
/* Set global state: ready for start_decompress */
cinfo->global_state = DSTATE_READY;
}
break;
case DSTATE_READY:
/* Can't advance past first SOS until start_decompress is called */
retcode = JPEG_REACHED_SOS;
break;
case DSTATE_PRELOAD:
case DSTATE_PRESCAN:
case DSTATE_SCANNING:
case DSTATE_RAW_OK:
case DSTATE_BUFIMAGE:
case DSTATE_BUFPOST:
case DSTATE_STOPPING:
retcode = (*cinfo->inputctl->consume_input) (cinfo);
break;
default:
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
}
return retcode;
}
/*
* Have we finished reading the input file?
*/
GLOBAL(boolean)
jpeg_input_complete (j_decompress_ptr cinfo)
{
/* Check for valid jpeg object */
if (cinfo->global_state < DSTATE_START ||
cinfo->global_state > DSTATE_STOPPING)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
return cinfo->inputctl->eoi_reached;
}
/*
* Is there more than one scan?
*/
GLOBAL(boolean)
jpeg_has_multiple_scans (j_decompress_ptr cinfo)
{
/* Only valid after jpeg_read_header completes */
if (cinfo->global_state < DSTATE_READY ||
cinfo->global_state > DSTATE_STOPPING)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
return cinfo->inputctl->has_multiple_scans;
}
/*
* Finish JPEG decompression.
*
* This will normally just verify the file trailer and release temp storage.
*
* Returns FALSE if suspended. The return value need be inspected only if
* a suspending data source is used.
*/
GLOBAL(boolean)
jpeg_finish_decompress (j_decompress_ptr cinfo)
{
if ((cinfo->global_state == DSTATE_SCANNING ||
cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
/* Terminate final pass of non-buffered mode */
if (cinfo->output_scanline < cinfo->output_height)
ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
(*cinfo->master->finish_output_pass) (cinfo);
cinfo->global_state = DSTATE_STOPPING;
} else if (cinfo->global_state == DSTATE_BUFIMAGE) {
/* Finishing after a buffered-image operation */
cinfo->global_state = DSTATE_STOPPING;
} else if (cinfo->global_state != DSTATE_STOPPING) {
/* STOPPING = repeat call after a suspension, anything else is error */
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
}
/* Read until EOI */
while (! cinfo->inputctl->eoi_reached) {
if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
return FALSE; /* Suspend, come back later */
}
/* Do final cleanup */
(*cinfo->src->term_source) (cinfo);
/* We can use jpeg_abort to release memory and reset global_state */
jpeg_abort((j_common_ptr) cinfo);
return TRUE;
}
|
1137519-player
|
jpeg-7/jdapimin.c
|
C
|
lgpl
| 13,461
|
/*
* jddctmgr.c
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains the inverse-DCT management logic.
* This code selects a particular IDCT implementation to be used,
* and it performs related housekeeping chores. No code in this file
* is executed per IDCT step, only during output pass setup.
*
* Note that the IDCT routines are responsible for performing coefficient
* dequantization as well as the IDCT proper. This module sets up the
* dequantization multiplier table needed by the IDCT routine.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jdct.h" /* Private declarations for DCT subsystem */
/*
* The decompressor input side (jdinput.c) saves away the appropriate
* quantization table for each component at the start of the first scan
* involving that component. (This is necessary in order to correctly
* decode files that reuse Q-table slots.)
* When we are ready to make an output pass, the saved Q-table is converted
* to a multiplier table that will actually be used by the IDCT routine.
* The multiplier table contents are IDCT-method-dependent. To support
* application changes in IDCT method between scans, we can remake the
* multiplier tables if necessary.
* In buffered-image mode, the first output pass may occur before any data
* has been seen for some components, and thus before their Q-tables have
* been saved away. To handle this case, multiplier tables are preset
* to zeroes; the result of the IDCT will be a neutral gray level.
*/
/* Private subobject for this module */
typedef struct {
struct jpeg_inverse_dct pub; /* public fields */
/* This array contains the IDCT method code that each multiplier table
* is currently set up for, or -1 if it's not yet set up.
* The actual multiplier tables are pointed to by dct_table in the
* per-component comp_info structures.
*/
int cur_method[MAX_COMPONENTS];
} my_idct_controller;
typedef my_idct_controller * my_idct_ptr;
/* Allocated multiplier tables: big enough for any supported variant */
typedef union {
ISLOW_MULT_TYPE islow_array[DCTSIZE2];
#ifdef DCT_IFAST_SUPPORTED
IFAST_MULT_TYPE ifast_array[DCTSIZE2];
#endif
#ifdef DCT_FLOAT_SUPPORTED
FLOAT_MULT_TYPE float_array[DCTSIZE2];
#endif
} multiplier_table;
/* The current scaled-IDCT routines require ISLOW-style multiplier tables,
* so be sure to compile that code if either ISLOW or SCALING is requested.
*/
#ifdef DCT_ISLOW_SUPPORTED
#define PROVIDE_ISLOW_TABLES
#else
#ifdef IDCT_SCALING_SUPPORTED
#define PROVIDE_ISLOW_TABLES
#endif
#endif
/*
* Prepare for an output pass.
* Here we select the proper IDCT routine for each component and build
* a matching multiplier table.
*/
METHODDEF(void)
start_pass (j_decompress_ptr cinfo)
{
my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
int ci, i;
jpeg_component_info *compptr;
int method = 0;
inverse_DCT_method_ptr method_ptr = NULL;
JQUANT_TBL * qtbl;
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
/* Select the proper IDCT routine for this component's scaling */
switch ((compptr->DCT_h_scaled_size << 8) + compptr->DCT_v_scaled_size) {
#ifdef IDCT_SCALING_SUPPORTED
case ((1 << 8) + 1):
method_ptr = jpeg_idct_1x1;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((2 << 8) + 2):
method_ptr = jpeg_idct_2x2;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((3 << 8) + 3):
method_ptr = jpeg_idct_3x3;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((4 << 8) + 4):
method_ptr = jpeg_idct_4x4;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((5 << 8) + 5):
method_ptr = jpeg_idct_5x5;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((6 << 8) + 6):
method_ptr = jpeg_idct_6x6;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((7 << 8) + 7):
method_ptr = jpeg_idct_7x7;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((9 << 8) + 9):
method_ptr = jpeg_idct_9x9;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((10 << 8) + 10):
method_ptr = jpeg_idct_10x10;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((11 << 8) + 11):
method_ptr = jpeg_idct_11x11;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((12 << 8) + 12):
method_ptr = jpeg_idct_12x12;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((13 << 8) + 13):
method_ptr = jpeg_idct_13x13;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((14 << 8) + 14):
method_ptr = jpeg_idct_14x14;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((15 << 8) + 15):
method_ptr = jpeg_idct_15x15;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((16 << 8) + 16):
method_ptr = jpeg_idct_16x16;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((16 << 8) + 8):
method_ptr = jpeg_idct_16x8;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((14 << 8) + 7):
method_ptr = jpeg_idct_14x7;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((12 << 8) + 6):
method_ptr = jpeg_idct_12x6;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((10 << 8) + 5):
method_ptr = jpeg_idct_10x5;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((8 << 8) + 4):
method_ptr = jpeg_idct_8x4;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((6 << 8) + 3):
method_ptr = jpeg_idct_6x3;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((4 << 8) + 2):
method_ptr = jpeg_idct_4x2;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((2 << 8) + 1):
method_ptr = jpeg_idct_2x1;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((8 << 8) + 16):
method_ptr = jpeg_idct_8x16;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((7 << 8) + 14):
method_ptr = jpeg_idct_7x14;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((6 << 8) + 12):
method_ptr = jpeg_idct_6x12;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((5 << 8) + 10):
method_ptr = jpeg_idct_5x10;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((4 << 8) + 8):
method_ptr = jpeg_idct_4x8;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((3 << 8) + 6):
method_ptr = jpeg_idct_3x6;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((2 << 8) + 4):
method_ptr = jpeg_idct_2x4;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
case ((1 << 8) + 2):
method_ptr = jpeg_idct_1x2;
method = JDCT_ISLOW; /* jidctint uses islow-style table */
break;
#endif
case ((DCTSIZE << 8) + DCTSIZE):
switch (cinfo->dct_method) {
#ifdef DCT_ISLOW_SUPPORTED
case JDCT_ISLOW:
method_ptr = jpeg_idct_islow;
method = JDCT_ISLOW;
break;
#endif
#ifdef DCT_IFAST_SUPPORTED
case JDCT_IFAST:
method_ptr = jpeg_idct_ifast;
method = JDCT_IFAST;
break;
#endif
#ifdef DCT_FLOAT_SUPPORTED
case JDCT_FLOAT:
method_ptr = jpeg_idct_float;
method = JDCT_FLOAT;
break;
#endif
default:
ERREXIT(cinfo, JERR_NOT_COMPILED);
break;
}
break;
default:
ERREXIT2(cinfo, JERR_BAD_DCTSIZE,
compptr->DCT_h_scaled_size, compptr->DCT_v_scaled_size);
break;
}
idct->pub.inverse_DCT[ci] = method_ptr;
/* Create multiplier table from quant table.
* However, we can skip this if the component is uninteresting
* or if we already built the table. Also, if no quant table
* has yet been saved for the component, we leave the
* multiplier table all-zero; we'll be reading zeroes from the
* coefficient controller's buffer anyway.
*/
if (! compptr->component_needed || idct->cur_method[ci] == method)
continue;
qtbl = compptr->quant_table;
if (qtbl == NULL) /* happens if no data yet for component */
continue;
idct->cur_method[ci] = method;
switch (method) {
#ifdef PROVIDE_ISLOW_TABLES
case JDCT_ISLOW:
{
/* For LL&M IDCT method, multipliers are equal to raw quantization
* coefficients, but are stored as ints to ensure access efficiency.
*/
ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
for (i = 0; i < DCTSIZE2; i++) {
ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
}
}
break;
#endif
#ifdef DCT_IFAST_SUPPORTED
case JDCT_IFAST:
{
/* For AA&N IDCT method, multipliers are equal to quantization
* coefficients scaled by scalefactor[row]*scalefactor[col], where
* scalefactor[0] = 1
* scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
* For integer operation, the multiplier table is to be scaled by
* IFAST_SCALE_BITS.
*/
IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
#define CONST_BITS 14
static const INT16 aanscales[DCTSIZE2] = {
/* precomputed values scaled up by 14 bits */
16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
};
SHIFT_TEMPS
for (i = 0; i < DCTSIZE2; i++) {
ifmtbl[i] = (IFAST_MULT_TYPE)
DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
(INT32) aanscales[i]),
CONST_BITS-IFAST_SCALE_BITS);
}
}
break;
#endif
#ifdef DCT_FLOAT_SUPPORTED
case JDCT_FLOAT:
{
/* For float AA&N IDCT method, multipliers are equal to quantization
* coefficients scaled by scalefactor[row]*scalefactor[col], where
* scalefactor[0] = 1
* scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
*/
FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
int row, col;
static const double aanscalefactor[DCTSIZE] = {
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
};
i = 0;
for (row = 0; row < DCTSIZE; row++) {
for (col = 0; col < DCTSIZE; col++) {
fmtbl[i] = (FLOAT_MULT_TYPE)
((double) qtbl->quantval[i] *
aanscalefactor[row] * aanscalefactor[col]);
i++;
}
}
}
break;
#endif
default:
ERREXIT(cinfo, JERR_NOT_COMPILED);
break;
}
}
}
/*
* Initialize IDCT manager.
*/
GLOBAL(void)
jinit_inverse_dct (j_decompress_ptr cinfo)
{
my_idct_ptr idct;
int ci;
jpeg_component_info *compptr;
idct = (my_idct_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(my_idct_controller));
cinfo->idct = (struct jpeg_inverse_dct *) idct;
idct->pub.start_pass = start_pass;
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
/* Allocate and pre-zero a multiplier table for each component */
compptr->dct_table =
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(multiplier_table));
MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
/* Mark multiplier table not yet set up for any method */
idct->cur_method[ci] = -1;
}
}
|
1137519-player
|
jpeg-7/jddctmgr.c
|
C
|
lgpl
| 12,307
|
/*
* jmemname.c
*
* Copyright (C) 1992-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file provides a generic implementation of the system-dependent
* portion of the JPEG memory manager. This implementation assumes that
* you must explicitly construct a name for each temp file.
* Also, the problem of determining the amount of memory available
* is shoved onto the user.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jmemsys.h" /* import the system-dependent declarations */
#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
extern void * malloc JPP((size_t size));
extern void free JPP((void *ptr));
#endif
#ifndef SEEK_SET /* pre-ANSI systems may not define this; */
#define SEEK_SET 0 /* if not, assume 0 is correct */
#endif
#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
#define READ_BINARY "r"
#define RW_BINARY "w+"
#else
#ifdef VMS /* VMS is very nonstandard */
#define READ_BINARY "rb", "ctx=stm"
#define RW_BINARY "w+b", "ctx=stm"
#else /* standard ANSI-compliant case */
#define READ_BINARY "rb"
#define RW_BINARY "w+b"
#endif
#endif
/*
* Selection of a file name for a temporary file.
* This is system-dependent!
*
* The code as given is suitable for most Unix systems, and it is easily
* modified for most non-Unix systems. Some notes:
* 1. The temp file is created in the directory named by TEMP_DIRECTORY.
* The default value is /usr/tmp, which is the conventional place for
* creating large temp files on Unix. On other systems you'll probably
* want to change the file location. You can do this by editing the
* #define, or (preferred) by defining TEMP_DIRECTORY in jconfig.h.
*
* 2. If you need to change the file name as well as its location,
* you can override the TEMP_FILE_NAME macro. (Note that this is
* actually a printf format string; it must contain %s and %d.)
* Few people should need to do this.
*
* 3. mktemp() is used to ensure that multiple processes running
* simultaneously won't select the same file names. If your system
* doesn't have mktemp(), define NO_MKTEMP to do it the hard way.
* (If you don't have <errno.h>, also define NO_ERRNO_H.)
*
* 4. You probably want to define NEED_SIGNAL_CATCHER so that cjpeg.c/djpeg.c
* will cause the temp files to be removed if you stop the program early.
*/
#ifndef TEMP_DIRECTORY /* can override from jconfig.h or Makefile */
#define TEMP_DIRECTORY "/usr/tmp/" /* recommended setting for Unix */
#endif
static int next_file_num; /* to distinguish among several temp files */
#ifdef NO_MKTEMP
#ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */
#define TEMP_FILE_NAME "%sJPG%03d.TMP"
#endif
#ifndef NO_ERRNO_H
#include <errno.h> /* to define ENOENT */
#endif
/* ANSI C specifies that errno is a macro, but on older systems it's more
* likely to be a plain int variable. And not all versions of errno.h
* bother to declare it, so we have to in order to be most portable. Thus:
*/
#ifndef errno
extern int errno;
#endif
LOCAL(void)
select_file_name (char * fname)
{
FILE * tfile;
/* Keep generating file names till we find one that's not in use */
for (;;) {
next_file_num++; /* advance counter */
sprintf(fname, TEMP_FILE_NAME, TEMP_DIRECTORY, next_file_num);
if ((tfile = fopen(fname, READ_BINARY)) == NULL) {
/* fopen could have failed for a reason other than the file not
* being there; for example, file there but unreadable.
* If <errno.h> isn't available, then we cannot test the cause.
*/
#ifdef ENOENT
if (errno != ENOENT)
continue;
#endif
break;
}
fclose(tfile); /* oops, it's there; close tfile & try again */
}
}
#else /* ! NO_MKTEMP */
/* Note that mktemp() requires the initial filename to end in six X's */
#ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */
#define TEMP_FILE_NAME "%sJPG%dXXXXXX"
#endif
LOCAL(void)
select_file_name (char * fname)
{
next_file_num++; /* advance counter */
sprintf(fname, TEMP_FILE_NAME, TEMP_DIRECTORY, next_file_num);
mktemp(fname); /* make sure file name is unique */
/* mktemp replaces the trailing XXXXXX with a unique string of characters */
}
#endif /* NO_MKTEMP */
/*
* Memory allocation and freeing are controlled by the regular library
* routines malloc() and free().
*/
GLOBAL(void *)
jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
{
return (void *) malloc(sizeofobject);
}
GLOBAL(void)
jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
{
free(object);
}
/*
* "Large" objects are treated the same as "small" ones.
* NB: although we include FAR keywords in the routine declarations,
* this file won't actually work in 80x86 small/medium model; at least,
* you probably won't be able to process useful-size images in only 64KB.
*/
GLOBAL(void FAR *)
jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
{
return (void FAR *) malloc(sizeofobject);
}
GLOBAL(void)
jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
{
free(object);
}
/*
* This routine computes the total memory space available for allocation.
* It's impossible to do this in a portable way; our current solution is
* to make the user tell us (with a default value set at compile time).
* If you can actually get the available space, it's a good idea to subtract
* a slop factor of 5% or so.
*/
#ifndef DEFAULT_MAX_MEM /* so can override from makefile */
#define DEFAULT_MAX_MEM 1000000L /* default: one megabyte */
#endif
GLOBAL(long)
jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
long max_bytes_needed, long already_allocated)
{
return cinfo->mem->max_memory_to_use - already_allocated;
}
/*
* Backing store (temporary file) management.
* Backing store objects are only used when the value returned by
* jpeg_mem_available is less than the total space needed. You can dispense
* with these routines if you have plenty of virtual memory; see jmemnobs.c.
*/
METHODDEF(void)
read_backing_store (j_common_ptr cinfo, backing_store_ptr info,
void FAR * buffer_address,
long file_offset, long byte_count)
{
if (fseek(info->temp_file, file_offset, SEEK_SET))
ERREXIT(cinfo, JERR_TFILE_SEEK);
if (JFREAD(info->temp_file, buffer_address, byte_count)
!= (size_t) byte_count)
ERREXIT(cinfo, JERR_TFILE_READ);
}
METHODDEF(void)
write_backing_store (j_common_ptr cinfo, backing_store_ptr info,
void FAR * buffer_address,
long file_offset, long byte_count)
{
if (fseek(info->temp_file, file_offset, SEEK_SET))
ERREXIT(cinfo, JERR_TFILE_SEEK);
if (JFWRITE(info->temp_file, buffer_address, byte_count)
!= (size_t) byte_count)
ERREXIT(cinfo, JERR_TFILE_WRITE);
}
METHODDEF(void)
close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
{
fclose(info->temp_file); /* close the file */
unlink(info->temp_name); /* delete the file */
/* If your system doesn't have unlink(), use remove() instead.
* remove() is the ANSI-standard name for this function, but if
* your system was ANSI you'd be using jmemansi.c, right?
*/
TRACEMSS(cinfo, 1, JTRC_TFILE_CLOSE, info->temp_name);
}
/*
* Initial opening of a backing-store object.
*/
GLOBAL(void)
jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
long total_bytes_needed)
{
select_file_name(info->temp_name);
if ((info->temp_file = fopen(info->temp_name, RW_BINARY)) == NULL)
ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
info->read_backing_store = read_backing_store;
info->write_backing_store = write_backing_store;
info->close_backing_store = close_backing_store;
TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name);
}
/*
* These routines take care of any system-dependent initialization and
* cleanup required.
*/
GLOBAL(long)
jpeg_mem_init (j_common_ptr cinfo)
{
next_file_num = 0; /* initialize temp file name generator */
return DEFAULT_MAX_MEM; /* default for max_memory_to_use */
}
GLOBAL(void)
jpeg_mem_term (j_common_ptr cinfo)
{
/* no work */
}
|
1137519-player
|
jpeg-7/jmemname.c
|
C
|
lgpl
| 8,314
|
/*
* jdinput.c
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* Modified 2002-2009 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains input control logic for the JPEG decompressor.
* These routines are concerned with controlling the decompressor's input
* processing (marker reading and coefficient decoding). The actual input
* reading is done in jdmarker.c, jdhuff.c, and jdarith.c.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/* Private state */
typedef struct {
struct jpeg_input_controller pub; /* public fields */
boolean inheaders; /* TRUE until first SOS is reached */
} my_input_controller;
typedef my_input_controller * my_inputctl_ptr;
/* Forward declarations */
METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
/*
* Routines to calculate various quantities related to the size of the image.
*/
LOCAL(void)
initial_setup (j_decompress_ptr cinfo)
/* Called once, when first SOS marker is reached */
{
int ci;
jpeg_component_info *compptr;
/* Make sure image isn't bigger than I can handle */
if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
(long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
/* For now, precision must match compiled-in value... */
if (cinfo->data_precision != BITS_IN_JSAMPLE)
ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
/* Check that number of components won't exceed internal array sizes */
if (cinfo->num_components > MAX_COMPONENTS)
ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
MAX_COMPONENTS);
/* Compute maximum sampling factors; check factor validity */
cinfo->max_h_samp_factor = 1;
cinfo->max_v_samp_factor = 1;
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
ERREXIT(cinfo, JERR_BAD_SAMPLING);
cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
compptr->h_samp_factor);
cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
compptr->v_samp_factor);
}
/* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
* In the full decompressor, this will be overridden by jdmaster.c;
* but in the transcoder, jdmaster.c is not used, so we must do it here.
*/
cinfo->min_DCT_h_scaled_size = DCTSIZE;
cinfo->min_DCT_v_scaled_size = DCTSIZE;
/* Compute dimensions of components */
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
compptr->DCT_h_scaled_size = DCTSIZE;
compptr->DCT_v_scaled_size = DCTSIZE;
/* Size in DCT blocks */
compptr->width_in_blocks = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
(long) (cinfo->max_h_samp_factor * DCTSIZE));
compptr->height_in_blocks = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
(long) (cinfo->max_v_samp_factor * DCTSIZE));
/* downsampled_width and downsampled_height will also be overridden by
* jdmaster.c if we are doing full decompression. The transcoder library
* doesn't use these values, but the calling application might.
*/
/* Size in samples */
compptr->downsampled_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
(long) cinfo->max_h_samp_factor);
compptr->downsampled_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
(long) cinfo->max_v_samp_factor);
/* Mark component needed, until color conversion says otherwise */
compptr->component_needed = TRUE;
/* Mark no quantization table yet saved for component */
compptr->quant_table = NULL;
}
/* Compute number of fully interleaved MCU rows. */
cinfo->total_iMCU_rows = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height,
(long) (cinfo->max_v_samp_factor*DCTSIZE));
/* Decide whether file contains multiple scans */
if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
cinfo->inputctl->has_multiple_scans = TRUE;
else
cinfo->inputctl->has_multiple_scans = FALSE;
}
LOCAL(void)
per_scan_setup (j_decompress_ptr cinfo)
/* Do computations that are needed before processing a JPEG scan */
/* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
{
int ci, mcublks, tmp;
jpeg_component_info *compptr;
if (cinfo->comps_in_scan == 1) {
/* Noninterleaved (single-component) scan */
compptr = cinfo->cur_comp_info[0];
/* Overall image size in MCUs */
cinfo->MCUs_per_row = compptr->width_in_blocks;
cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
/* For noninterleaved scan, always one block per MCU */
compptr->MCU_width = 1;
compptr->MCU_height = 1;
compptr->MCU_blocks = 1;
compptr->MCU_sample_width = compptr->DCT_h_scaled_size;
compptr->last_col_width = 1;
/* For noninterleaved scans, it is convenient to define last_row_height
* as the number of block rows present in the last iMCU row.
*/
tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
if (tmp == 0) tmp = compptr->v_samp_factor;
compptr->last_row_height = tmp;
/* Prepare array describing MCU composition */
cinfo->blocks_in_MCU = 1;
cinfo->MCU_membership[0] = 0;
} else {
/* Interleaved (multi-component) scan */
if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
MAX_COMPS_IN_SCAN);
/* Overall image size in MCUs */
cinfo->MCUs_per_row = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width,
(long) (cinfo->max_h_samp_factor*DCTSIZE));
cinfo->MCU_rows_in_scan = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height,
(long) (cinfo->max_v_samp_factor*DCTSIZE));
cinfo->blocks_in_MCU = 0;
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
/* Sampling factors give # of blocks of component in each MCU */
compptr->MCU_width = compptr->h_samp_factor;
compptr->MCU_height = compptr->v_samp_factor;
compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_h_scaled_size;
/* Figure number of non-dummy blocks in last MCU column & row */
tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
if (tmp == 0) tmp = compptr->MCU_width;
compptr->last_col_width = tmp;
tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
if (tmp == 0) tmp = compptr->MCU_height;
compptr->last_row_height = tmp;
/* Prepare array describing MCU composition */
mcublks = compptr->MCU_blocks;
if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
while (mcublks-- > 0) {
cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
}
}
}
}
/*
* Save away a copy of the Q-table referenced by each component present
* in the current scan, unless already saved during a prior scan.
*
* In a multiple-scan JPEG file, the encoder could assign different components
* the same Q-table slot number, but change table definitions between scans
* so that each component uses a different Q-table. (The IJG encoder is not
* currently capable of doing this, but other encoders might.) Since we want
* to be able to dequantize all the components at the end of the file, this
* means that we have to save away the table actually used for each component.
* We do this by copying the table at the start of the first scan containing
* the component.
* The JPEG spec prohibits the encoder from changing the contents of a Q-table
* slot between scans of a component using that slot. If the encoder does so
* anyway, this decoder will simply use the Q-table values that were current
* at the start of the first scan for the component.
*
* The decompressor output side looks only at the saved quant tables,
* not at the current Q-table slots.
*/
LOCAL(void)
latch_quant_tables (j_decompress_ptr cinfo)
{
int ci, qtblno;
jpeg_component_info *compptr;
JQUANT_TBL * qtbl;
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
/* No work if we already saved Q-table for this component */
if (compptr->quant_table != NULL)
continue;
/* Make sure specified quantization table is present */
qtblno = compptr->quant_tbl_no;
if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
cinfo->quant_tbl_ptrs[qtblno] == NULL)
ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
/* OK, save away the quantization table */
qtbl = (JQUANT_TBL *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(JQUANT_TBL));
MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
compptr->quant_table = qtbl;
}
}
/*
* Initialize the input modules to read a scan of compressed data.
* The first call to this is done by jdmaster.c after initializing
* the entire decompressor (during jpeg_start_decompress).
* Subsequent calls come from consume_markers, below.
*/
METHODDEF(void)
start_input_pass (j_decompress_ptr cinfo)
{
per_scan_setup(cinfo);
latch_quant_tables(cinfo);
(*cinfo->entropy->start_pass) (cinfo);
(*cinfo->coef->start_input_pass) (cinfo);
cinfo->inputctl->consume_input = cinfo->coef->consume_data;
}
/*
* Finish up after inputting a compressed-data scan.
* This is called by the coefficient controller after it's read all
* the expected data of the scan.
*/
METHODDEF(void)
finish_input_pass (j_decompress_ptr cinfo)
{
cinfo->inputctl->consume_input = consume_markers;
}
/*
* Read JPEG markers before, between, or after compressed-data scans.
* Change state as necessary when a new scan is reached.
* Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
*
* The consume_input method pointer points either here or to the
* coefficient controller's consume_data routine, depending on whether
* we are reading a compressed data segment or inter-segment markers.
*/
METHODDEF(int)
consume_markers (j_decompress_ptr cinfo)
{
my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
int val;
if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
return JPEG_REACHED_EOI;
val = (*cinfo->marker->read_markers) (cinfo);
switch (val) {
case JPEG_REACHED_SOS: /* Found SOS */
if (inputctl->inheaders) { /* 1st SOS */
initial_setup(cinfo);
inputctl->inheaders = FALSE;
/* Note: start_input_pass must be called by jdmaster.c
* before any more input can be consumed. jdapimin.c is
* responsible for enforcing this sequencing.
*/
} else { /* 2nd or later SOS marker */
if (! inputctl->pub.has_multiple_scans)
ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
start_input_pass(cinfo);
}
break;
case JPEG_REACHED_EOI: /* Found EOI */
inputctl->pub.eoi_reached = TRUE;
if (inputctl->inheaders) { /* Tables-only datastream, apparently */
if (cinfo->marker->saw_SOF)
ERREXIT(cinfo, JERR_SOF_NO_SOS);
} else {
/* Prevent infinite loop in coef ctlr's decompress_data routine
* if user set output_scan_number larger than number of scans.
*/
if (cinfo->output_scan_number > cinfo->input_scan_number)
cinfo->output_scan_number = cinfo->input_scan_number;
}
break;
case JPEG_SUSPENDED:
break;
}
return val;
}
/*
* Reset state to begin a fresh datastream.
*/
METHODDEF(void)
reset_input_controller (j_decompress_ptr cinfo)
{
my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
inputctl->pub.consume_input = consume_markers;
inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
inputctl->pub.eoi_reached = FALSE;
inputctl->inheaders = TRUE;
/* Reset other modules */
(*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
(*cinfo->marker->reset_marker_reader) (cinfo);
/* Reset progression state -- would be cleaner if entropy decoder did this */
cinfo->coef_bits = NULL;
}
/*
* Initialize the input controller module.
* This is called only once, when the decompression object is created.
*/
GLOBAL(void)
jinit_input_controller (j_decompress_ptr cinfo)
{
my_inputctl_ptr inputctl;
/* Create subobject in permanent pool */
inputctl = (my_inputctl_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
SIZEOF(my_input_controller));
cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
/* Initialize method pointers */
inputctl->pub.consume_input = consume_markers;
inputctl->pub.reset_input_controller = reset_input_controller;
inputctl->pub.start_input_pass = start_input_pass;
inputctl->pub.finish_input_pass = finish_input_pass;
/* Initialize state: can't use reset_input_controller since we don't
* want to try to reset other modules yet.
*/
inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
inputctl->pub.eoi_reached = FALSE;
inputctl->inheaders = TRUE;
}
|
1137519-player
|
jpeg-7/jdinput.c
|
C
|
lgpl
| 13,635
|
/*
* jutils.c
*
* Copyright (C) 1991-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains tables and miscellaneous utility routines needed
* for both compression and decompression.
* Note we prefix all global names with "j" to minimize conflicts with
* a surrounding application.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/*
* jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
* of a DCT block read in natural order (left to right, top to bottom).
*/
#if 0 /* This table is not actually needed in v6a */
const int jpeg_zigzag_order[DCTSIZE2] = {
0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63
};
#endif
/*
* jpeg_natural_order[i] is the natural-order position of the i'th element
* of zigzag order.
*
* When reading corrupted data, the Huffman decoders could attempt
* to reference an entry beyond the end of this array (if the decoded
* zero run length reaches past the end of the block). To prevent
* wild stores without adding an inner-loop test, we put some extra
* "63"s after the real entries. This will cause the extra coefficient
* to be stored in location 63 of the block, not somewhere random.
* The worst case would be a run-length of 15, which means we need 16
* fake entries.
*/
const int jpeg_natural_order[DCTSIZE2+16] = {
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63,
63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
63, 63, 63, 63, 63, 63, 63, 63
};
/*
* Arithmetic utilities
*/
GLOBAL(long)
jdiv_round_up (long a, long b)
/* Compute a/b rounded up to next integer, ie, ceil(a/b) */
/* Assumes a >= 0, b > 0 */
{
return (a + b - 1L) / b;
}
GLOBAL(long)
jround_up (long a, long b)
/* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
/* Assumes a >= 0, b > 0 */
{
a += b - 1L;
return a - (a % b);
}
/* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
* and coefficient-block arrays. This won't work on 80x86 because the arrays
* are FAR and we're assuming a small-pointer memory model. However, some
* DOS compilers provide far-pointer versions of memcpy() and memset() even
* in the small-model libraries. These will be used if USE_FMEM is defined.
* Otherwise, the routines below do it the hard way. (The performance cost
* is not all that great, because these routines aren't very heavily used.)
*/
#ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
#define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
#define FMEMZERO(target,size) MEMZERO(target,size)
#else /* 80x86 case, define if we can */
#ifdef USE_FMEM
#define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
#define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
#endif
#endif
GLOBAL(void)
jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
JSAMPARRAY output_array, int dest_row,
int num_rows, JDIMENSION num_cols)
/* Copy some rows of samples from one place to another.
* num_rows rows are copied from input_array[source_row++]
* to output_array[dest_row++]; these areas may overlap for duplication.
* The source and destination arrays must be at least as wide as num_cols.
*/
{
register JSAMPROW inptr, outptr;
#ifdef FMEMCOPY
register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
#else
register JDIMENSION count;
#endif
register int row;
input_array += source_row;
output_array += dest_row;
for (row = num_rows; row > 0; row--) {
inptr = *input_array++;
outptr = *output_array++;
#ifdef FMEMCOPY
FMEMCOPY(outptr, inptr, count);
#else
for (count = num_cols; count > 0; count--)
*outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
#endif
}
}
GLOBAL(void)
jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
JDIMENSION num_blocks)
/* Copy a row of coefficient blocks from one place to another. */
{
#ifdef FMEMCOPY
FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
#else
register JCOEFPTR inptr, outptr;
register long count;
inptr = (JCOEFPTR) input_row;
outptr = (JCOEFPTR) output_row;
for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
*outptr++ = *inptr++;
}
#endif
}
GLOBAL(void)
jzero_far (void FAR * target, size_t bytestozero)
/* Zero out a chunk of FAR memory. */
/* This might be sample-array data, block-array data, or alloc_large data. */
{
#ifdef FMEMZERO
FMEMZERO(target, bytestozero);
#else
register char FAR * ptr = (char FAR *) target;
register size_t count;
for (count = bytestozero; count > 0; count--) {
*ptr++ = 0;
}
#endif
}
|
1137519-player
|
jpeg-7/jutils.c
|
C
|
lgpl
| 5,239
|
/*
* rdrle.c
*
* Copyright (C) 1991-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains routines to read input images in Utah RLE format.
* The Utah Raster Toolkit library is required (version 3.1 or later).
*
* These routines may need modification for non-Unix environments or
* specialized applications. As they stand, they assume input from
* an ordinary stdio stream. They further assume that reading begins
* at the start of the file; start_input may need work if the
* user interface has already read some data (e.g., to determine that
* the file is indeed RLE format).
*
* Based on code contributed by Mike Lijewski,
* with updates from Robert Hutchinson.
*/
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#ifdef RLE_SUPPORTED
/* rle.h is provided by the Utah Raster Toolkit. */
#include <rle.h>
/*
* We assume that JSAMPLE has the same representation as rle_pixel,
* to wit, "unsigned char". Hence we can't cope with 12- or 16-bit samples.
*/
#if BITS_IN_JSAMPLE != 8
Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
#endif
/*
* We support the following types of RLE files:
*
* GRAYSCALE - 8 bits, no colormap
* MAPPEDGRAY - 8 bits, 1 channel colomap
* PSEUDOCOLOR - 8 bits, 3 channel colormap
* TRUECOLOR - 24 bits, 3 channel colormap
* DIRECTCOLOR - 24 bits, no colormap
*
* For now, we ignore any alpha channel in the image.
*/
typedef enum
{ GRAYSCALE, MAPPEDGRAY, PSEUDOCOLOR, TRUECOLOR, DIRECTCOLOR } rle_kind;
/*
* Since RLE stores scanlines bottom-to-top, we have to invert the image
* to conform to JPEG's top-to-bottom order. To do this, we read the
* incoming image into a virtual array on the first get_pixel_rows call,
* then fetch the required row from the virtual array on subsequent calls.
*/
typedef struct _rle_source_struct * rle_source_ptr;
typedef struct _rle_source_struct {
struct cjpeg_source_struct pub; /* public fields */
rle_kind visual; /* actual type of input file */
jvirt_sarray_ptr image; /* virtual array to hold the image */
JDIMENSION row; /* current row # in the virtual array */
rle_hdr header; /* Input file information */
rle_pixel** rle_row; /* holds a row returned by rle_getrow() */
} rle_source_struct;
/*
* Read the file header; return image size and component count.
*/
METHODDEF(void)
start_input_rle (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
rle_source_ptr source = (rle_source_ptr) sinfo;
JDIMENSION width, height;
#ifdef PROGRESS_REPORT
cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
#endif
/* Use RLE library routine to get the header info */
source->header = *rle_hdr_init(NULL);
source->header.rle_file = source->pub.input_file;
switch (rle_get_setup(&(source->header))) {
case RLE_SUCCESS:
/* A-OK */
break;
case RLE_NOT_RLE:
ERREXIT(cinfo, JERR_RLE_NOT);
break;
case RLE_NO_SPACE:
ERREXIT(cinfo, JERR_RLE_MEM);
break;
case RLE_EMPTY:
ERREXIT(cinfo, JERR_RLE_EMPTY);
break;
case RLE_EOF:
ERREXIT(cinfo, JERR_RLE_EOF);
break;
default:
ERREXIT(cinfo, JERR_RLE_BADERROR);
break;
}
/* Figure out what we have, set private vars and return values accordingly */
width = source->header.xmax - source->header.xmin + 1;
height = source->header.ymax - source->header.ymin + 1;
source->header.xmin = 0; /* realign horizontally */
source->header.xmax = width-1;
cinfo->image_width = width;
cinfo->image_height = height;
cinfo->data_precision = 8; /* we can only handle 8 bit data */
if (source->header.ncolors == 1 && source->header.ncmap == 0) {
source->visual = GRAYSCALE;
TRACEMS2(cinfo, 1, JTRC_RLE_GRAY, width, height);
} else if (source->header.ncolors == 1 && source->header.ncmap == 1) {
source->visual = MAPPEDGRAY;
TRACEMS3(cinfo, 1, JTRC_RLE_MAPGRAY, width, height,
1 << source->header.cmaplen);
} else if (source->header.ncolors == 1 && source->header.ncmap == 3) {
source->visual = PSEUDOCOLOR;
TRACEMS3(cinfo, 1, JTRC_RLE_MAPPED, width, height,
1 << source->header.cmaplen);
} else if (source->header.ncolors == 3 && source->header.ncmap == 3) {
source->visual = TRUECOLOR;
TRACEMS3(cinfo, 1, JTRC_RLE_FULLMAP, width, height,
1 << source->header.cmaplen);
} else if (source->header.ncolors == 3 && source->header.ncmap == 0) {
source->visual = DIRECTCOLOR;
TRACEMS2(cinfo, 1, JTRC_RLE, width, height);
} else
ERREXIT(cinfo, JERR_RLE_UNSUPPORTED);
if (source->visual == GRAYSCALE || source->visual == MAPPEDGRAY) {
cinfo->in_color_space = JCS_GRAYSCALE;
cinfo->input_components = 1;
} else {
cinfo->in_color_space = JCS_RGB;
cinfo->input_components = 3;
}
/*
* A place to hold each scanline while it's converted.
* (GRAYSCALE scanlines don't need converting)
*/
if (source->visual != GRAYSCALE) {
source->rle_row = (rle_pixel**) (*cinfo->mem->alloc_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE,
(JDIMENSION) width, (JDIMENSION) cinfo->input_components);
}
/* request a virtual array to hold the image */
source->image = (*cinfo->mem->request_virt_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
(JDIMENSION) (width * source->header.ncolors),
(JDIMENSION) height, (JDIMENSION) 1);
#ifdef PROGRESS_REPORT
if (progress != NULL) {
/* count file input as separate pass */
progress->total_extra_passes++;
}
#endif
source->pub.buffer_height = 1;
}
/*
* Read one row of pixels.
* Called only after load_image has read the image into the virtual array.
* Used for GRAYSCALE, MAPPEDGRAY, TRUECOLOR, and DIRECTCOLOR images.
*/
METHODDEF(JDIMENSION)
get_rle_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
rle_source_ptr source = (rle_source_ptr) sinfo;
source->row--;
source->pub.buffer = (*cinfo->mem->access_virt_sarray)
((j_common_ptr) cinfo, source->image, source->row, (JDIMENSION) 1, FALSE);
return 1;
}
/*
* Read one row of pixels.
* Called only after load_image has read the image into the virtual array.
* Used for PSEUDOCOLOR images.
*/
METHODDEF(JDIMENSION)
get_pseudocolor_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
rle_source_ptr source = (rle_source_ptr) sinfo;
JSAMPROW src_row, dest_row;
JDIMENSION col;
rle_map *colormap;
int val;
colormap = source->header.cmap;
dest_row = source->pub.buffer[0];
source->row--;
src_row = * (*cinfo->mem->access_virt_sarray)
((j_common_ptr) cinfo, source->image, source->row, (JDIMENSION) 1, FALSE);
for (col = cinfo->image_width; col > 0; col--) {
val = GETJSAMPLE(*src_row++);
*dest_row++ = (JSAMPLE) (colormap[val ] >> 8);
*dest_row++ = (JSAMPLE) (colormap[val + 256] >> 8);
*dest_row++ = (JSAMPLE) (colormap[val + 512] >> 8);
}
return 1;
}
/*
* Load the image into a virtual array. We have to do this because RLE
* files start at the lower left while the JPEG standard has them starting
* in the upper left. This is called the first time we want to get a row
* of input. What we do is load the RLE data into the array and then call
* the appropriate routine to read one row from the array. Before returning,
* we set source->pub.get_pixel_rows so that subsequent calls go straight to
* the appropriate row-reading routine.
*/
METHODDEF(JDIMENSION)
load_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
rle_source_ptr source = (rle_source_ptr) sinfo;
JDIMENSION row, col;
JSAMPROW scanline, red_ptr, green_ptr, blue_ptr;
rle_pixel **rle_row;
rle_map *colormap;
char channel;
#ifdef PROGRESS_REPORT
cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
#endif
colormap = source->header.cmap;
rle_row = source->rle_row;
/* Read the RLE data into our virtual array.
* We assume here that (a) rle_pixel is represented the same as JSAMPLE,
* and (b) we are not on a machine where FAR pointers differ from regular.
*/
RLE_CLR_BIT(source->header, RLE_ALPHA); /* don't read the alpha channel */
#ifdef PROGRESS_REPORT
if (progress != NULL) {
progress->pub.pass_limit = cinfo->image_height;
progress->pub.pass_counter = 0;
(*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
}
#endif
switch (source->visual) {
case GRAYSCALE:
case PSEUDOCOLOR:
for (row = 0; row < cinfo->image_height; row++) {
rle_row = (rle_pixel **) (*cinfo->mem->access_virt_sarray)
((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE);
rle_getrow(&source->header, rle_row);
#ifdef PROGRESS_REPORT
if (progress != NULL) {
progress->pub.pass_counter++;
(*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
}
#endif
}
break;
case MAPPEDGRAY:
case TRUECOLOR:
for (row = 0; row < cinfo->image_height; row++) {
scanline = * (*cinfo->mem->access_virt_sarray)
((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE);
rle_row = source->rle_row;
rle_getrow(&source->header, rle_row);
for (col = 0; col < cinfo->image_width; col++) {
for (channel = 0; channel < source->header.ncolors; channel++) {
*scanline++ = (JSAMPLE)
(colormap[GETJSAMPLE(rle_row[channel][col]) + 256 * channel] >> 8);
}
}
#ifdef PROGRESS_REPORT
if (progress != NULL) {
progress->pub.pass_counter++;
(*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
}
#endif
}
break;
case DIRECTCOLOR:
for (row = 0; row < cinfo->image_height; row++) {
scanline = * (*cinfo->mem->access_virt_sarray)
((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE);
rle_getrow(&source->header, rle_row);
red_ptr = rle_row[0];
green_ptr = rle_row[1];
blue_ptr = rle_row[2];
for (col = cinfo->image_width; col > 0; col--) {
*scanline++ = *red_ptr++;
*scanline++ = *green_ptr++;
*scanline++ = *blue_ptr++;
}
#ifdef PROGRESS_REPORT
if (progress != NULL) {
progress->pub.pass_counter++;
(*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
}
#endif
}
}
#ifdef PROGRESS_REPORT
if (progress != NULL)
progress->completed_extra_passes++;
#endif
/* Set up to call proper row-extraction routine in future */
if (source->visual == PSEUDOCOLOR) {
source->pub.buffer = source->rle_row;
source->pub.get_pixel_rows = get_pseudocolor_row;
} else {
source->pub.get_pixel_rows = get_rle_row;
}
source->row = cinfo->image_height;
/* And fetch the topmost (bottommost) row */
return (*source->pub.get_pixel_rows) (cinfo, sinfo);
}
/*
* Finish up at the end of the file.
*/
METHODDEF(void)
finish_input_rle (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
/* no work */
}
/*
* The module selection routine for RLE format input.
*/
GLOBAL(cjpeg_source_ptr)
jinit_read_rle (j_compress_ptr cinfo)
{
rle_source_ptr source;
/* Create module interface object */
source = (rle_source_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(rle_source_struct));
/* Fill in method ptrs */
source->pub.start_input = start_input_rle;
source->pub.finish_input = finish_input_rle;
source->pub.get_pixel_rows = load_image;
return (cjpeg_source_ptr) source;
}
#endif /* RLE_SUPPORTED */
|
1137519-player
|
jpeg-7/rdrle.c
|
C
|
lgpl
| 11,673
|
/*
* jdct.h
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This include file contains common declarations for the forward and
* inverse DCT modules. These declarations are private to the DCT managers
* (jcdctmgr.c, jddctmgr.c) and the individual DCT algorithms.
* The individual DCT algorithms are kept in separate files to ease
* machine-dependent tuning (e.g., assembly coding).
*/
/*
* A forward DCT routine is given a pointer to an input sample array and
* a pointer to a work area of type DCTELEM[]; the DCT is to be performed
* in-place in that buffer. Type DCTELEM is int for 8-bit samples, INT32
* for 12-bit samples. (NOTE: Floating-point DCT implementations use an
* array of type FAST_FLOAT, instead.)
* The input data is to be fetched from the sample array starting at a
* specified column. (Any row offset needed will be applied to the array
* pointer before it is passed to the FDCT code.)
* Note that the number of samples fetched by the FDCT routine is
* DCT_h_scaled_size * DCT_v_scaled_size.
* The DCT outputs are returned scaled up by a factor of 8; they therefore
* have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
* convention improves accuracy in integer implementations and saves some
* work in floating-point ones.
* Quantization of the output coefficients is done by jcdctmgr.c.
*/
#if BITS_IN_JSAMPLE == 8
typedef int DCTELEM; /* 16 or 32 bits is fine */
#else
typedef INT32 DCTELEM; /* must have 32 bits */
#endif
typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data,
JSAMPARRAY sample_data,
JDIMENSION start_col));
typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data,
JSAMPARRAY sample_data,
JDIMENSION start_col));
/*
* An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
* to an output sample array. The routine must dequantize the input data as
* well as perform the IDCT; for dequantization, it uses the multiplier table
* pointed to by compptr->dct_table. The output data is to be placed into the
* sample array starting at a specified column. (Any row offset needed will
* be applied to the array pointer before it is passed to the IDCT code.)
* Note that the number of samples emitted by the IDCT routine is
* DCT_h_scaled_size * DCT_v_scaled_size.
*/
/* typedef inverse_DCT_method_ptr is declared in jpegint.h */
/*
* Each IDCT routine has its own ideas about the best dct_table element type.
*/
typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
#if BITS_IN_JSAMPLE == 8
typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
#define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
#else
typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
#define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
#endif
typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
/*
* Each IDCT routine is responsible for range-limiting its results and
* converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
* be quite far out of range if the input data is corrupt, so a bulletproof
* range-limiting step is required. We use a mask-and-table-lookup method
* to do the combined operations quickly. See the comments with
* prepare_range_limit_table (in jdmaster.c) for more info.
*/
#define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
#define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
/* Short forms of external names for systems with brain-damaged linkers. */
#ifdef NEED_SHORT_EXTERNAL_NAMES
#define jpeg_fdct_islow jFDislow
#define jpeg_fdct_ifast jFDifast
#define jpeg_fdct_float jFDfloat
#define jpeg_fdct_7x7 jFD7x7
#define jpeg_fdct_6x6 jFD6x6
#define jpeg_fdct_5x5 jFD5x5
#define jpeg_fdct_4x4 jFD4x4
#define jpeg_fdct_3x3 jFD3x3
#define jpeg_fdct_2x2 jFD2x2
#define jpeg_fdct_1x1 jFD1x1
#define jpeg_fdct_9x9 jFD9x9
#define jpeg_fdct_10x10 jFD10x10
#define jpeg_fdct_11x11 jFD11x11
#define jpeg_fdct_12x12 jFD12x12
#define jpeg_fdct_13x13 jFD13x13
#define jpeg_fdct_14x14 jFD14x14
#define jpeg_fdct_15x15 jFD15x15
#define jpeg_fdct_16x16 jFD16x16
#define jpeg_fdct_16x8 jFD16x8
#define jpeg_fdct_14x7 jFD14x7
#define jpeg_fdct_12x6 jFD12x6
#define jpeg_fdct_10x5 jFD10x5
#define jpeg_fdct_8x4 jFD8x4
#define jpeg_fdct_6x3 jFD6x3
#define jpeg_fdct_4x2 jFD4x2
#define jpeg_fdct_2x1 jFD2x1
#define jpeg_fdct_8x16 jFD8x16
#define jpeg_fdct_7x14 jFD7x14
#define jpeg_fdct_6x12 jFD6x12
#define jpeg_fdct_5x10 jFD5x10
#define jpeg_fdct_4x8 jFD4x8
#define jpeg_fdct_3x6 jFD3x6
#define jpeg_fdct_2x4 jFD2x4
#define jpeg_fdct_1x2 jFD1x2
#define jpeg_idct_islow jRDislow
#define jpeg_idct_ifast jRDifast
#define jpeg_idct_float jRDfloat
#define jpeg_idct_7x7 jRD7x7
#define jpeg_idct_6x6 jRD6x6
#define jpeg_idct_5x5 jRD5x5
#define jpeg_idct_4x4 jRD4x4
#define jpeg_idct_3x3 jRD3x3
#define jpeg_idct_2x2 jRD2x2
#define jpeg_idct_1x1 jRD1x1
#define jpeg_idct_9x9 jRD9x9
#define jpeg_idct_10x10 jRD10x10
#define jpeg_idct_11x11 jRD11x11
#define jpeg_idct_12x12 jRD12x12
#define jpeg_idct_13x13 jRD13x13
#define jpeg_idct_14x14 jRD14x14
#define jpeg_idct_15x15 jRD15x15
#define jpeg_idct_16x16 jRD16x16
#define jpeg_idct_16x8 jRD16x8
#define jpeg_idct_14x7 jRD14x7
#define jpeg_idct_12x6 jRD12x6
#define jpeg_idct_10x5 jRD10x5
#define jpeg_idct_8x4 jRD8x4
#define jpeg_idct_6x3 jRD6x3
#define jpeg_idct_4x2 jRD4x2
#define jpeg_idct_2x1 jRD2x1
#define jpeg_idct_8x16 jRD8x16
#define jpeg_idct_7x14 jRD7x14
#define jpeg_idct_6x12 jRD6x12
#define jpeg_idct_5x10 jRD5x10
#define jpeg_idct_4x8 jRD4x8
#define jpeg_idct_3x6 jRD3x8
#define jpeg_idct_2x4 jRD2x4
#define jpeg_idct_1x2 jRD1x2
#endif /* NEED_SHORT_EXTERNAL_NAMES */
/* Extern declarations for the forward and inverse DCT routines. */
EXTERN(void) jpeg_fdct_islow
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_ifast
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_float
JPP((FAST_FLOAT * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_7x7
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_6x6
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_5x5
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_4x4
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_3x3
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_2x2
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_1x1
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_9x9
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_10x10
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_11x11
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_12x12
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_13x13
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_14x14
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_15x15
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_16x16
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_16x8
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_14x7
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_12x6
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_10x5
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_8x4
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_6x3
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_4x2
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_2x1
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_8x16
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_7x14
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_6x12
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_5x10
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_4x8
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_3x6
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_2x4
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_fdct_1x2
JPP((DCTELEM * data, JSAMPARRAY sample_data, JDIMENSION start_col));
EXTERN(void) jpeg_idct_islow
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_ifast
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_float
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_7x7
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_6x6
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_5x5
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_4x4
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_3x3
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_2x2
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_1x1
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_9x9
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_10x10
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_11x11
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_12x12
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_13x13
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_14x14
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_15x15
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_16x16
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_16x8
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_14x7
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_12x6
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_10x5
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_8x4
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_6x3
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_4x2
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_2x1
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_8x16
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_7x14
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_6x12
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_5x10
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_4x8
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_3x6
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_2x4
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
EXTERN(void) jpeg_idct_1x2
JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
/*
* Macros for handling fixed-point arithmetic; these are used by many
* but not all of the DCT/IDCT modules.
*
* All values are expected to be of type INT32.
* Fractional constants are scaled left by CONST_BITS bits.
* CONST_BITS is defined within each module using these macros,
* and may differ from one module to the next.
*/
#define ONE ((INT32) 1)
#define CONST_SCALE (ONE << CONST_BITS)
/* Convert a positive real constant to an integer scaled by CONST_SCALE.
* Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
* thus causing a lot of useless floating-point operations at run time.
*/
#define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
/* Descale and correctly round an INT32 value that's scaled by N bits.
* We assume RIGHT_SHIFT rounds towards minus infinity, so adding
* the fudge factor is correct for either sign of X.
*/
#define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
* This macro is used only when the two inputs will actually be no more than
* 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
* full 32x32 multiply. This provides a useful speedup on many machines.
* Unfortunately there is no way to specify a 16x16->32 multiply portably
* in C, but some C compilers will do the right thing if you provide the
* correct combination of casts.
*/
#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
#define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
#endif
#ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
#define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
#endif
#ifndef MULTIPLY16C16 /* default definition */
#define MULTIPLY16C16(var,const) ((var) * (const))
#endif
/* Same except both inputs are variables. */
#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
#define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
#endif
#ifndef MULTIPLY16V16 /* default definition */
#define MULTIPLY16V16(var1,var2) ((var1) * (var2))
#endif
|
1137519-player
|
jpeg-7/jdct.h
|
C
|
lgpl
| 17,145
|
/*
* jversion.h
*
* Copyright (C) 1991-2009, Thomas G. Lane, Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains software version identification.
*/
#define JVERSION "7 27-Jun-2009"
#define JCOPYRIGHT "Copyright (C) 2009, Thomas G. Lane, Guido Vollbeding"
|
1137519-player
|
jpeg-7/jversion.h
|
C
|
lgpl
| 395
|
/*
* jcarith.c
*
* Developed 1997 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains portable arithmetic entropy encoding routines for JPEG
* (implementing the ISO/IEC IS 10918-1 and CCITT Recommendation ITU-T T.81).
*
* Both sequential and progressive modes are supported in this single module.
*
* Suspension is not currently supported in this module.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/* Expanded entropy encoder object for arithmetic encoding. */
typedef struct {
struct jpeg_entropy_encoder pub; /* public fields */
INT32 c; /* C register, base of coding interval, layout as in sec. D.1.3 */
INT32 a; /* A register, normalized size of coding interval */
INT32 sc; /* counter for stacked 0xFF values which might overflow */
INT32 zc; /* counter for pending 0x00 output values which might *
* be discarded at the end ("Pacman" termination) */
int ct; /* bit shift counter, determines when next byte will be written */
int buffer; /* buffer for most recent output byte != 0xFF */
int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
int dc_context[MAX_COMPS_IN_SCAN]; /* context index for DC conditioning */
unsigned int restarts_to_go; /* MCUs left in this restart interval */
int next_restart_num; /* next restart number to write (0-7) */
/* Pointers to statistics areas (these workspaces have image lifespan) */
unsigned char * dc_stats[NUM_ARITH_TBLS];
unsigned char * ac_stats[NUM_ARITH_TBLS];
} arith_entropy_encoder;
typedef arith_entropy_encoder * arith_entropy_ptr;
/* The following two definitions specify the allocation chunk size
* for the statistics area.
* According to sections F.1.4.4.1.3 and F.1.4.4.2, we need at least
* 49 statistics bins for DC, and 245 statistics bins for AC coding.
* Note that we use one additional AC bin for codings with fixed
* probability (0.5), thus the minimum number for AC is 246.
*
* We use a compact representation with 1 byte per statistics bin,
* thus the numbers directly represent byte sizes.
* This 1 byte per statistics bin contains the meaning of the MPS
* (more probable symbol) in the highest bit (mask 0x80), and the
* index into the probability estimation state machine table
* in the lower bits (mask 0x7F).
*/
#define DC_STAT_BINS 64
#define AC_STAT_BINS 256
/* NOTE: Uncomment the following #define if you want to use the
* given formula for calculating the AC conditioning parameter Kx
* for spectral selection progressive coding in section G.1.3.2
* of the spec (Kx = Kmin + SRL (8 + Se - Kmin) 4).
* Although the spec and P&M authors claim that this "has proven
* to give good results for 8 bit precision samples", I'm not
* convinced yet that this is really beneficial.
* Early tests gave only very marginal compression enhancements
* (a few - around 5 or so - bytes even for very large files),
* which would turn out rather negative if we'd suppress the
* DAC (Define Arithmetic Conditioning) marker segments for
* the default parameters in the future.
* Note that currently the marker writing module emits 12-byte
* DAC segments for a full-component scan in a color image.
* This is not worth worrying about IMHO. However, since the
* spec defines the default values to be used if the tables
* are omitted (unlike Huffman tables, which are required
* anyway), one might optimize this behaviour in the future,
* and then it would be disadvantageous to use custom tables if
* they don't provide sufficient gain to exceed the DAC size.
*
* On the other hand, I'd consider it as a reasonable result
* that the conditioning has no significant influence on the
* compression performance. This means that the basic
* statistical model is already rather stable.
*
* Thus, at the moment, we use the default conditioning values
* anyway, and do not use the custom formula.
*
#define CALCULATE_SPECTRAL_CONDITIONING
*/
/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
* We assume that int right shift is unsigned if INT32 right shift is,
* which should be safe.
*/
#ifdef RIGHT_SHIFT_IS_UNSIGNED
#define ISHIFT_TEMPS int ishift_temp;
#define IRIGHT_SHIFT(x,shft) \
((ishift_temp = (x)) < 0 ? \
(ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
(ishift_temp >> (shft)))
#else
#define ISHIFT_TEMPS
#define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
#endif
LOCAL(void)
emit_byte (int val, j_compress_ptr cinfo)
/* Write next output byte; we do not support suspension in this module. */
{
struct jpeg_destination_mgr * dest = cinfo->dest;
*dest->next_output_byte++ = (JOCTET) val;
if (--dest->free_in_buffer == 0)
if (! (*dest->empty_output_buffer) (cinfo))
ERREXIT(cinfo, JERR_CANT_SUSPEND);
}
/*
* Finish up at the end of an arithmetic-compressed scan.
*/
METHODDEF(void)
finish_pass (j_compress_ptr cinfo)
{
arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
INT32 temp;
/* Section D.1.8: Termination of encoding */
/* Find the e->c in the coding interval with the largest
* number of trailing zero bits */
if ((temp = (e->a - 1 + e->c) & 0xFFFF0000L) < e->c)
e->c = temp + 0x8000L;
else
e->c = temp;
/* Send remaining bytes to output */
e->c <<= e->ct;
if (e->c & 0xF8000000L) {
/* One final overflow has to be handled */
if (e->buffer >= 0) {
if (e->zc)
do emit_byte(0x00, cinfo);
while (--e->zc);
emit_byte(e->buffer + 1, cinfo);
if (e->buffer + 1 == 0xFF)
emit_byte(0x00, cinfo);
}
e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */
e->sc = 0;
} else {
if (e->buffer == 0)
++e->zc;
else if (e->buffer >= 0) {
if (e->zc)
do emit_byte(0x00, cinfo);
while (--e->zc);
emit_byte(e->buffer, cinfo);
}
if (e->sc) {
if (e->zc)
do emit_byte(0x00, cinfo);
while (--e->zc);
do {
emit_byte(0xFF, cinfo);
emit_byte(0x00, cinfo);
} while (--e->sc);
}
}
/* Output final bytes only if they are not 0x00 */
if (e->c & 0x7FFF800L) {
if (e->zc) /* output final pending zero bytes */
do emit_byte(0x00, cinfo);
while (--e->zc);
emit_byte((e->c >> 19) & 0xFF, cinfo);
if (((e->c >> 19) & 0xFF) == 0xFF)
emit_byte(0x00, cinfo);
if (e->c & 0x7F800L) {
emit_byte((e->c >> 11) & 0xFF, cinfo);
if (((e->c >> 11) & 0xFF) == 0xFF)
emit_byte(0x00, cinfo);
}
}
}
/*
* The core arithmetic encoding routine (common in JPEG and JBIG).
* This needs to go as fast as possible.
* Machine-dependent optimization facilities
* are not utilized in this portable implementation.
* However, this code should be fairly efficient and
* may be a good base for further optimizations anyway.
*
* Parameter 'val' to be encoded may be 0 or 1 (binary decision).
*
* Note: I've added full "Pacman" termination support to the
* byte output routines, which is equivalent to the optional
* Discard_final_zeros procedure (Figure D.15) in the spec.
* Thus, we always produce the shortest possible output
* stream compliant to the spec (no trailing zero bytes,
* except for FF stuffing).
*
* I've also introduced a new scheme for accessing
* the probability estimation state machine table,
* derived from Markus Kuhn's JBIG implementation.
*/
LOCAL(void)
arith_encode (j_compress_ptr cinfo, unsigned char *st, int val)
{
extern const INT32 jaritab[];
register arith_entropy_ptr e = (arith_entropy_ptr) cinfo->entropy;
register unsigned char nl, nm;
register INT32 qe, temp;
register int sv;
/* Fetch values from our compact representation of Table D.2:
* Qe values and probability estimation state machine
*/
sv = *st;
qe = jaritab[sv & 0x7F]; /* => Qe_Value */
nl = qe & 0xFF; qe >>= 8; /* Next_Index_LPS + Switch_MPS */
nm = qe & 0xFF; qe >>= 8; /* Next_Index_MPS */
/* Encode & estimation procedures per sections D.1.4 & D.1.5 */
e->a -= qe;
if (val != (sv >> 7)) {
/* Encode the less probable symbol */
if (e->a >= qe) {
/* If the interval size (qe) for the less probable symbol (LPS)
* is larger than the interval size for the MPS, then exchange
* the two symbols for coding efficiency, otherwise code the LPS
* as usual: */
e->c += e->a;
e->a = qe;
}
*st = (sv & 0x80) ^ nl; /* Estimate_after_LPS */
} else {
/* Encode the more probable symbol */
if (e->a >= 0x8000L)
return; /* A >= 0x8000 -> ready, no renormalization required */
if (e->a < qe) {
/* If the interval size (qe) for the less probable symbol (LPS)
* is larger than the interval size for the MPS, then exchange
* the two symbols for coding efficiency: */
e->c += e->a;
e->a = qe;
}
*st = (sv & 0x80) ^ nm; /* Estimate_after_MPS */
}
/* Renormalization & data output per section D.1.6 */
do {
e->a <<= 1;
e->c <<= 1;
if (--e->ct == 0) {
/* Another byte is ready for output */
temp = e->c >> 19;
if (temp > 0xFF) {
/* Handle overflow over all stacked 0xFF bytes */
if (e->buffer >= 0) {
if (e->zc)
do emit_byte(0x00, cinfo);
while (--e->zc);
emit_byte(e->buffer + 1, cinfo);
if (e->buffer + 1 == 0xFF)
emit_byte(0x00, cinfo);
}
e->zc += e->sc; /* carry-over converts stacked 0xFF bytes to 0x00 */
e->sc = 0;
/* Note: The 3 spacer bits in the C register guarantee
* that the new buffer byte can't be 0xFF here
* (see page 160 in the P&M JPEG book). */
e->buffer = temp & 0xFF; /* new output byte, might overflow later */
} else if (temp == 0xFF) {
++e->sc; /* stack 0xFF byte (which might overflow later) */
} else {
/* Output all stacked 0xFF bytes, they will not overflow any more */
if (e->buffer == 0)
++e->zc;
else if (e->buffer >= 0) {
if (e->zc)
do emit_byte(0x00, cinfo);
while (--e->zc);
emit_byte(e->buffer, cinfo);
}
if (e->sc) {
if (e->zc)
do emit_byte(0x00, cinfo);
while (--e->zc);
do {
emit_byte(0xFF, cinfo);
emit_byte(0x00, cinfo);
} while (--e->sc);
}
e->buffer = temp & 0xFF; /* new output byte (can still overflow) */
}
e->c &= 0x7FFFFL;
e->ct += 8;
}
} while (e->a < 0x8000L);
}
/*
* Emit a restart marker & resynchronize predictions.
*/
LOCAL(void)
emit_restart (j_compress_ptr cinfo, int restart_num)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
int ci;
jpeg_component_info * compptr;
finish_pass(cinfo);
emit_byte(0xFF, cinfo);
emit_byte(JPEG_RST0 + restart_num, cinfo);
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
/* Re-initialize statistics areas */
if (cinfo->progressive_mode == 0 || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
MEMZERO(entropy->dc_stats[compptr->dc_tbl_no], DC_STAT_BINS);
/* Reset DC predictions to 0 */
entropy->last_dc_val[ci] = 0;
entropy->dc_context[ci] = 0;
}
if (cinfo->progressive_mode == 0 || cinfo->Ss) {
MEMZERO(entropy->ac_stats[compptr->ac_tbl_no], AC_STAT_BINS);
}
}
/* Reset arithmetic encoding variables */
entropy->c = 0;
entropy->a = 0x10000L;
entropy->sc = 0;
entropy->zc = 0;
entropy->ct = 11;
entropy->buffer = -1; /* empty */
}
/*
* MCU encoding for DC initial scan (either spectral selection,
* or first pass of successive approximation).
*/
METHODDEF(boolean)
encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
JBLOCKROW block;
unsigned char *st;
int blkn, ci, tbl;
int v, v2, m;
ISHIFT_TEMPS
/* Emit restart marker if needed */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0) {
emit_restart(cinfo, entropy->next_restart_num);
entropy->restarts_to_go = cinfo->restart_interval;
entropy->next_restart_num++;
entropy->next_restart_num &= 7;
}
entropy->restarts_to_go--;
}
/* Encode the MCU data blocks */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
block = MCU_data[blkn];
ci = cinfo->MCU_membership[blkn];
tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
/* Compute the DC value after the required point transform by Al.
* This is simply an arithmetic right shift.
*/
m = IRIGHT_SHIFT((int) ((*block)[0]), cinfo->Al);
/* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */
/* Table F.4: Point to statistics bin S0 for DC coefficient coding */
st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
/* Figure F.4: Encode_DC_DIFF */
if ((v = m - entropy->last_dc_val[ci]) == 0) {
arith_encode(cinfo, st, 0);
entropy->dc_context[ci] = 0; /* zero diff category */
} else {
entropy->last_dc_val[ci] = m;
arith_encode(cinfo, st, 1);
/* Figure F.6: Encoding nonzero value v */
/* Figure F.7: Encoding the sign of v */
if (v > 0) {
arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
st += 2; /* Table F.4: SP = S0 + 2 */
entropy->dc_context[ci] = 4; /* small positive diff category */
} else {
v = -v;
arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
st += 3; /* Table F.4: SN = S0 + 3 */
entropy->dc_context[ci] = 8; /* small negative diff category */
}
/* Figure F.8: Encoding the magnitude category of v */
m = 0;
if (v -= 1) {
arith_encode(cinfo, st, 1);
m = 1;
v2 = v;
st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
while (v2 >>= 1) {
arith_encode(cinfo, st, 1);
m <<= 1;
st += 1;
}
}
arith_encode(cinfo, st, 0);
/* Section F.1.4.4.1.2: Establish dc_context conditioning category */
if (m < (int) (((INT32) 1 << cinfo->arith_dc_L[tbl]) >> 1))
entropy->dc_context[ci] = 0; /* zero diff category */
else if (m > (int) (((INT32) 1 << cinfo->arith_dc_U[tbl]) >> 1))
entropy->dc_context[ci] += 8; /* large diff category */
/* Figure F.9: Encoding the magnitude bit pattern of v */
st += 14;
while (m >>= 1)
arith_encode(cinfo, st, (m & v) ? 1 : 0);
}
}
return TRUE;
}
/*
* MCU encoding for AC initial scan (either spectral selection,
* or first pass of successive approximation).
*/
METHODDEF(boolean)
encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
JBLOCKROW block;
unsigned char *st;
int tbl, k, ke;
int v, v2, m;
/* Emit restart marker if needed */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0) {
emit_restart(cinfo, entropy->next_restart_num);
entropy->restarts_to_go = cinfo->restart_interval;
entropy->next_restart_num++;
entropy->next_restart_num &= 7;
}
entropy->restarts_to_go--;
}
/* Encode the MCU data block */
block = MCU_data[0];
tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
/* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
/* Establish EOB (end-of-block) index */
for (ke = cinfo->Se + 1; ke > 1; ke--)
/* We must apply the point transform by Al. For AC coefficients this
* is an integer division with rounding towards 0. To do this portably
* in C, we shift after obtaining the absolute value.
*/
if ((v = (*block)[jpeg_natural_order[ke - 1]]) >= 0) {
if (v >>= cinfo->Al) break;
} else {
v = -v;
if (v >>= cinfo->Al) break;
}
/* Figure F.5: Encode_AC_Coefficients */
for (k = cinfo->Ss; k < ke; k++) {
st = entropy->ac_stats[tbl] + 3 * (k - 1);
arith_encode(cinfo, st, 0); /* EOB decision */
entropy->ac_stats[tbl][245] = 0;
for (;;) {
if ((v = (*block)[jpeg_natural_order[k]]) >= 0) {
if (v >>= cinfo->Al) {
arith_encode(cinfo, st + 1, 1);
arith_encode(cinfo, entropy->ac_stats[tbl] + 245, 0);
break;
}
} else {
v = -v;
if (v >>= cinfo->Al) {
arith_encode(cinfo, st + 1, 1);
arith_encode(cinfo, entropy->ac_stats[tbl] + 245, 1);
break;
}
}
arith_encode(cinfo, st + 1, 0); st += 3; k++;
}
st += 2;
/* Figure F.8: Encoding the magnitude category of v */
m = 0;
if (v -= 1) {
arith_encode(cinfo, st, 1);
m = 1;
v2 = v;
if (v2 >>= 1) {
arith_encode(cinfo, st, 1);
m <<= 1;
st = entropy->ac_stats[tbl] +
(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
while (v2 >>= 1) {
arith_encode(cinfo, st, 1);
m <<= 1;
st += 1;
}
}
}
arith_encode(cinfo, st, 0);
/* Figure F.9: Encoding the magnitude bit pattern of v */
st += 14;
while (m >>= 1)
arith_encode(cinfo, st, (m & v) ? 1 : 0);
}
/* Encode EOB decision only if k <= cinfo->Se */
if (k <= cinfo->Se) {
st = entropy->ac_stats[tbl] + 3 * (k - 1);
arith_encode(cinfo, st, 1);
}
return TRUE;
}
/*
* MCU encoding for DC successive approximation refinement scan.
*/
METHODDEF(boolean)
encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
unsigned char st[4];
int Al, blkn;
/* Emit restart marker if needed */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0) {
emit_restart(cinfo, entropy->next_restart_num);
entropy->restarts_to_go = cinfo->restart_interval;
entropy->next_restart_num++;
entropy->next_restart_num &= 7;
}
entropy->restarts_to_go--;
}
Al = cinfo->Al;
/* Encode the MCU data blocks */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
st[0] = 0; /* use fixed probability estimation */
/* We simply emit the Al'th bit of the DC coefficient value. */
arith_encode(cinfo, st, (MCU_data[blkn][0][0] >> Al) & 1);
}
return TRUE;
}
/*
* MCU encoding for AC successive approximation refinement scan.
*/
METHODDEF(boolean)
encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
JBLOCKROW block;
unsigned char *st;
int tbl, k, ke, kex;
int v;
/* Emit restart marker if needed */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0) {
emit_restart(cinfo, entropy->next_restart_num);
entropy->restarts_to_go = cinfo->restart_interval;
entropy->next_restart_num++;
entropy->next_restart_num &= 7;
}
entropy->restarts_to_go--;
}
/* Encode the MCU data block */
block = MCU_data[0];
tbl = cinfo->cur_comp_info[0]->ac_tbl_no;
/* Section G.1.3.3: Encoding of AC coefficients */
/* Establish EOB (end-of-block) index */
for (ke = cinfo->Se + 1; ke > 1; ke--)
/* We must apply the point transform by Al. For AC coefficients this
* is an integer division with rounding towards 0. To do this portably
* in C, we shift after obtaining the absolute value.
*/
if ((v = (*block)[jpeg_natural_order[ke - 1]]) >= 0) {
if (v >>= cinfo->Al) break;
} else {
v = -v;
if (v >>= cinfo->Al) break;
}
/* Establish EOBx (previous stage end-of-block) index */
for (kex = ke; kex > 1; kex--)
if ((v = (*block)[jpeg_natural_order[kex - 1]]) >= 0) {
if (v >>= cinfo->Ah) break;
} else {
v = -v;
if (v >>= cinfo->Ah) break;
}
/* Figure G.10: Encode_AC_Coefficients_SA */
for (k = cinfo->Ss; k < ke; k++) {
st = entropy->ac_stats[tbl] + 3 * (k - 1);
if (k >= kex)
arith_encode(cinfo, st, 0); /* EOB decision */
entropy->ac_stats[tbl][245] = 0;
for (;;) {
if ((v = (*block)[jpeg_natural_order[k]]) >= 0) {
if (v >>= cinfo->Al) {
if (v >> 1) /* previously nonzero coef */
arith_encode(cinfo, st + 2, (v & 1));
else { /* newly nonzero coef */
arith_encode(cinfo, st + 1, 1);
arith_encode(cinfo, entropy->ac_stats[tbl] + 245, 0);
}
break;
}
} else {
v = -v;
if (v >>= cinfo->Al) {
if (v >> 1) /* previously nonzero coef */
arith_encode(cinfo, st + 2, (v & 1));
else { /* newly nonzero coef */
arith_encode(cinfo, st + 1, 1);
arith_encode(cinfo, entropy->ac_stats[tbl] + 245, 1);
}
break;
}
}
arith_encode(cinfo, st + 1, 0); st += 3; k++;
}
}
/* Encode EOB decision only if k <= cinfo->Se */
if (k <= cinfo->Se) {
st = entropy->ac_stats[tbl] + 3 * (k - 1);
arith_encode(cinfo, st, 1);
}
return TRUE;
}
/*
* Encode and output one MCU's worth of arithmetic-compressed coefficients.
*/
METHODDEF(boolean)
encode_mcu (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
jpeg_component_info * compptr;
JBLOCKROW block;
unsigned char *st;
int blkn, ci, tbl, k, ke;
int v, v2, m;
/* Emit restart marker if needed */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0) {
emit_restart(cinfo, entropy->next_restart_num);
entropy->restarts_to_go = cinfo->restart_interval;
entropy->next_restart_num++;
entropy->next_restart_num &= 7;
}
entropy->restarts_to_go--;
}
/* Encode the MCU data blocks */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
block = MCU_data[blkn];
ci = cinfo->MCU_membership[blkn];
compptr = cinfo->cur_comp_info[ci];
/* Sections F.1.4.1 & F.1.4.4.1: Encoding of DC coefficients */
tbl = compptr->dc_tbl_no;
/* Table F.4: Point to statistics bin S0 for DC coefficient coding */
st = entropy->dc_stats[tbl] + entropy->dc_context[ci];
/* Figure F.4: Encode_DC_DIFF */
if ((v = (*block)[0] - entropy->last_dc_val[ci]) == 0) {
arith_encode(cinfo, st, 0);
entropy->dc_context[ci] = 0; /* zero diff category */
} else {
entropy->last_dc_val[ci] = (*block)[0];
arith_encode(cinfo, st, 1);
/* Figure F.6: Encoding nonzero value v */
/* Figure F.7: Encoding the sign of v */
if (v > 0) {
arith_encode(cinfo, st + 1, 0); /* Table F.4: SS = S0 + 1 */
st += 2; /* Table F.4: SP = S0 + 2 */
entropy->dc_context[ci] = 4; /* small positive diff category */
} else {
v = -v;
arith_encode(cinfo, st + 1, 1); /* Table F.4: SS = S0 + 1 */
st += 3; /* Table F.4: SN = S0 + 3 */
entropy->dc_context[ci] = 8; /* small negative diff category */
}
/* Figure F.8: Encoding the magnitude category of v */
m = 0;
if (v -= 1) {
arith_encode(cinfo, st, 1);
m = 1;
v2 = v;
st = entropy->dc_stats[tbl] + 20; /* Table F.4: X1 = 20 */
while (v2 >>= 1) {
arith_encode(cinfo, st, 1);
m <<= 1;
st += 1;
}
}
arith_encode(cinfo, st, 0);
/* Section F.1.4.4.1.2: Establish dc_context conditioning category */
if (m < (int) (((INT32) 1 << cinfo->arith_dc_L[tbl]) >> 1))
entropy->dc_context[ci] = 0; /* zero diff category */
else if (m > (int) (((INT32) 1 << cinfo->arith_dc_U[tbl]) >> 1))
entropy->dc_context[ci] += 8; /* large diff category */
/* Figure F.9: Encoding the magnitude bit pattern of v */
st += 14;
while (m >>= 1)
arith_encode(cinfo, st, (m & v) ? 1 : 0);
}
/* Sections F.1.4.2 & F.1.4.4.2: Encoding of AC coefficients */
tbl = compptr->ac_tbl_no;
/* Establish EOB (end-of-block) index */
for (ke = DCTSIZE2; ke > 1; ke--)
if ((*block)[jpeg_natural_order[ke - 1]]) break;
/* Figure F.5: Encode_AC_Coefficients */
for (k = 1; k < ke; k++) {
st = entropy->ac_stats[tbl] + 3 * (k - 1);
arith_encode(cinfo, st, 0); /* EOB decision */
while ((v = (*block)[jpeg_natural_order[k]]) == 0) {
arith_encode(cinfo, st + 1, 0); st += 3; k++;
}
arith_encode(cinfo, st + 1, 1);
/* Figure F.6: Encoding nonzero value v */
/* Figure F.7: Encoding the sign of v */
entropy->ac_stats[tbl][245] = 0;
if (v > 0) {
arith_encode(cinfo, entropy->ac_stats[tbl] + 245, 0);
} else {
v = -v;
arith_encode(cinfo, entropy->ac_stats[tbl] + 245, 1);
}
st += 2;
/* Figure F.8: Encoding the magnitude category of v */
m = 0;
if (v -= 1) {
arith_encode(cinfo, st, 1);
m = 1;
v2 = v;
if (v2 >>= 1) {
arith_encode(cinfo, st, 1);
m <<= 1;
st = entropy->ac_stats[tbl] +
(k <= cinfo->arith_ac_K[tbl] ? 189 : 217);
while (v2 >>= 1) {
arith_encode(cinfo, st, 1);
m <<= 1;
st += 1;
}
}
}
arith_encode(cinfo, st, 0);
/* Figure F.9: Encoding the magnitude bit pattern of v */
st += 14;
while (m >>= 1)
arith_encode(cinfo, st, (m & v) ? 1 : 0);
}
/* Encode EOB decision only if k < DCTSIZE2 */
if (k < DCTSIZE2) {
st = entropy->ac_stats[tbl] + 3 * (k - 1);
arith_encode(cinfo, st, 1);
}
}
return TRUE;
}
/*
* Initialize for an arithmetic-compressed scan.
*/
METHODDEF(void)
start_pass (j_compress_ptr cinfo, boolean gather_statistics)
{
arith_entropy_ptr entropy = (arith_entropy_ptr) cinfo->entropy;
int ci, tbl;
jpeg_component_info * compptr;
if (gather_statistics)
/* Make sure to avoid that in the master control logic!
* We are fully adaptive here and need no extra
* statistics gathering pass!
*/
ERREXIT(cinfo, JERR_NOT_COMPILED);
/* We assume jcmaster.c already validated the progressive scan parameters. */
/* Select execution routines */
if (cinfo->progressive_mode) {
if (cinfo->Ah == 0) {
if (cinfo->Ss == 0)
entropy->pub.encode_mcu = encode_mcu_DC_first;
else
entropy->pub.encode_mcu = encode_mcu_AC_first;
} else {
if (cinfo->Ss == 0)
entropy->pub.encode_mcu = encode_mcu_DC_refine;
else
entropy->pub.encode_mcu = encode_mcu_AC_refine;
}
} else
entropy->pub.encode_mcu = encode_mcu;
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
/* Allocate & initialize requested statistics areas */
if (cinfo->progressive_mode == 0 || (cinfo->Ss == 0 && cinfo->Ah == 0)) {
tbl = compptr->dc_tbl_no;
if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
if (entropy->dc_stats[tbl] == NULL)
entropy->dc_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo, JPOOL_IMAGE, DC_STAT_BINS);
MEMZERO(entropy->dc_stats[tbl], DC_STAT_BINS);
/* Initialize DC predictions to 0 */
entropy->last_dc_val[ci] = 0;
entropy->dc_context[ci] = 0;
}
if (cinfo->progressive_mode == 0 || cinfo->Ss) {
tbl = compptr->ac_tbl_no;
if (tbl < 0 || tbl >= NUM_ARITH_TBLS)
ERREXIT1(cinfo, JERR_NO_ARITH_TABLE, tbl);
if (entropy->ac_stats[tbl] == NULL)
entropy->ac_stats[tbl] = (unsigned char *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo, JPOOL_IMAGE, AC_STAT_BINS);
MEMZERO(entropy->ac_stats[tbl], AC_STAT_BINS);
#ifdef CALCULATE_SPECTRAL_CONDITIONING
if (cinfo->progressive_mode)
/* Section G.1.3.2: Set appropriate arithmetic conditioning value Kx */
cinfo->arith_ac_K[tbl] = cinfo->Ss + ((8 + cinfo->Se - cinfo->Ss) >> 4);
#endif
}
}
/* Initialize arithmetic encoding variables */
entropy->c = 0;
entropy->a = 0x10000L;
entropy->sc = 0;
entropy->zc = 0;
entropy->ct = 11;
entropy->buffer = -1; /* empty */
/* Initialize restart stuff */
entropy->restarts_to_go = cinfo->restart_interval;
entropy->next_restart_num = 0;
}
/*
* Module initialization routine for arithmetic entropy encoding.
*/
GLOBAL(void)
jinit_arith_encoder (j_compress_ptr cinfo)
{
arith_entropy_ptr entropy;
int i;
entropy = (arith_entropy_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(arith_entropy_encoder));
cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
entropy->pub.start_pass = start_pass;
entropy->pub.finish_pass = finish_pass;
/* Mark tables unallocated */
for (i = 0; i < NUM_ARITH_TBLS; i++) {
entropy->dc_stats[i] = NULL;
entropy->ac_stats[i] = NULL;
}
}
|
1137519-player
|
jpeg-7/jcarith.c
|
C
|
lgpl
| 28,108
|
/*
* rdppm.c
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* Modified 2009 by Bill Allombert, Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains routines to read input images in PPM/PGM format.
* The extended 2-byte-per-sample raw PPM/PGM formats are supported.
* The PBMPLUS library is NOT required to compile this software
* (but it is highly useful as a set of PPM image manipulation programs).
*
* These routines may need modification for non-Unix environments or
* specialized applications. As they stand, they assume input from
* an ordinary stdio stream. They further assume that reading begins
* at the start of the file; start_input may need work if the
* user interface has already read some data (e.g., to determine that
* the file is indeed PPM format).
*/
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#ifdef PPM_SUPPORTED
/* Portions of this code are based on the PBMPLUS library, which is:
**
** Copyright (C) 1988 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
*/
/* Macros to deal with unsigned chars as efficiently as compiler allows */
#ifdef HAVE_UNSIGNED_CHAR
typedef unsigned char U_CHAR;
#define UCH(x) ((int) (x))
#else /* !HAVE_UNSIGNED_CHAR */
#ifdef CHAR_IS_UNSIGNED
typedef char U_CHAR;
#define UCH(x) ((int) (x))
#else
typedef char U_CHAR;
#define UCH(x) ((int) (x) & 0xFF)
#endif
#endif /* HAVE_UNSIGNED_CHAR */
#define ReadOK(file,buffer,len) (JFREAD(file,buffer,len) == ((size_t) (len)))
/*
* On most systems, reading individual bytes with getc() is drastically less
* efficient than buffering a row at a time with fread(). On PCs, we must
* allocate the buffer in near data space, because we are assuming small-data
* memory model, wherein fread() can't reach far memory. If you need to
* process very wide images on a PC, you might have to compile in large-memory
* model, or else replace fread() with a getc() loop --- which will be much
* slower.
*/
/* Private version of data source object */
typedef struct {
struct cjpeg_source_struct pub; /* public fields */
U_CHAR *iobuffer; /* non-FAR pointer to I/O buffer */
JSAMPROW pixrow; /* FAR pointer to same */
size_t buffer_width; /* width of I/O buffer */
JSAMPLE *rescale; /* => maxval-remapping array, or NULL */
} ppm_source_struct;
typedef ppm_source_struct * ppm_source_ptr;
LOCAL(int)
pbm_getc (FILE * infile)
/* Read next char, skipping over any comments */
/* A comment/newline sequence is returned as a newline */
{
register int ch;
ch = getc(infile);
if (ch == '#') {
do {
ch = getc(infile);
} while (ch != '\n' && ch != EOF);
}
return ch;
}
LOCAL(unsigned int)
read_pbm_integer (j_compress_ptr cinfo, FILE * infile)
/* Read an unsigned decimal integer from the PPM file */
/* Swallows one trailing character after the integer */
/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
/* This should not be a problem in practice. */
{
register int ch;
register unsigned int val;
/* Skip any leading whitespace */
do {
ch = pbm_getc(infile);
if (ch == EOF)
ERREXIT(cinfo, JERR_INPUT_EOF);
} while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
if (ch < '0' || ch > '9')
ERREXIT(cinfo, JERR_PPM_NONNUMERIC);
val = ch - '0';
while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
val *= 10;
val += ch - '0';
}
return val;
}
/*
* Read one row of pixels.
*
* We provide several different versions depending on input file format.
* In all cases, input is scaled to the size of JSAMPLE.
*
* A really fast path is provided for reading byte/sample raw files with
* maxval = MAXJSAMPLE, which is the normal case for 8-bit data.
*/
METHODDEF(JDIMENSION)
get_text_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PGM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr) sinfo;
FILE * infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
ptr = source->pub.buffer[0];
for (col = cinfo->image_width; col > 0; col--) {
*ptr++ = rescale[read_pbm_integer(cinfo, infile)];
}
return 1;
}
METHODDEF(JDIMENSION)
get_text_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr) sinfo;
FILE * infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
ptr = source->pub.buffer[0];
for (col = cinfo->image_width; col > 0; col--) {
*ptr++ = rescale[read_pbm_integer(cinfo, infile)];
*ptr++ = rescale[read_pbm_integer(cinfo, infile)];
*ptr++ = rescale[read_pbm_integer(cinfo, infile)];
}
return 1;
}
METHODDEF(JDIMENSION)
get_scaled_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PGM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr) sinfo;
register JSAMPROW ptr;
register U_CHAR * bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
*ptr++ = rescale[UCH(*bufferptr++)];
}
return 1;
}
METHODDEF(JDIMENSION)
get_scaled_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr) sinfo;
register JSAMPROW ptr;
register U_CHAR * bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
*ptr++ = rescale[UCH(*bufferptr++)];
*ptr++ = rescale[UCH(*bufferptr++)];
*ptr++ = rescale[UCH(*bufferptr++)];
}
return 1;
}
METHODDEF(JDIMENSION)
get_raw_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format files with maxval = MAXJSAMPLE.
* In this case we just read right into the JSAMPLE buffer!
* Note that same code works for PPM and PGM files.
*/
{
ppm_source_ptr source = (ppm_source_ptr) sinfo;
if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
return 1;
}
METHODDEF(JDIMENSION)
get_word_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-word-format PGM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr) sinfo;
register JSAMPROW ptr;
register U_CHAR * bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
register int temp;
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
*ptr++ = rescale[temp];
}
return 1;
}
METHODDEF(JDIMENSION)
get_word_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-word-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr) sinfo;
register JSAMPROW ptr;
register U_CHAR * bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
register int temp;
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
*ptr++ = rescale[temp];
}
return 1;
}
/*
* Read the file header; return image size and component count.
*/
METHODDEF(void)
start_input_ppm (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
ppm_source_ptr source = (ppm_source_ptr) sinfo;
int c;
unsigned int w, h, maxval;
boolean need_iobuffer, use_raw_buffer, need_rescale;
if (getc(source->pub.input_file) != 'P')
ERREXIT(cinfo, JERR_PPM_NOT);
c = getc(source->pub.input_file); /* subformat discriminator character */
/* detect unsupported variants (ie, PBM) before trying to read header */
switch (c) {
case '2': /* it's a text-format PGM file */
case '3': /* it's a text-format PPM file */
case '5': /* it's a raw-format PGM file */
case '6': /* it's a raw-format PPM file */
break;
default:
ERREXIT(cinfo, JERR_PPM_NOT);
break;
}
/* fetch the remaining header info */
w = read_pbm_integer(cinfo, source->pub.input_file);
h = read_pbm_integer(cinfo, source->pub.input_file);
maxval = read_pbm_integer(cinfo, source->pub.input_file);
if (w <= 0 || h <= 0 || maxval <= 0) /* error check */
ERREXIT(cinfo, JERR_PPM_NOT);
cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */
cinfo->image_width = (JDIMENSION) w;
cinfo->image_height = (JDIMENSION) h;
/* initialize flags to most common settings */
need_iobuffer = TRUE; /* do we need an I/O buffer? */
use_raw_buffer = FALSE; /* do we map input buffer onto I/O buffer? */
need_rescale = TRUE; /* do we need a rescale array? */
switch (c) {
case '2': /* it's a text-format PGM file */
cinfo->input_components = 1;
cinfo->in_color_space = JCS_GRAYSCALE;
TRACEMS2(cinfo, 1, JTRC_PGM_TEXT, w, h);
source->pub.get_pixel_rows = get_text_gray_row;
need_iobuffer = FALSE;
break;
case '3': /* it's a text-format PPM file */
cinfo->input_components = 3;
cinfo->in_color_space = JCS_RGB;
TRACEMS2(cinfo, 1, JTRC_PPM_TEXT, w, h);
source->pub.get_pixel_rows = get_text_rgb_row;
need_iobuffer = FALSE;
break;
case '5': /* it's a raw-format PGM file */
cinfo->input_components = 1;
cinfo->in_color_space = JCS_GRAYSCALE;
TRACEMS2(cinfo, 1, JTRC_PGM, w, h);
if (maxval > 255) {
source->pub.get_pixel_rows = get_word_gray_row;
} else if (maxval == MAXJSAMPLE && SIZEOF(JSAMPLE) == SIZEOF(U_CHAR)) {
source->pub.get_pixel_rows = get_raw_row;
use_raw_buffer = TRUE;
need_rescale = FALSE;
} else {
source->pub.get_pixel_rows = get_scaled_gray_row;
}
break;
case '6': /* it's a raw-format PPM file */
cinfo->input_components = 3;
cinfo->in_color_space = JCS_RGB;
TRACEMS2(cinfo, 1, JTRC_PPM, w, h);
if (maxval > 255) {
source->pub.get_pixel_rows = get_word_rgb_row;
} else if (maxval == MAXJSAMPLE && SIZEOF(JSAMPLE) == SIZEOF(U_CHAR)) {
source->pub.get_pixel_rows = get_raw_row;
use_raw_buffer = TRUE;
need_rescale = FALSE;
} else {
source->pub.get_pixel_rows = get_scaled_rgb_row;
}
break;
}
/* Allocate space for I/O buffer: 1 or 3 bytes or words/pixel. */
if (need_iobuffer) {
source->buffer_width = (size_t) w * cinfo->input_components *
((maxval<=255) ? SIZEOF(U_CHAR) : (2*SIZEOF(U_CHAR)));
source->iobuffer = (U_CHAR *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
source->buffer_width);
}
/* Create compressor input buffer. */
if (use_raw_buffer) {
/* For unscaled raw-input case, we can just map it onto the I/O buffer. */
/* Synthesize a JSAMPARRAY pointer structure */
/* Cast here implies near->far pointer conversion on PCs */
source->pixrow = (JSAMPROW) source->iobuffer;
source->pub.buffer = & source->pixrow;
source->pub.buffer_height = 1;
} else {
/* Need to translate anyway, so make a separate sample buffer. */
source->pub.buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE,
(JDIMENSION) w * cinfo->input_components, (JDIMENSION) 1);
source->pub.buffer_height = 1;
}
/* Compute the rescaling array if required. */
if (need_rescale) {
INT32 val, half_maxval;
/* On 16-bit-int machines we have to be careful of maxval = 65535 */
source->rescale = (JSAMPLE *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
(size_t) (((long) maxval + 1L) * SIZEOF(JSAMPLE)));
half_maxval = maxval / 2;
for (val = 0; val <= (INT32) maxval; val++) {
/* The multiplication here must be done in 32 bits to avoid overflow */
source->rescale[val] = (JSAMPLE) ((val*MAXJSAMPLE + half_maxval)/maxval);
}
}
}
/*
* Finish up at the end of the file.
*/
METHODDEF(void)
finish_input_ppm (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
/* no work */
}
/*
* The module selection routine for PPM format input.
*/
GLOBAL(cjpeg_source_ptr)
jinit_read_ppm (j_compress_ptr cinfo)
{
ppm_source_ptr source;
/* Create module interface object */
source = (ppm_source_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(ppm_source_struct));
/* Fill in method ptrs, except get_pixel_rows which start_input sets */
source->pub.start_input = start_input_ppm;
source->pub.finish_input = finish_input_ppm;
return (cjpeg_source_ptr) source;
}
#endif /* PPM_SUPPORTED */
|
1137519-player
|
jpeg-7/rdppm.c
|
C
|
lgpl
| 14,078
|
/*
* jidctfst.c
*
* Copyright (C) 1994-1998, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains a fast, not so accurate integer implementation of the
* inverse DCT (Discrete Cosine Transform). In the IJG code, this routine
* must also perform dequantization of the input coefficients.
*
* A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
* on each row (or vice versa, but it's more convenient to emit a row at
* a time). Direct algorithms are also available, but they are much more
* complex and seem not to be any faster when reduced to code.
*
* This implementation is based on Arai, Agui, and Nakajima's algorithm for
* scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
* Japanese, but the algorithm is described in the Pennebaker & Mitchell
* JPEG textbook (see REFERENCES section in file README). The following code
* is based directly on figure 4-8 in P&M.
* While an 8-point DCT cannot be done in less than 11 multiplies, it is
* possible to arrange the computation so that many of the multiplies are
* simple scalings of the final outputs. These multiplies can then be
* folded into the multiplications or divisions by the JPEG quantization
* table entries. The AA&N method leaves only 5 multiplies and 29 adds
* to be done in the DCT itself.
* The primary disadvantage of this method is that with fixed-point math,
* accuracy is lost due to imprecise representation of the scaled
* quantization values. The smaller the quantization table entry, the less
* precise the scaled value, so this implementation does worse with high-
* quality-setting files than with low-quality ones.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jdct.h" /* Private declarations for DCT subsystem */
#ifdef DCT_IFAST_SUPPORTED
/*
* This module is specialized to the case DCTSIZE = 8.
*/
#if DCTSIZE != 8
Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
#endif
/* Scaling decisions are generally the same as in the LL&M algorithm;
* see jidctint.c for more details. However, we choose to descale
* (right shift) multiplication products as soon as they are formed,
* rather than carrying additional fractional bits into subsequent additions.
* This compromises accuracy slightly, but it lets us save a few shifts.
* More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
* everywhere except in the multiplications proper; this saves a good deal
* of work on 16-bit-int machines.
*
* The dequantized coefficients are not integers because the AA&N scaling
* factors have been incorporated. We represent them scaled up by PASS1_BITS,
* so that the first and second IDCT rounds have the same input scaling.
* For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
* avoid a descaling shift; this compromises accuracy rather drastically
* for small quantization table entries, but it saves a lot of shifts.
* For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
* so we use a much larger scaling factor to preserve accuracy.
*
* A final compromise is to represent the multiplicative constants to only
* 8 fractional bits, rather than 13. This saves some shifting work on some
* machines, and may also reduce the cost of multiplication (since there
* are fewer one-bits in the constants).
*/
#if BITS_IN_JSAMPLE == 8
#define CONST_BITS 8
#define PASS1_BITS 2
#else
#define CONST_BITS 8
#define PASS1_BITS 1 /* lose a little precision to avoid overflow */
#endif
/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
* causing a lot of useless floating-point operations at run time.
* To get around this we use the following pre-calculated constants.
* If you change CONST_BITS you may want to add appropriate values.
* (With a reasonable C compiler, you can just rely on the FIX() macro...)
*/
#if CONST_BITS == 8
#define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
#define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
#define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
#define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
#else
#define FIX_1_082392200 FIX(1.082392200)
#define FIX_1_414213562 FIX(1.414213562)
#define FIX_1_847759065 FIX(1.847759065)
#define FIX_2_613125930 FIX(2.613125930)
#endif
/* We can gain a little more speed, with a further compromise in accuracy,
* by omitting the addition in a descaling shift. This yields an incorrectly
* rounded result half the time...
*/
#ifndef USE_ACCURATE_ROUNDING
#undef DESCALE
#define DESCALE(x,n) RIGHT_SHIFT(x, n)
#endif
/* Multiply a DCTELEM variable by an INT32 constant, and immediately
* descale to yield a DCTELEM result.
*/
#define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
/* Dequantize a coefficient by multiplying it by the multiplier-table
* entry; produce a DCTELEM result. For 8-bit data a 16x16->16
* multiplication will do. For 12-bit data, the multiplier table is
* declared INT32, so a 32-bit multiply will be used.
*/
#if BITS_IN_JSAMPLE == 8
#define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
#else
#define DEQUANTIZE(coef,quantval) \
DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
#endif
/* Like DESCALE, but applies to a DCTELEM and produces an int.
* We assume that int right shift is unsigned if INT32 right shift is.
*/
#ifdef RIGHT_SHIFT_IS_UNSIGNED
#define ISHIFT_TEMPS DCTELEM ishift_temp;
#if BITS_IN_JSAMPLE == 8
#define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
#else
#define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
#endif
#define IRIGHT_SHIFT(x,shft) \
((ishift_temp = (x)) < 0 ? \
(ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
(ishift_temp >> (shft)))
#else
#define ISHIFT_TEMPS
#define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
#endif
#ifdef USE_ACCURATE_ROUNDING
#define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
#else
#define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
#endif
#define NO_ZERO_ROW_TEST
/*
* Perform dequantization and inverse DCT on one block of coefficients.
*/
GLOBAL(void)
jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
JCOEFPTR coef_block,
JSAMPARRAY output_buf, JDIMENSION output_col)
{
DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
DCTELEM tmp10, tmp11, tmp12, tmp13;
DCTELEM z5, z10, z11, z12, z13;
JCOEFPTR inptr;
IFAST_MULT_TYPE * quantptr;
int * wsptr;
JSAMPROW outptr;
JSAMPLE *range_limit = IDCT_range_limit(cinfo);
int ctr;
int workspace[DCTSIZE2]; /* buffers data between passes */
SHIFT_TEMPS /* for DESCALE */
ISHIFT_TEMPS /* for IDESCALE */
/* Pass 1: process columns from input, store into work array. */
inptr = coef_block;
quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
wsptr = workspace;
for (ctr = DCTSIZE; ctr > 0; ctr--) {
/* Due to quantization, we will usually find that many of the input
* coefficients are zero, especially the AC terms. We can exploit this
* by short-circuiting the IDCT calculation for any column in which all
* the AC terms are zero. In that case each output is equal to the
* DC coefficient (with scale factor as needed).
* With typical images and quantization tables, half or more of the
* column DCT calculations can be simplified this way.
*/
if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
inptr[DCTSIZE*7] == 0) {
/* AC terms all zero */
int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
wsptr[DCTSIZE*0] = dcval;
wsptr[DCTSIZE*1] = dcval;
wsptr[DCTSIZE*2] = dcval;
wsptr[DCTSIZE*3] = dcval;
wsptr[DCTSIZE*4] = dcval;
wsptr[DCTSIZE*5] = dcval;
wsptr[DCTSIZE*6] = dcval;
wsptr[DCTSIZE*7] = dcval;
inptr++; /* advance pointers to next column */
quantptr++;
wsptr++;
continue;
}
/* Even part */
tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
tmp10 = tmp0 + tmp2; /* phase 3 */
tmp11 = tmp0 - tmp2;
tmp13 = tmp1 + tmp3; /* phases 5-3 */
tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
tmp0 = tmp10 + tmp13; /* phase 2 */
tmp3 = tmp10 - tmp13;
tmp1 = tmp11 + tmp12;
tmp2 = tmp11 - tmp12;
/* Odd part */
tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
z13 = tmp6 + tmp5; /* phase 6 */
z10 = tmp6 - tmp5;
z11 = tmp4 + tmp7;
z12 = tmp4 - tmp7;
tmp7 = z11 + z13; /* phase 5 */
tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
tmp6 = tmp12 - tmp7; /* phase 2 */
tmp5 = tmp11 - tmp6;
tmp4 = tmp10 + tmp5;
wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
inptr++; /* advance pointers to next column */
quantptr++;
wsptr++;
}
/* Pass 2: process rows from work array, store into output array. */
/* Note that we must descale the results by a factor of 8 == 2**3, */
/* and also undo the PASS1_BITS scaling. */
wsptr = workspace;
for (ctr = 0; ctr < DCTSIZE; ctr++) {
outptr = output_buf[ctr] + output_col;
/* Rows of zeroes can be exploited in the same way as we did with columns.
* However, the column calculation has created many nonzero AC terms, so
* the simplification applies less often (typically 5% to 10% of the time).
* On machines with very fast multiplication, it's possible that the
* test takes more time than it's worth. In that case this section
* may be commented out.
*/
#ifndef NO_ZERO_ROW_TEST
if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
/* AC terms all zero */
JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
& RANGE_MASK];
outptr[0] = dcval;
outptr[1] = dcval;
outptr[2] = dcval;
outptr[3] = dcval;
outptr[4] = dcval;
outptr[5] = dcval;
outptr[6] = dcval;
outptr[7] = dcval;
wsptr += DCTSIZE; /* advance pointer to next row */
continue;
}
#endif
/* Even part */
tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
- tmp13;
tmp0 = tmp10 + tmp13;
tmp3 = tmp10 - tmp13;
tmp1 = tmp11 + tmp12;
tmp2 = tmp11 - tmp12;
/* Odd part */
z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
tmp7 = z11 + z13; /* phase 5 */
tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
tmp6 = tmp12 - tmp7; /* phase 2 */
tmp5 = tmp11 - tmp6;
tmp4 = tmp10 + tmp5;
/* Final output stage: scale down by a factor of 8 and range-limit */
outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
& RANGE_MASK];
outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
& RANGE_MASK];
outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
& RANGE_MASK];
outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
& RANGE_MASK];
outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
& RANGE_MASK];
outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
& RANGE_MASK];
outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
& RANGE_MASK];
outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
& RANGE_MASK];
wsptr += DCTSIZE; /* advance pointer to next row */
}
}
#endif /* DCT_IFAST_SUPPORTED */
|
1137519-player
|
jpeg-7/jidctfst.c
|
C
|
lgpl
| 13,191
|
/*
* jcparam.c
*
* Copyright (C) 1991-1998, Thomas G. Lane.
* Modified 2003-2008 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains optional default-setting code for the JPEG compressor.
* Applications do not have to use this file, but those that don't use it
* must know a lot more about the innards of the JPEG code.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/*
* Quantization table setup routines
*/
GLOBAL(void)
jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
const unsigned int *basic_table,
int scale_factor, boolean force_baseline)
/* Define a quantization table equal to the basic_table times
* a scale factor (given as a percentage).
* If force_baseline is TRUE, the computed quantization table entries
* are limited to 1..255 for JPEG baseline compatibility.
*/
{
JQUANT_TBL ** qtblptr;
int i;
long temp;
/* Safety check to ensure start_compress not called yet. */
if (cinfo->global_state != CSTATE_START)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
if (*qtblptr == NULL)
*qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
for (i = 0; i < DCTSIZE2; i++) {
temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
/* limit the values to the valid range */
if (temp <= 0L) temp = 1L;
if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
if (force_baseline && temp > 255L)
temp = 255L; /* limit to baseline range if requested */
(*qtblptr)->quantval[i] = (UINT16) temp;
}
/* Initialize sent_table FALSE so table will be written to JPEG file. */
(*qtblptr)->sent_table = FALSE;
}
/* These are the sample quantization tables given in JPEG spec section K.1.
* The spec says that the values given produce "good" quality, and
* when divided by 2, "very good" quality.
*/
static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77,
24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 99
};
static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
};
GLOBAL(void)
jpeg_default_qtables (j_compress_ptr cinfo, boolean force_baseline)
/* Set or change the 'quality' (quantization) setting, using default tables
* and straight percentage-scaling quality scales.
* This entry point allows different scalings for luminance and chrominance.
*/
{
/* Set up two quantization tables using the specified scaling */
jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
cinfo->q_scale_factor[0], force_baseline);
jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
cinfo->q_scale_factor[1], force_baseline);
}
GLOBAL(void)
jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
boolean force_baseline)
/* Set or change the 'quality' (quantization) setting, using default tables
* and a straight percentage-scaling quality scale. In most cases it's better
* to use jpeg_set_quality (below); this entry point is provided for
* applications that insist on a linear percentage scaling.
*/
{
/* Set up two quantization tables using the specified scaling */
jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
scale_factor, force_baseline);
jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
scale_factor, force_baseline);
}
GLOBAL(int)
jpeg_quality_scaling (int quality)
/* Convert a user-specified quality rating to a percentage scaling factor
* for an underlying quantization table, using our recommended scaling curve.
* The input 'quality' factor should be 0 (terrible) to 100 (very good).
*/
{
/* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
if (quality <= 0) quality = 1;
if (quality > 100) quality = 100;
/* The basic table is used as-is (scaling 100) for a quality of 50.
* Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
* note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
* to make all the table entries 1 (hence, minimum quantization loss).
* Qualities 1..50 are converted to scaling percentage 5000/Q.
*/
if (quality < 50)
quality = 5000 / quality;
else
quality = 200 - quality*2;
return quality;
}
GLOBAL(void)
jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
/* Set or change the 'quality' (quantization) setting, using default tables.
* This is the standard quality-adjusting entry point for typical user
* interfaces; only those who want detailed control over quantization tables
* would use the preceding three routines directly.
*/
{
/* Convert user 0-100 rating to percentage scaling */
quality = jpeg_quality_scaling(quality);
/* Set up standard quality tables */
jpeg_set_linear_quality(cinfo, quality, force_baseline);
}
/*
* Huffman table setup routines
*/
LOCAL(void)
add_huff_table (j_compress_ptr cinfo,
JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
/* Define a Huffman table */
{
int nsymbols, len;
if (*htblptr == NULL)
*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
/* Copy the number-of-symbols-of-each-code-length counts */
MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
/* Validate the counts. We do this here mainly so we can copy the right
* number of symbols from the val[] array, without risking marching off
* the end of memory. jchuff.c will do a more thorough test later.
*/
nsymbols = 0;
for (len = 1; len <= 16; len++)
nsymbols += bits[len];
if (nsymbols < 1 || nsymbols > 256)
ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
/* Initialize sent_table FALSE so table will be written to JPEG file. */
(*htblptr)->sent_table = FALSE;
}
LOCAL(void)
std_huff_tables (j_compress_ptr cinfo)
/* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
/* IMPORTANT: these are only valid for 8-bit data precision! */
{
static const UINT8 bits_dc_luminance[17] =
{ /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
static const UINT8 val_dc_luminance[] =
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
static const UINT8 bits_dc_chrominance[17] =
{ /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
static const UINT8 val_dc_chrominance[] =
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
static const UINT8 bits_ac_luminance[17] =
{ /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
static const UINT8 val_ac_luminance[] =
{ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa };
static const UINT8 bits_ac_chrominance[17] =
{ /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
static const UINT8 val_ac_chrominance[] =
{ 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa };
add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
bits_dc_luminance, val_dc_luminance);
add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
bits_ac_luminance, val_ac_luminance);
add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
bits_dc_chrominance, val_dc_chrominance);
add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
bits_ac_chrominance, val_ac_chrominance);
}
/*
* Default parameter setup for compression.
*
* Applications that don't choose to use this routine must do their
* own setup of all these parameters. Alternately, you can call this
* to establish defaults and then alter parameters selectively. This
* is the recommended approach since, if we add any new parameters,
* your code will still work (they'll be set to reasonable defaults).
*/
GLOBAL(void)
jpeg_set_defaults (j_compress_ptr cinfo)
{
int i;
/* Safety check to ensure start_compress not called yet. */
if (cinfo->global_state != CSTATE_START)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
/* Allocate comp_info array large enough for maximum component count.
* Array is made permanent in case application wants to compress
* multiple images at same param settings.
*/
if (cinfo->comp_info == NULL)
cinfo->comp_info = (jpeg_component_info *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
MAX_COMPONENTS * SIZEOF(jpeg_component_info));
/* Initialize everything not dependent on the color space */
cinfo->scale_num = 1; /* 1:1 scaling */
cinfo->scale_denom = 1;
cinfo->data_precision = BITS_IN_JSAMPLE;
/* Set up two quantization tables using default quality of 75 */
jpeg_set_quality(cinfo, 75, TRUE);
/* Set up two Huffman tables */
std_huff_tables(cinfo);
/* Initialize default arithmetic coding conditioning */
for (i = 0; i < NUM_ARITH_TBLS; i++) {
cinfo->arith_dc_L[i] = 0;
cinfo->arith_dc_U[i] = 1;
cinfo->arith_ac_K[i] = 5;
}
/* Default is no multiple-scan output */
cinfo->scan_info = NULL;
cinfo->num_scans = 0;
/* Expect normal source image, not raw downsampled data */
cinfo->raw_data_in = FALSE;
/* Use Huffman coding, not arithmetic coding, by default */
cinfo->arith_code = FALSE;
/* By default, don't do extra passes to optimize entropy coding */
cinfo->optimize_coding = FALSE;
/* The standard Huffman tables are only valid for 8-bit data precision.
* If the precision is higher, force optimization on so that usable
* tables will be computed. This test can be removed if default tables
* are supplied that are valid for the desired precision.
*/
if (cinfo->data_precision > 8)
cinfo->optimize_coding = TRUE;
/* By default, use the simpler non-cosited sampling alignment */
cinfo->CCIR601_sampling = FALSE;
/* By default, apply fancy downsampling */
cinfo->do_fancy_downsampling = TRUE;
/* No input smoothing */
cinfo->smoothing_factor = 0;
/* DCT algorithm preference */
cinfo->dct_method = JDCT_DEFAULT;
/* No restart markers */
cinfo->restart_interval = 0;
cinfo->restart_in_rows = 0;
/* Fill in default JFIF marker parameters. Note that whether the marker
* will actually be written is determined by jpeg_set_colorspace.
*
* By default, the library emits JFIF version code 1.01.
* An application that wants to emit JFIF 1.02 extension markers should set
* JFIF_minor_version to 2. We could probably get away with just defaulting
* to 1.02, but there may still be some decoders in use that will complain
* about that; saying 1.01 should minimize compatibility problems.
*/
cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
cinfo->JFIF_minor_version = 1;
cinfo->density_unit = 0; /* Pixel size is unknown by default */
cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
cinfo->Y_density = 1;
/* Choose JPEG colorspace based on input space, set defaults accordingly */
jpeg_default_colorspace(cinfo);
}
/*
* Select an appropriate JPEG colorspace for in_color_space.
*/
GLOBAL(void)
jpeg_default_colorspace (j_compress_ptr cinfo)
{
switch (cinfo->in_color_space) {
case JCS_GRAYSCALE:
jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
break;
case JCS_RGB:
jpeg_set_colorspace(cinfo, JCS_YCbCr);
break;
case JCS_YCbCr:
jpeg_set_colorspace(cinfo, JCS_YCbCr);
break;
case JCS_CMYK:
jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
break;
case JCS_YCCK:
jpeg_set_colorspace(cinfo, JCS_YCCK);
break;
case JCS_UNKNOWN:
jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
break;
default:
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
}
}
/*
* Set the JPEG colorspace, and choose colorspace-dependent default values.
*/
GLOBAL(void)
jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
{
jpeg_component_info * compptr;
int ci;
#define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
(compptr = &cinfo->comp_info[index], \
compptr->component_id = (id), \
compptr->h_samp_factor = (hsamp), \
compptr->v_samp_factor = (vsamp), \
compptr->quant_tbl_no = (quant), \
compptr->dc_tbl_no = (dctbl), \
compptr->ac_tbl_no = (actbl) )
/* Safety check to ensure start_compress not called yet. */
if (cinfo->global_state != CSTATE_START)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
/* For all colorspaces, we use Q and Huff tables 0 for luminance components,
* tables 1 for chrominance components.
*/
cinfo->jpeg_color_space = colorspace;
cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
switch (colorspace) {
case JCS_GRAYSCALE:
cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
cinfo->num_components = 1;
/* JFIF specifies component ID 1 */
SET_COMP(0, 1, 1,1, 0, 0,0);
break;
case JCS_RGB:
cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
cinfo->num_components = 3;
SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
break;
case JCS_YCbCr:
cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
cinfo->num_components = 3;
/* JFIF specifies component IDs 1,2,3 */
/* We default to 2x2 subsamples of chrominance */
SET_COMP(0, 1, 2,2, 0, 0,0);
SET_COMP(1, 2, 1,1, 1, 1,1);
SET_COMP(2, 3, 1,1, 1, 1,1);
break;
case JCS_CMYK:
cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
cinfo->num_components = 4;
SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
break;
case JCS_YCCK:
cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
cinfo->num_components = 4;
SET_COMP(0, 1, 2,2, 0, 0,0);
SET_COMP(1, 2, 1,1, 1, 1,1);
SET_COMP(2, 3, 1,1, 1, 1,1);
SET_COMP(3, 4, 2,2, 0, 0,0);
break;
case JCS_UNKNOWN:
cinfo->num_components = cinfo->input_components;
if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
MAX_COMPONENTS);
for (ci = 0; ci < cinfo->num_components; ci++) {
SET_COMP(ci, ci, 1,1, 0, 0,0);
}
break;
default:
ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
}
}
#ifdef C_PROGRESSIVE_SUPPORTED
LOCAL(jpeg_scan_info *)
fill_a_scan (jpeg_scan_info * scanptr, int ci,
int Ss, int Se, int Ah, int Al)
/* Support routine: generate one scan for specified component */
{
scanptr->comps_in_scan = 1;
scanptr->component_index[0] = ci;
scanptr->Ss = Ss;
scanptr->Se = Se;
scanptr->Ah = Ah;
scanptr->Al = Al;
scanptr++;
return scanptr;
}
LOCAL(jpeg_scan_info *)
fill_scans (jpeg_scan_info * scanptr, int ncomps,
int Ss, int Se, int Ah, int Al)
/* Support routine: generate one scan for each component */
{
int ci;
for (ci = 0; ci < ncomps; ci++) {
scanptr->comps_in_scan = 1;
scanptr->component_index[0] = ci;
scanptr->Ss = Ss;
scanptr->Se = Se;
scanptr->Ah = Ah;
scanptr->Al = Al;
scanptr++;
}
return scanptr;
}
LOCAL(jpeg_scan_info *)
fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
/* Support routine: generate interleaved DC scan if possible, else N scans */
{
int ci;
if (ncomps <= MAX_COMPS_IN_SCAN) {
/* Single interleaved DC scan */
scanptr->comps_in_scan = ncomps;
for (ci = 0; ci < ncomps; ci++)
scanptr->component_index[ci] = ci;
scanptr->Ss = scanptr->Se = 0;
scanptr->Ah = Ah;
scanptr->Al = Al;
scanptr++;
} else {
/* Noninterleaved DC scan for each component */
scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
}
return scanptr;
}
/*
* Create a recommended progressive-JPEG script.
* cinfo->num_components and cinfo->jpeg_color_space must be correct.
*/
GLOBAL(void)
jpeg_simple_progression (j_compress_ptr cinfo)
{
int ncomps = cinfo->num_components;
int nscans;
jpeg_scan_info * scanptr;
/* Safety check to ensure start_compress not called yet. */
if (cinfo->global_state != CSTATE_START)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
/* Figure space needed for script. Calculation must match code below! */
if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
/* Custom script for YCbCr color images. */
nscans = 10;
} else {
/* All-purpose script for other color spaces. */
if (ncomps > MAX_COMPS_IN_SCAN)
nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
else
nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
}
/* Allocate space for script.
* We need to put it in the permanent pool in case the application performs
* multiple compressions without changing the settings. To avoid a memory
* leak if jpeg_simple_progression is called repeatedly for the same JPEG
* object, we try to re-use previously allocated space, and we allocate
* enough space to handle YCbCr even if initially asked for grayscale.
*/
if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
cinfo->script_space_size = MAX(nscans, 10);
cinfo->script_space = (jpeg_scan_info *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
cinfo->script_space_size * SIZEOF(jpeg_scan_info));
}
scanptr = cinfo->script_space;
cinfo->scan_info = scanptr;
cinfo->num_scans = nscans;
if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
/* Custom script for YCbCr color images. */
/* Initial DC scan */
scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
/* Initial AC scan: get some luma data out in a hurry */
scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
/* Chroma data is too small to be worth expending many scans on */
scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
/* Complete spectral selection for luma AC */
scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
/* Refine next bit of luma AC */
scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
/* Finish DC successive approximation */
scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
/* Finish AC successive approximation */
scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
/* Luma bottom bit comes last since it's usually largest scan */
scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
} else {
/* All-purpose script for other color spaces. */
/* Successive approximation first pass */
scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
/* Successive approximation second pass */
scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
/* Successive approximation final pass */
scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
}
}
#endif /* C_PROGRESSIVE_SUPPORTED */
|
1137519-player
|
jpeg-7/jcparam.c
|
C
|
lgpl
| 22,009
|
.TH RDJPGCOM 1 "02 April 2009"
.SH NAME
rdjpgcom \- display text comments from a JPEG file
.SH SYNOPSIS
.B rdjpgcom
[
.B \-raw
]
[
.B \-verbose
]
[
.I filename
]
.LP
.SH DESCRIPTION
.LP
.B rdjpgcom
reads the named JPEG/JFIF file, or the standard input if no file is named,
and prints any text comments found in the file on the standard output.
.PP
The JPEG standard allows "comment" (COM) blocks to occur within a JPEG file.
Although the standard doesn't actually define what COM blocks are for, they
are widely used to hold user-supplied text strings. This lets you add
annotations, titles, index terms, etc to your JPEG files, and later retrieve
them as text. COM blocks do not interfere with the image stored in the JPEG
file. The maximum size of a COM block is 64K, but you can have as many of
them as you like in one JPEG file.
.SH OPTIONS
.TP
.B \-raw
Normally
.B rdjpgcom
escapes non-printable characters in comments, for security reasons.
This option avoids that.
.PP
.B \-verbose
Causes
.B rdjpgcom
to also display the JPEG image dimensions.
.PP
Switch names may be abbreviated, and are not case sensitive.
.SH HINTS
.B rdjpgcom
does not depend on the IJG JPEG library. Its source code is intended as an
illustration of the minimum amount of code required to parse a JPEG file
header correctly.
.PP
In
.B \-verbose
mode,
.B rdjpgcom
will also attempt to print the contents of any "APP12" markers as text.
Some digital cameras produce APP12 markers containing useful textual
information. If you like, you can modify the source code to print
other APPn marker types as well.
.SH SEE ALSO
.BR cjpeg (1),
.BR djpeg (1),
.BR jpegtran (1),
.BR wrjpgcom (1)
.SH AUTHOR
Independent JPEG Group
|
1137519-player
|
jpeg-7/rdjpgcom.1
|
Roff Manpage
|
lgpl
| 1,699
|
/*
* jdmerge.c
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains code for merged upsampling/color conversion.
*
* This file combines functions from jdsample.c and jdcolor.c;
* read those files first to understand what's going on.
*
* When the chroma components are to be upsampled by simple replication
* (ie, box filtering), we can save some work in color conversion by
* calculating all the output pixels corresponding to a pair of chroma
* samples at one time. In the conversion equations
* R = Y + K1 * Cr
* G = Y + K2 * Cb + K3 * Cr
* B = Y + K4 * Cb
* only the Y term varies among the group of pixels corresponding to a pair
* of chroma samples, so the rest of the terms can be calculated just once.
* At typical sampling ratios, this eliminates half or three-quarters of the
* multiplications needed for color conversion.
*
* This file currently provides implementations for the following cases:
* YCbCr => RGB color conversion only.
* Sampling ratios of 2h1v or 2h2v.
* No scaling needed at upsample time.
* Corner-aligned (non-CCIR601) sampling alignment.
* Other special cases could be added, but in most applications these are
* the only common cases. (For uncommon cases we fall back on the more
* general code in jdsample.c and jdcolor.c.)
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "lcd.h"
#ifdef UPSAMPLE_MERGING_SUPPORTED
/* Private subobject */
typedef struct {
struct jpeg_upsampler pub; /* public fields */
/* Pointer to routine to do actual upsampling/conversion of one row group */
JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
JSAMPARRAY output_buf));
/* Private state for YCC->RGB conversion */
int * Cr_r_tab; /* => table for Cr to R conversion */
int * Cb_b_tab; /* => table for Cb to B conversion */
INT32 * Cr_g_tab; /* => table for Cr to G conversion */
INT32 * Cb_g_tab; /* => table for Cb to G conversion */
/* For 2:1 vertical sampling, we produce two output rows at a time.
* We need a "spare" row buffer to hold the second output row if the
* application provides just a one-row buffer; we also use the spare
* to discard the dummy last row if the image height is odd.
*/
JSAMPROW spare_row;
boolean spare_full; /* T if spare buffer is occupied */
JDIMENSION out_row_width; /* samples per output row */
JDIMENSION rows_to_go; /* counts rows remaining in image */
} my_upsampler;
typedef my_upsampler * my_upsample_ptr;
#define SCALEBITS 16 /* speediest right-shift on some machines */
#define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
#define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
/*
* Initialize tables for YCC->RGB colorspace conversion.
* This is taken directly from jdcolor.c; see that file for more info.
*/
LOCAL(void)
build_ycc_rgb_table (j_decompress_ptr cinfo)
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
int i;
INT32 x;
SHIFT_TEMPS
upsample->Cr_r_tab = (int *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
(MAXJSAMPLE+1) * SIZEOF(int));
upsample->Cb_b_tab = (int *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
(MAXJSAMPLE+1) * SIZEOF(int));
upsample->Cr_g_tab = (INT32 *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
(MAXJSAMPLE+1) * SIZEOF(INT32));
upsample->Cb_g_tab = (INT32 *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
(MAXJSAMPLE+1) * SIZEOF(INT32));
for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
/* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
/* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
/* Cr=>R value is nearest int to 1.40200 * x */
upsample->Cr_r_tab[i] = (int)
RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
/* Cb=>B value is nearest int to 1.77200 * x */
upsample->Cb_b_tab[i] = (int)
RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
/* Cr=>G value is scaled-up -0.71414 * x */
upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
/* Cb=>G value is scaled-up -0.34414 * x */
/* We also add in ONE_HALF so that need not do it in inner loop */
upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
}
}
void
build_ycc_rgb_table2 (JSAMPLE *ycc_rgb_table, j_decompress_ptr cinfo)
{
// my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
int i;
INT32 x;
SHIFT_TEMPS
cinfo->Cr_r_tab = (int *)ycc_rgb_table;
// (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
// (MAXJSAMPLE+1) * SIZEOF(int));
ycc_rgb_table += (MAXJSAMPLE+1) * SIZEOF(int);
cinfo->Cb_b_tab = (int *)ycc_rgb_table;
// (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
// (MAXJSAMPLE+1) * SIZEOF(int));
ycc_rgb_table += (MAXJSAMPLE+1) * SIZEOF(int);
cinfo->Cr_g_tab = (INT32 *)ycc_rgb_table;
// (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
// (MAXJSAMPLE+1) * SIZEOF(INT32));
ycc_rgb_table += (MAXJSAMPLE+1) * SIZEOF(INT32);
cinfo->Cb_g_tab = (INT32 *)ycc_rgb_table;
// (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
// (MAXJSAMPLE+1) * SIZEOF(INT32));
for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
/* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
/* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
/* Cr=>R value is nearest int to 1.40200 * x */
cinfo->Cr_r_tab[i] = (int)
RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
/* Cb=>B value is nearest int to 1.77200 * x */
cinfo->Cb_b_tab[i] = (int)
RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
/* Cr=>G value is scaled-up -0.71414 * x */
cinfo->Cr_g_tab[i] = (- FIX(0.71414)) * x;
/* Cb=>G value is scaled-up -0.34414 * x */
/* We also add in ONE_HALF so that need not do it in inner loop */
cinfo->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
}
}
/*
* Initialize for an upsampling pass.
*/
METHODDEF(void)
start_pass_merged_upsample (j_decompress_ptr cinfo)
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
/* Mark the spare buffer empty */
upsample->spare_full = FALSE;
/* Initialize total-height counter for detecting bottom of image */
upsample->rows_to_go = cinfo->output_height;
}
/*
* Control routine to do upsampling (and color conversion).
*
* The control routine just handles the row buffering considerations.
*/
METHODDEF(void)
merged_2v_upsample (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
JDIMENSION in_row_groups_avail,
JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
JDIMENSION out_rows_avail)
/* 2:1 vertical sampling case: may need a spare row. */
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
JSAMPROW work_ptrs[2];
JDIMENSION num_rows; /* number of rows returned to caller */
if (upsample->spare_full) {
/* If we have a spare row saved from a previous cycle, just return it. */
// jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
// 1, upsample->out_row_width);
num_rows = 1;
upsample->spare_full = FALSE;
} else {
/* Figure number of rows to return to caller. */
num_rows = 2;
/* Not more than the distance to the end of the image. */
if (num_rows > upsample->rows_to_go)
num_rows = upsample->rows_to_go;
/* And not more than what the client can accept: */
out_rows_avail -= *out_row_ctr;
if (num_rows > out_rows_avail)
num_rows = out_rows_avail;
/* Create output pointer array for upsampler. */
work_ptrs[0] = output_buf[*out_row_ctr];
if (num_rows > 1) {
work_ptrs[1] = output_buf[*out_row_ctr + 1];
} else {
work_ptrs[1] = upsample->spare_row;
upsample->spare_full = TRUE;
}
/* Now do the upsampling. */
(*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
}
/* Adjust counts */
*out_row_ctr += num_rows;
upsample->rows_to_go -= num_rows;
/* When the buffer is emptied, declare this input row group consumed */
if (! upsample->spare_full)
(*in_row_group_ctr)++;
}
METHODDEF(void)
merged_1v_upsample (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
JDIMENSION in_row_groups_avail,
JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
JDIMENSION out_rows_avail)
/* 1:1 vertical sampling case: much easier, never need a spare row. */
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
/* Just do the upsampling. */
(*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
output_buf + *out_row_ctr);
/* Adjust counts */
(*out_row_ctr)++;
(*in_row_group_ctr)++;
}
/*
* These are the routines invoked by the control routines to do
* the actual upsampling/conversion. One row group is processed per call.
*
* Note: since we may be writing directly into application-supplied buffers,
* we have to be honest about the output width; we can't assume the buffer
* has been rounded up to an even width.
*/
/*
* Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
*/
METHODDEF(void)
h2v1_merged_upsample (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
JSAMPARRAY output_buf)
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
JDIMENSION col;
int y, cred, cgreen, cblue;
int cb, cr;
// JSAMPROW outptr;
JSAMPROW inptr0, inptr1, inptr2;
/* copy these pointers into registers if possible */
JSAMPLE * range_limit = cinfo->sample_range_limit;
int * Crrtab = upsample->Cr_r_tab;
int * Cbbtab = upsample->Cb_b_tab;
INT32 * Crgtab = upsample->Cr_g_tab;
INT32 * Cbgtab = upsample->Cb_g_tab;
SHIFT_TEMPS
inptr0 = input_buf[0][in_row_group_ctr];
inptr1 = input_buf[1][in_row_group_ctr];
inptr2 = input_buf[2][in_row_group_ctr];
// outptr = output_buf[0];
/* Loop for each pair of output pixels */
for (col = cinfo->output_width >> 1; col > 0; col--) {
/* Do the chroma part of the calculation */
cb = GETJSAMPLE(*inptr1++);
cr = GETJSAMPLE(*inptr2++);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
/* Fetch 2 Y values and emit 2 pixels */
y = GETJSAMPLE(*inptr0++);
// outptr[RGB_RED] = range_limit[y + cred];
// outptr[RGB_GREEN] = range_limit[y + cgreen];
// outptr[RGB_BLUE] = range_limit[y + cblue];
// outptr += RGB_PIXELSIZE;
LCD->RAM = range_limit[y + cblue] >> 3 | (range_limit[y + cgreen] >> 2) << 5 | (range_limit[y + cred] >> 3) << 11;
y = GETJSAMPLE(*inptr0++);
// outptr[RGB_RED] = range_limit[y + cred];
// outptr[RGB_GREEN] = range_limit[y + cgreen];
// outptr[RGB_BLUE] = range_limit[y + cblue];
// outptr += RGB_PIXELSIZE;
LCD->RAM = range_limit[y + cblue] >> 3 | (range_limit[y + cgreen] >> 2) << 5 | (range_limit[y + cred] >> 3) << 11;
}
/* If image width is odd, do the last output column separately */
if (cinfo->output_width & 1) {
cb = GETJSAMPLE(*inptr1);
cr = GETJSAMPLE(*inptr2);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
y = GETJSAMPLE(*inptr0);
// outptr[RGB_RED] = range_limit[y + cred];
// outptr[RGB_GREEN] = range_limit[y + cgreen];
// outptr[RGB_BLUE] = range_limit[y + cblue];
LCD->RAM = range_limit[y + cblue] >> 3 | (range_limit[y + cgreen] >> 2) << 5 | (range_limit[y + cred] >> 3) << 11;
}
}
/*
* Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
*/
METHODDEF(void)
h2v2_merged_upsample (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
JSAMPARRAY output_buf)
{
int y, cred, cgreen, cblue;
int col;
JSAMPLE * range_limit = cinfo->sample_range_limit;
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
int cb, cr;
// JSAMPROW outptr0, outptr1;
JSAMPROW inptr00, inptr01, inptr1, inptr2;
// JDIMENSION col;
/* copy these pointers into registers if possible */
int * Crrtab = upsample->Cr_r_tab;
int * Cbbtab = upsample->Cb_b_tab;
INT32 * Crgtab = upsample->Cr_g_tab;
INT32 * Cbgtab = upsample->Cb_g_tab;
SHIFT_TEMPS
inptr00 = input_buf[0][in_row_group_ctr*2];
// inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
inptr1 = input_buf[1][in_row_group_ctr];
inptr2 = input_buf[2][in_row_group_ctr];
/* Loop for each group of output pixels */
for (col = cinfo->output_width >> 1; col > 0; col--) {
/* Do the chroma part of the calculation */
cb = GETJSAMPLE(*inptr1++);
cr = GETJSAMPLE(*inptr2++);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
/* Fetch 4 Y values and emit 4 pixels */
y = GETJSAMPLE(*inptr00++);
LCD->RAM = range_limit[y + cblue] >> 3 | (range_limit[y + cgreen] >> 2) << 5 | (range_limit[y + cred] >> 3) << 11;
y = GETJSAMPLE(*inptr00++);
LCD->RAM = range_limit[y + cblue] >> 3 | (range_limit[y + cgreen] >> 2) << 5 | (range_limit[y + cred] >> 3) << 11;
}
// inptr00 = input_buf[0][in_row_group_ctr*2];
inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
inptr1 = input_buf[1][in_row_group_ctr];
inptr2 = input_buf[2][in_row_group_ctr];
/* Loop for each group of output pixels */
for (col = cinfo->output_width >> 1; col > 0; col--) {
/* Do the chroma part of the calculation */
cb = GETJSAMPLE(*inptr1++);
cr = GETJSAMPLE(*inptr2++);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
/* Fetch 4 Y values and emit 4 pixels */
y = GETJSAMPLE(*inptr01++);
LCD->RAM = range_limit[y + cblue] >> 3 | (range_limit[y + cgreen] >> 2) << 5 | (range_limit[y + cred] >> 3) << 11;
y = GETJSAMPLE(*inptr01++);
LCD->RAM = range_limit[y + cblue] >> 3 | (range_limit[y + cgreen] >> 2) << 5 | (range_limit[y + cred] >> 3) << 11;
}
/* If image width is odd, do the last output column separately */
if (cinfo->output_width & 1) {
cb = GETJSAMPLE(*inptr1);
cr = GETJSAMPLE(*inptr2);
cred = Crrtab[cr];
cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
cblue = Cbbtab[cb];
y = GETJSAMPLE(*inptr00);
// outptr0[RGB_RED] = range_limit[y + cred];
// outptr0[RGB_GREEN] = range_limit[y + cgreen];
// outptr0[RGB_BLUE] = range_limit[y + cblue];
LCD->RAM = range_limit[y + cblue] >> 3 | (range_limit[y + cgreen] >> 2) << 5 | (range_limit[y + cred] >> 3) << 11;
y = GETJSAMPLE(*inptr01);
// outptr1[RGB_RED] = range_limit[y + cred];
// outptr1[RGB_GREEN] = range_limit[y + cgreen];
// outptr1[RGB_BLUE] = range_limit[y + cblue];
LCD->RAM = range_limit[y + cblue] >> 3 | (range_limit[y + cgreen] >> 2) << 5 | (range_limit[y + cred] >> 3) << 11;
}
}
/*
* Module initialization routine for merged upsampling/color conversion.
*
* NB: this is called under the conditions determined by use_merged_upsample()
* in jdmaster.c. That routine MUST correspond to the actual capabilities
* of this module; no safety checks are made here.
*/
GLOBAL(void)
jinit_merged_upsampler (j_decompress_ptr cinfo)
{
my_upsample_ptr upsample;
upsample = (my_upsample_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(my_upsampler));
cinfo->upsample = (struct jpeg_upsampler *) upsample;
upsample->pub.start_pass = start_pass_merged_upsample;
upsample->pub.need_context_rows = FALSE;
upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
if (cinfo->max_v_samp_factor == 2) {
upsample->pub.upsample = merged_2v_upsample;
upsample->upmethod = h2v2_merged_upsample;
/* Allocate a spare row buffer */
// upsample->spare_row = (JSAMPROW)
// (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
// (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
} else {
upsample->pub.upsample = merged_1v_upsample;
upsample->upmethod = h2v1_merged_upsample;
/* No spare row needed */
upsample->spare_row = NULL;
}
if(!cinfo->useMergedUpsampling)
build_ycc_rgb_table(cinfo);
else {
upsample->Cr_r_tab = cinfo->Cr_r_tab;
upsample->Cb_b_tab = cinfo->Cb_b_tab;
upsample->Cr_g_tab = cinfo->Cr_g_tab;
upsample->Cb_g_tab = cinfo->Cb_g_tab;
}
}
#endif /* UPSAMPLE_MERGING_SUPPORTED */
|
1137519-player
|
jpeg-7/jdmerge.c
|
C
|
lgpl
| 16,718
|
/*
* jdhuff.c
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* Modified 2006-2009 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains Huffman entropy decoding routines.
* Both sequential and progressive modes are supported in this single module.
*
* Much of the complexity here has to do with supporting input suspension.
* If the data source module demands suspension, we want to be able to back
* up to the start of the current MCU. To do this, we copy state variables
* into local working storage, and update them back to the permanent
* storage only upon successful completion of an MCU.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/* Derived data constructed for each Huffman table */
#define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
typedef struct {
/* Basic tables: (element [0] of each array is unused) */
INT32 maxcode[18]; /* largest code of length k (-1 if none) */
/* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
INT32 valoffset[17]; /* huffval[] offset for codes of length k */
/* valoffset[k] = huffval[] index of 1st symbol of code length k, less
* the smallest code of length k; so given a code of length k, the
* corresponding symbol is huffval[code + valoffset[k]]
*/
/* Link to public Huffman table (needed only in jpeg_huff_decode) */
JHUFF_TBL *pub;
/* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
* the input data stream. If the next Huffman code is no more
* than HUFF_LOOKAHEAD bits long, we can obtain its length and
* the corresponding symbol directly from these tables.
*/
int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
} d_derived_tbl;
/*
* Fetching the next N bits from the input stream is a time-critical operation
* for the Huffman decoders. We implement it with a combination of inline
* macros and out-of-line subroutines. Note that N (the number of bits
* demanded at one time) never exceeds 15 for JPEG use.
*
* We read source bytes into get_buffer and dole out bits as needed.
* If get_buffer already contains enough bits, they are fetched in-line
* by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
* bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
* as full as possible (not just to the number of bits needed; this
* prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
* Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
* On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
* at least the requested number of bits --- dummy zeroes are inserted if
* necessary.
*/
typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
#define BIT_BUF_SIZE 32 /* size of buffer in bits */
/* If long is > 32 bits on your machine, and shifting/masking longs is
* reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
* appropriately should be a win. Unfortunately we can't define the size
* with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
* because not all machines measure sizeof in 8-bit bytes.
*/
typedef struct { /* Bitreading state saved across MCUs */
bit_buf_type get_buffer; /* current bit-extraction buffer */
int bits_left; /* # of unused bits in it */
} bitread_perm_state;
typedef struct { /* Bitreading working state within an MCU */
/* Current data source location */
/* We need a copy, rather than munging the original, in case of suspension */
const JOCTET * next_input_byte; /* => next byte to read from source */
size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
/* Bit input buffer --- note these values are kept in register variables,
* not in this struct, inside the inner loops.
*/
bit_buf_type get_buffer; /* current bit-extraction buffer */
int bits_left; /* # of unused bits in it */
/* Pointer needed by jpeg_fill_bit_buffer. */
j_decompress_ptr cinfo; /* back link to decompress master record */
} bitread_working_state;
/* Macros to declare and load/save bitread local variables. */
#define BITREAD_STATE_VARS \
register bit_buf_type get_buffer; \
register int bits_left; \
bitread_working_state br_state
#define BITREAD_LOAD_STATE(cinfop,permstate) \
br_state.cinfo = cinfop; \
br_state.next_input_byte = cinfop->src->next_input_byte; \
br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
get_buffer = permstate.get_buffer; \
bits_left = permstate.bits_left;
#define BITREAD_SAVE_STATE(cinfop,permstate) \
cinfop->src->next_input_byte = br_state.next_input_byte; \
cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
permstate.get_buffer = get_buffer; \
permstate.bits_left = bits_left
/*
* These macros provide the in-line portion of bit fetching.
* Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
* before using GET_BITS, PEEK_BITS, or DROP_BITS.
* The variables get_buffer and bits_left are assumed to be locals,
* but the state struct might not be (jpeg_huff_decode needs this).
* CHECK_BIT_BUFFER(state,n,action);
* Ensure there are N bits in get_buffer; if suspend, take action.
* val = GET_BITS(n);
* Fetch next N bits.
* val = PEEK_BITS(n);
* Fetch next N bits without removing them from the buffer.
* DROP_BITS(n);
* Discard next N bits.
* The value N should be a simple variable, not an expression, because it
* is evaluated multiple times.
*/
#define CHECK_BIT_BUFFER(state,nbits,action) \
{ if (bits_left < (nbits)) { \
if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
{ action; } \
get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
#define GET_BITS(nbits) \
(((int) (get_buffer >> (bits_left -= (nbits)))) & BIT_MASK(nbits))
#define PEEK_BITS(nbits) \
(((int) (get_buffer >> (bits_left - (nbits)))) & BIT_MASK(nbits))
#define DROP_BITS(nbits) \
(bits_left -= (nbits))
/*
* Code for extracting next Huffman-coded symbol from input bit stream.
* Again, this is time-critical and we make the main paths be macros.
*
* We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
* without looping. Usually, more than 95% of the Huffman codes will be 8
* or fewer bits long. The few overlength codes are handled with a loop,
* which need not be inline code.
*
* Notes about the HUFF_DECODE macro:
* 1. Near the end of the data segment, we may fail to get enough bits
* for a lookahead. In that case, we do it the hard way.
* 2. If the lookahead table contains no entry, the next code must be
* more than HUFF_LOOKAHEAD bits long.
* 3. jpeg_huff_decode returns -1 if forced to suspend.
*/
#define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
{ register int nb, look; \
if (bits_left < HUFF_LOOKAHEAD) { \
if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
get_buffer = state.get_buffer; bits_left = state.bits_left; \
if (bits_left < HUFF_LOOKAHEAD) { \
nb = 1; goto slowlabel; \
} \
} \
look = PEEK_BITS(HUFF_LOOKAHEAD); \
if ((nb = htbl->look_nbits[look]) != 0) { \
DROP_BITS(nb); \
result = htbl->look_sym[look]; \
} else { \
nb = HUFF_LOOKAHEAD+1; \
slowlabel: \
if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
{ failaction; } \
get_buffer = state.get_buffer; bits_left = state.bits_left; \
} \
}
/*
* Expanded entropy decoder object for Huffman decoding.
*
* The savable_state subrecord contains fields that change within an MCU,
* but must not be updated permanently until we complete the MCU.
*/
typedef struct {
unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
} savable_state;
/* This macro is to work around compilers with missing or broken
* structure assignment. You'll need to fix this code if you have
* such a compiler and you change MAX_COMPS_IN_SCAN.
*/
#ifndef NO_STRUCT_ASSIGN
#define ASSIGN_STATE(dest,src) ((dest) = (src))
#else
#if MAX_COMPS_IN_SCAN == 4
#define ASSIGN_STATE(dest,src) \
((dest).EOBRUN = (src).EOBRUN, \
(dest).last_dc_val[0] = (src).last_dc_val[0], \
(dest).last_dc_val[1] = (src).last_dc_val[1], \
(dest).last_dc_val[2] = (src).last_dc_val[2], \
(dest).last_dc_val[3] = (src).last_dc_val[3])
#endif
#endif
typedef struct {
struct jpeg_entropy_decoder pub; /* public fields */
/* These fields are loaded into local variables at start of each MCU.
* In case of suspension, we exit WITHOUT updating them.
*/
bitread_perm_state bitstate; /* Bit buffer at start of MCU */
savable_state saved; /* Other state at start of MCU */
/* These fields are NOT loaded into local working state. */
unsigned int restarts_to_go; /* MCUs left in this restart interval */
/* Following two fields used only in progressive mode */
/* Pointers to derived tables (these workspaces have image lifespan) */
d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
/* Following fields used only in sequential mode */
/* Pointers to derived tables (these workspaces have image lifespan) */
d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
/* Precalculated info set up by start_pass for use in decode_mcu: */
/* Pointers to derived tables to be used for each block within an MCU */
d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
/* Whether we care about the DC and AC coefficient values for each block */
int coef_limit[D_MAX_BLOCKS_IN_MCU];
} huff_entropy_decoder;
typedef huff_entropy_decoder * huff_entropy_ptr;
//static const int jpeg_zigzag_order[8][8] = {
static int jpeg_zigzag_order[8][8] = {
{ 0, 1, 5, 6, 14, 15, 27, 28 },
{ 2, 4, 7, 13, 16, 26, 29, 42 },
{ 3, 8, 12, 17, 25, 30, 41, 43 },
{ 9, 11, 18, 24, 31, 40, 44, 53 },
{ 10, 19, 23, 32, 39, 45, 52, 54 },
{ 20, 22, 33, 38, 46, 51, 55, 60 },
{ 21, 34, 37, 47, 50, 56, 59, 61 },
{ 35, 36, 48, 49, 57, 58, 62, 63 }
};
/*
* Compute the derived values for a Huffman table.
* This routine also performs some validation checks on the table.
*/
LOCAL(void)
jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
d_derived_tbl ** pdtbl)
{
JHUFF_TBL *htbl;
d_derived_tbl *dtbl;
int p, i, l, si, numsymbols;
int lookbits, ctr;
char huffsize[257];
unsigned int huffcode[257];
unsigned int code;
/* Note that huffsize[] and huffcode[] are filled in code-length order,
* paralleling the order of the symbols themselves in htbl->huffval[].
*/
/* Find the input Huffman table */
if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
htbl =
isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
if (htbl == NULL)
ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
/* Allocate a workspace if we haven't already done so. */
if (*pdtbl == NULL)
*pdtbl = (d_derived_tbl *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(d_derived_tbl));
dtbl = *pdtbl;
dtbl->pub = htbl; /* fill in back link */
/* Figure C.1: make table of Huffman code length for each symbol */
p = 0;
for (l = 1; l <= 16; l++) {
i = (int) htbl->bits[l];
if (i < 0 || p + i > 256) /* protect against table overrun */
ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
while (i--)
huffsize[p++] = (char) l;
}
huffsize[p] = 0;
numsymbols = p;
/* Figure C.2: generate the codes themselves */
/* We also validate that the counts represent a legal Huffman code tree. */
code = 0;
si = huffsize[0];
p = 0;
while (huffsize[p]) {
while (((int) huffsize[p]) == si) {
huffcode[p++] = code;
code++;
}
/* code is now 1 more than the last code used for codelength si; but
* it must still fit in si bits, since no code is allowed to be all ones.
*/
if (((INT32) code) >= (((INT32) 1) << si))
ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
code <<= 1;
si++;
}
/* Figure F.15: generate decoding tables for bit-sequential decoding */
p = 0;
for (l = 1; l <= 16; l++) {
if (htbl->bits[l]) {
/* valoffset[l] = huffval[] index of 1st symbol of code length l,
* minus the minimum code of length l
*/
dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
p += htbl->bits[l];
dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
} else {
dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
}
}
dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
/* Compute lookahead tables to speed up decoding.
* First we set all the table entries to 0, indicating "too long";
* then we iterate through the Huffman codes that are short enough and
* fill in all the entries that correspond to bit sequences starting
* with that code.
*/
MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
p = 0;
for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
/* l = current code's length, p = its index in huffcode[] & huffval[]. */
/* Generate left-justified code followed by all possible bit sequences */
lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
dtbl->look_nbits[lookbits] = l;
dtbl->look_sym[lookbits] = htbl->huffval[p];
lookbits++;
}
}
}
/* Validate symbols as being reasonable.
* For AC tables, we make no check, but accept all byte values 0..255.
* For DC tables, we require the symbols to be in range 0..15.
* (Tighter bounds could be applied depending on the data depth and mode,
* but this is sufficient to ensure safe decoding.)
*/
if (isDC) {
for (i = 0; i < numsymbols; i++) {
int sym = htbl->huffval[i];
if (sym < 0 || sym > 15)
ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
}
}
}
/*
* Out-of-line code for bit fetching.
* Note: current values of get_buffer and bits_left are passed as parameters,
* but are returned in the corresponding fields of the state struct.
*
* On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
* of get_buffer to be used. (On machines with wider words, an even larger
* buffer could be used.) However, on some machines 32-bit shifts are
* quite slow and take time proportional to the number of places shifted.
* (This is true with most PC compilers, for instance.) In this case it may
* be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
* average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
*/
#ifdef SLOW_SHIFT_32
#define MIN_GET_BITS 15 /* minimum allowable value */
#else
#define MIN_GET_BITS (BIT_BUF_SIZE-7)
#endif
LOCAL(boolean)
jpeg_fill_bit_buffer (bitread_working_state * state,
register bit_buf_type get_buffer, register int bits_left,
int nbits)
/* Load up the bit buffer to a depth of at least nbits */
{
/* Copy heavily used state fields into locals (hopefully registers) */
register const JOCTET * next_input_byte = state->next_input_byte;
register size_t bytes_in_buffer = state->bytes_in_buffer;
j_decompress_ptr cinfo = state->cinfo;
/* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
/* (It is assumed that no request will be for more than that many bits.) */
/* We fail to do so only if we hit a marker or are forced to suspend. */
if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
while (bits_left < MIN_GET_BITS) {
register int c;
/* Attempt to read a byte */
if (bytes_in_buffer == 0) {
if (! (*cinfo->src->fill_input_buffer) (cinfo))
return FALSE;
next_input_byte = cinfo->src->next_input_byte;
bytes_in_buffer = cinfo->src->bytes_in_buffer;
}
bytes_in_buffer--;
c = GETJOCTET(*next_input_byte++);
/* If it's 0xFF, check and discard stuffed zero byte */
if (c == 0xFF) {
/* Loop here to discard any padding FF's on terminating marker,
* so that we can save a valid unread_marker value. NOTE: we will
* accept multiple FF's followed by a 0 as meaning a single FF data
* byte. This data pattern is not valid according to the standard.
*/
do {
if (bytes_in_buffer == 0) {
if (! (*cinfo->src->fill_input_buffer) (cinfo))
return FALSE;
next_input_byte = cinfo->src->next_input_byte;
bytes_in_buffer = cinfo->src->bytes_in_buffer;
}
bytes_in_buffer--;
c = GETJOCTET(*next_input_byte++);
} while (c == 0xFF);
if (c == 0) {
/* Found FF/00, which represents an FF data byte */
c = 0xFF;
} else {
/* Oops, it's actually a marker indicating end of compressed data.
* Save the marker code for later use.
* Fine point: it might appear that we should save the marker into
* bitread working state, not straight into permanent state. But
* once we have hit a marker, we cannot need to suspend within the
* current MCU, because we will read no more bytes from the data
* source. So it is OK to update permanent state right away.
*/
cinfo->unread_marker = c;
/* See if we need to insert some fake zero bits. */
goto no_more_bytes;
}
}
/* OK, load c into get_buffer */
get_buffer = (get_buffer << 8) | c;
bits_left += 8;
} /* end while */
} else {
no_more_bytes:
/* We get here if we've read the marker that terminates the compressed
* data segment. There should be enough bits in the buffer register
* to satisfy the request; if so, no problem.
*/
if (nbits > bits_left) {
/* Uh-oh. Report corrupted data to user and stuff zeroes into
* the data stream, so that we can produce some kind of image.
* We use a nonvolatile flag to ensure that only one warning message
* appears per data segment.
*/
if (! cinfo->entropy->insufficient_data) {
WARNMS(cinfo, JWRN_HIT_MARKER);
cinfo->entropy->insufficient_data = TRUE;
}
/* Fill the buffer with zero bits */
get_buffer <<= MIN_GET_BITS - bits_left;
bits_left = MIN_GET_BITS;
}
}
/* Unload the local registers */
state->next_input_byte = next_input_byte;
state->bytes_in_buffer = bytes_in_buffer;
state->get_buffer = get_buffer;
state->bits_left = bits_left;
return TRUE;
}
/*
* Figure F.12: extend sign bit.
* On some machines, a shift and sub will be faster than a table lookup.
*/
#ifdef AVOID_TABLES
#define BIT_MASK(nbits) ((1<<(nbits))-1)
#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) - ((1<<(s))-1) : (x))
#else
#define BIT_MASK(nbits) bmask[nbits]
#define HUFF_EXTEND(x,s) ((x) <= bmask[(s) - 1] ? (x) - bmask[s] : (x))
static const int bmask[16] = /* bmask[n] is mask for n rightmost bits */
{ 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };
#endif /* AVOID_TABLES */
/*
* Out-of-line code for Huffman code decoding.
*/
LOCAL(int)
jpeg_huff_decode (bitread_working_state * state,
register bit_buf_type get_buffer, register int bits_left,
d_derived_tbl * htbl, int min_bits)
{
register int l = min_bits;
register INT32 code;
/* HUFF_DECODE has determined that the code is at least min_bits */
/* bits long, so fetch that many bits in one swoop. */
CHECK_BIT_BUFFER(*state, l, return -1);
code = GET_BITS(l);
/* Collect the rest of the Huffman code one bit at a time. */
/* This is per Figure F.16 in the JPEG spec. */
while (code > htbl->maxcode[l]) {
code <<= 1;
CHECK_BIT_BUFFER(*state, 1, return -1);
code |= GET_BITS(1);
l++;
}
/* Unload the local registers */
state->get_buffer = get_buffer;
state->bits_left = bits_left;
/* With garbage input we may reach the sentinel value l = 17. */
if (l > 16) {
WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
return 0; /* fake a zero as the safest result */
}
return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
}
/*
* Check for a restart marker & resynchronize decoder.
* Returns FALSE if must suspend.
*/
LOCAL(boolean)
process_restart (j_decompress_ptr cinfo)
{
huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
int ci;
/* Throw away any unused bits remaining in bit buffer; */
/* include any full bytes in next_marker's count of discarded bytes */
cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
entropy->bitstate.bits_left = 0;
/* Advance past the RSTn marker */
if (! (*cinfo->marker->read_restart_marker) (cinfo))
return FALSE;
/* Re-initialize DC predictions to 0 */
for (ci = 0; ci < cinfo->comps_in_scan; ci++)
entropy->saved.last_dc_val[ci] = 0;
/* Re-init EOB run count, too */
entropy->saved.EOBRUN = 0;
/* Reset restart counter */
entropy->restarts_to_go = cinfo->restart_interval;
/* Reset out-of-data flag, unless read_restart_marker left us smack up
* against a marker. In that case we will end up treating the next data
* segment as empty, and we can avoid producing bogus output pixels by
* leaving the flag set.
*/
if (cinfo->unread_marker == 0)
entropy->pub.insufficient_data = FALSE;
return TRUE;
}
/*
* Huffman MCU decoding.
* Each of these routines decodes and returns one MCU's worth of
* Huffman-compressed coefficients.
* The coefficients are reordered from zigzag order into natural array order,
* but are not dequantized.
*
* The i'th block of the MCU is stored into the block pointed to by
* MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
* (Wholesale zeroing is usually a little faster than retail...)
*
* We return FALSE if data source requested suspension. In that case no
* changes have been made to permanent state. (Exception: some output
* coefficients may already have been assigned. This is harmless for
* spectral selection, since we'll just re-assign them on the next call.
* Successive approximation AC refinement has to be more careful, however.)
*/
/*
* MCU decoding for DC initial scan (either spectral selection,
* or first pass of successive approximation).
*/
METHODDEF(boolean)
decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
int Al = cinfo->Al;
register int s, r;
int blkn, ci;
JBLOCKROW block;
BITREAD_STATE_VARS;
savable_state state;
d_derived_tbl * tbl;
jpeg_component_info * compptr;
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* If we've run out of data, just leave the MCU set to zeroes.
* This way, we return uniform gray for the remainder of the segment.
*/
if (! entropy->pub.insufficient_data) {
/* Load up working state */
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
ASSIGN_STATE(state, entropy->saved);
/* Outer loop handles each block in the MCU */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
block = MCU_data[blkn];
ci = cinfo->MCU_membership[blkn];
compptr = cinfo->cur_comp_info[ci];
tbl = entropy->derived_tbls[compptr->dc_tbl_no];
/* Decode a single block's worth of coefficients */
/* Section F.2.2.1: decode the DC coefficient difference */
HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
if (s) {
CHECK_BIT_BUFFER(br_state, s, return FALSE);
r = GET_BITS(s);
s = HUFF_EXTEND(r, s);
}
/* Convert DC difference to actual value, update last_dc_val */
s += state.last_dc_val[ci];
state.last_dc_val[ci] = s;
/* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
(*block)[0] = (JCOEF) (s << Al);
}
/* Completed MCU, so update state */
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
ASSIGN_STATE(entropy->saved, state);
}
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
}
/*
* MCU decoding for AC initial scan (either spectral selection,
* or first pass of successive approximation).
*/
METHODDEF(boolean)
decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
int Se = cinfo->Se;
int Al = cinfo->Al;
register int s, k, r;
unsigned int EOBRUN;
JBLOCKROW block;
BITREAD_STATE_VARS;
d_derived_tbl * tbl;
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* If we've run out of data, just leave the MCU set to zeroes.
* This way, we return uniform gray for the remainder of the segment.
*/
if (! entropy->pub.insufficient_data) {
/* Load up working state.
* We can avoid loading/saving bitread state if in an EOB run.
*/
EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
/* There is always only one block per MCU */
if (EOBRUN > 0) /* if it's a band of zeroes... */
EOBRUN--; /* ...process it now (we do nothing) */
else {
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
block = MCU_data[0];
tbl = entropy->ac_derived_tbl;
for (k = cinfo->Ss; k <= Se; k++) {
HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
r = s >> 4;
s &= 15;
if (s) {
k += r;
CHECK_BIT_BUFFER(br_state, s, return FALSE);
r = GET_BITS(s);
s = HUFF_EXTEND(r, s);
/* Scale and output coefficient in natural (dezigzagged) order */
(*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
} else {
if (r == 15) { /* ZRL */
k += 15; /* skip 15 zeroes in band */
} else { /* EOBr, run length is 2^r + appended bits */
EOBRUN = 1 << r;
if (r) { /* EOBr, r > 0 */
CHECK_BIT_BUFFER(br_state, r, return FALSE);
r = GET_BITS(r);
EOBRUN += r;
}
EOBRUN--; /* this band is processed at this moment */
break; /* force end-of-band */
}
}
}
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
}
/* Completed MCU, so update state */
entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
}
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
}
/*
* MCU decoding for DC successive approximation refinement scan.
* Note: we assume such scans can be multi-component, although the spec
* is not very clear on the point.
*/
METHODDEF(boolean)
decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
int blkn;
JBLOCKROW block;
BITREAD_STATE_VARS;
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* Not worth the cycles to check insufficient_data here,
* since we will not change the data anyway if we read zeroes.
*/
/* Load up working state */
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
/* Outer loop handles each block in the MCU */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
block = MCU_data[blkn];
/* Encoded data is simply the next bit of the two's-complement DC value */
CHECK_BIT_BUFFER(br_state, 1, return FALSE);
if (GET_BITS(1))
(*block)[0] |= p1;
/* Note: since we use |=, repeating the assignment later is safe */
}
/* Completed MCU, so update state */
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
}
/*
* MCU decoding for AC successive approximation refinement scan.
*/
METHODDEF(boolean)
decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
int Se = cinfo->Se;
int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
register int s, k, r;
unsigned int EOBRUN;
JBLOCKROW block;
JCOEFPTR thiscoef;
BITREAD_STATE_VARS;
d_derived_tbl * tbl;
int num_newnz;
int newnz_pos[DCTSIZE2];
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* If we've run out of data, don't modify the MCU.
*/
if (! entropy->pub.insufficient_data) {
/* Load up working state */
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
/* There is always only one block per MCU */
block = MCU_data[0];
tbl = entropy->ac_derived_tbl;
/* If we are forced to suspend, we must undo the assignments to any newly
* nonzero coefficients in the block, because otherwise we'd get confused
* next time about which coefficients were already nonzero.
* But we need not undo addition of bits to already-nonzero coefficients;
* instead, we can test the current bit to see if we already did it.
*/
num_newnz = 0;
/* initialize coefficient loop counter to start of band */
k = cinfo->Ss;
if (EOBRUN == 0) {
for (; k <= Se; k++) {
HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
r = s >> 4;
s &= 15;
if (s) {
if (s != 1) /* size of new coef should always be 1 */
WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
CHECK_BIT_BUFFER(br_state, 1, goto undoit);
if (GET_BITS(1))
s = p1; /* newly nonzero coef is positive */
else
s = m1; /* newly nonzero coef is negative */
} else {
if (r != 15) {
EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
if (r) {
CHECK_BIT_BUFFER(br_state, r, goto undoit);
r = GET_BITS(r);
EOBRUN += r;
}
break; /* rest of block is handled by EOB logic */
}
/* note s = 0 for processing ZRL */
}
/* Advance over already-nonzero coefs and r still-zero coefs,
* appending correction bits to the nonzeroes. A correction bit is 1
* if the absolute value of the coefficient must be increased.
*/
do {
thiscoef = *block + jpeg_natural_order[k];
if (*thiscoef != 0) {
CHECK_BIT_BUFFER(br_state, 1, goto undoit);
if (GET_BITS(1)) {
if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
if (*thiscoef >= 0)
*thiscoef += p1;
else
*thiscoef += m1;
}
}
} else {
if (--r < 0)
break; /* reached target zero coefficient */
}
k++;
} while (k <= Se);
if (s) {
int pos = jpeg_natural_order[k];
/* Output newly nonzero coefficient */
(*block)[pos] = (JCOEF) s;
/* Remember its position in case we have to suspend */
newnz_pos[num_newnz++] = pos;
}
}
}
if (EOBRUN > 0) {
/* Scan any remaining coefficient positions after the end-of-band
* (the last newly nonzero coefficient, if any). Append a correction
* bit to each already-nonzero coefficient. A correction bit is 1
* if the absolute value of the coefficient must be increased.
*/
for (; k <= Se; k++) {
thiscoef = *block + jpeg_natural_order[k];
if (*thiscoef != 0) {
CHECK_BIT_BUFFER(br_state, 1, goto undoit);
if (GET_BITS(1)) {
if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
if (*thiscoef >= 0)
*thiscoef += p1;
else
*thiscoef += m1;
}
}
}
}
/* Count one block completed in EOB run */
EOBRUN--;
}
/* Completed MCU, so update state */
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
}
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
undoit:
/* Re-zero any output coefficients that we made newly nonzero */
while (num_newnz > 0)
(*block)[newnz_pos[--num_newnz]] = 0;
return FALSE;
}
/*
* Decode one MCU's worth of Huffman-compressed coefficients.
*/
METHODDEF(boolean)
decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
int blkn;
BITREAD_STATE_VARS;
savable_state state;
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* If we've run out of data, just leave the MCU set to zeroes.
* This way, we return uniform gray for the remainder of the segment.
*/
if (! entropy->pub.insufficient_data) {
/* Load up working state */
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
ASSIGN_STATE(state, entropy->saved);
/* Outer loop handles each block in the MCU */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
JBLOCKROW block = MCU_data[blkn];
d_derived_tbl * htbl;
register int s, k, r;
int coef_limit, ci;
/* Decode a single block's worth of coefficients */
/* Section F.2.2.1: decode the DC coefficient difference */
htbl = entropy->dc_cur_tbls[blkn];
HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
htbl = entropy->ac_cur_tbls[blkn];
k = 1;
coef_limit = entropy->coef_limit[blkn];
if (coef_limit) {
/* Convert DC difference to actual value, update last_dc_val */
if (s) {
CHECK_BIT_BUFFER(br_state, s, return FALSE);
r = GET_BITS(s);
s = HUFF_EXTEND(r, s);
}
ci = cinfo->MCU_membership[blkn];
s += state.last_dc_val[ci];
state.last_dc_val[ci] = s;
/* Output the DC coefficient */
(*block)[0] = (JCOEF) s;
/* Section F.2.2.2: decode the AC coefficients */
/* Since zeroes are skipped, output area must be cleared beforehand */
for (; k < coef_limit; k++) {
HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
r = s >> 4;
s &= 15;
if (s) {
k += r;
CHECK_BIT_BUFFER(br_state, s, return FALSE);
r = GET_BITS(s);
s = HUFF_EXTEND(r, s);
/* Output coefficient in natural (dezigzagged) order.
* Note: the extra entries in jpeg_natural_order[] will save us
* if k >= DCTSIZE2, which could happen if the data is corrupted.
*/
(*block)[jpeg_natural_order[k]] = (JCOEF) s;
} else {
if (r != 15)
goto EndOfBlock;
k += 15;
}
}
} else {
if (s) {
CHECK_BIT_BUFFER(br_state, s, return FALSE);
DROP_BITS(s);
}
}
/* Section F.2.2.2: decode the AC coefficients */
/* In this path we just discard the values */
for (; k < DCTSIZE2; k++) {
HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
r = s >> 4;
s &= 15;
if (s) {
k += r;
CHECK_BIT_BUFFER(br_state, s, return FALSE);
DROP_BITS(s);
} else {
if (r != 15)
break;
k += 15;
}
}
EndOfBlock: ;
}
/* Completed MCU, so update state */
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
ASSIGN_STATE(entropy->saved, state);
}
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
}
/*
* Initialize for a Huffman-compressed scan.
*/
METHODDEF(void)
start_pass_huff_decoder (j_decompress_ptr cinfo)
{
huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
int ci, blkn, dctbl, actbl, i;
jpeg_component_info * compptr;
if (cinfo->progressive_mode) {
/* Validate progressive scan parameters */
if (cinfo->Ss == 0) {
if (cinfo->Se != 0)
goto bad;
} else {
/* need not check Ss/Se < 0 since they came from unsigned bytes */
if (cinfo->Se < cinfo->Ss || cinfo->Se >= DCTSIZE2)
goto bad;
/* AC scans may have only one component */
if (cinfo->comps_in_scan != 1)
goto bad;
}
if (cinfo->Ah != 0) {
/* Successive approximation refinement scan: must have Al = Ah-1. */
if (cinfo->Ah-1 != cinfo->Al)
goto bad;
}
if (cinfo->Al > 13) { /* need not check for < 0 */
/* Arguably the maximum Al value should be less than 13 for 8-bit precision,
* but the spec doesn't say so, and we try to be liberal about what we
* accept. Note: large Al values could result in out-of-range DC
* coefficients during early scans, leading to bizarre displays due to
* overflows in the IDCT math. But we won't crash.
*/
bad:
ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
}
/* Update progression status, and verify that scan order is legal.
* Note that inter-scan inconsistencies are treated as warnings
* not fatal errors ... not clear if this is right way to behave.
*/
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
if (cinfo->Ah != expected)
WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
coef_bit_ptr[coefi] = cinfo->Al;
}
}
/* Select MCU decoding routine */
if (cinfo->Ah == 0) {
if (cinfo->Ss == 0)
entropy->pub.decode_mcu = decode_mcu_DC_first;
else
entropy->pub.decode_mcu = decode_mcu_AC_first;
} else {
if (cinfo->Ss == 0)
entropy->pub.decode_mcu = decode_mcu_DC_refine;
else
entropy->pub.decode_mcu = decode_mcu_AC_refine;
}
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
/* Make sure requested tables are present, and compute derived tables.
* We may build same derived table more than once, but it's not expensive.
*/
if (cinfo->Ss == 0) {
if (cinfo->Ah == 0) { /* DC refinement needs no table */
i = compptr->dc_tbl_no;
jpeg_make_d_derived_tbl(cinfo, TRUE, i,
& entropy->derived_tbls[i]);
}
} else {
i = compptr->ac_tbl_no;
jpeg_make_d_derived_tbl(cinfo, FALSE, i,
& entropy->derived_tbls[i]);
/* remember the single active table */
entropy->ac_derived_tbl = entropy->derived_tbls[i];
}
/* Initialize DC predictions to 0 */
entropy->saved.last_dc_val[ci] = 0;
}
/* Initialize private state variables */
entropy->saved.EOBRUN = 0;
} else {
/* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
* This ought to be an error condition, but we make it a warning because
* there are some baseline files out there with all zeroes in these bytes.
*/
if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
cinfo->Ah != 0 || cinfo->Al != 0)
WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
/* Select MCU decoding routine */
entropy->pub.decode_mcu = decode_mcu;
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
dctbl = compptr->dc_tbl_no;
actbl = compptr->ac_tbl_no;
/* Compute derived values for Huffman tables */
/* We may do this more than once for a table, but it's not expensive */
jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
& entropy->dc_derived_tbls[dctbl]);
jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
& entropy->ac_derived_tbls[actbl]);
/* Initialize DC predictions to 0 */
entropy->saved.last_dc_val[ci] = 0;
}
/* Precalculate decoding info for each block in an MCU of this scan */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
ci = cinfo->MCU_membership[blkn];
compptr = cinfo->cur_comp_info[ci];
/* Precalculate which table to use for each block */
entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
/* Decide whether we really care about the coefficient values */
if (compptr->component_needed) {
ci = compptr->DCT_v_scaled_size;
if (ci <= 0 || ci > 8) ci = 8;
i = compptr->DCT_h_scaled_size;
if (i <= 0 || i > 8) i = 8;
entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1];
} else {
entropy->coef_limit[blkn] = 0;
}
}
}
/* Initialize bitread state variables */
entropy->bitstate.bits_left = 0;
entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
entropy->pub.insufficient_data = FALSE;
/* Initialize restart counter */
entropy->restarts_to_go = cinfo->restart_interval;
}
/*
* Module initialization routine for Huffman entropy decoding.
*/
GLOBAL(void)
jinit_huff_decoder (j_decompress_ptr cinfo)
{
huff_entropy_ptr entropy;
int i;
entropy = (huff_entropy_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(huff_entropy_decoder));
cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
entropy->pub.start_pass = start_pass_huff_decoder;
if (cinfo->progressive_mode) {
/* Create progression status table */
int *coef_bit_ptr, ci;
cinfo->coef_bits = (int (*)[DCTSIZE2])
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
cinfo->num_components*DCTSIZE2*SIZEOF(int));
coef_bit_ptr = & cinfo->coef_bits[0][0];
for (ci = 0; ci < cinfo->num_components; ci++)
for (i = 0; i < DCTSIZE2; i++)
*coef_bit_ptr++ = -1;
/* Mark derived tables unallocated */
for (i = 0; i < NUM_HUFF_TBLS; i++) {
entropy->derived_tbls[i] = NULL;
}
} else {
/* Mark tables unallocated */
for (i = 0; i < NUM_HUFF_TBLS; i++) {
entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
}
}
}
|
1137519-player
|
jpeg-7/jdhuff.c
|
C
|
lgpl
| 42,378
|
/*
* rdjpgcom.c
*
* Copyright (C) 1994-1997, Thomas G. Lane.
* Modified 2009 by Bill Allombert, Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains a very simple stand-alone application that displays
* the text in COM (comment) markers in a JFIF file.
* This may be useful as an example of the minimum logic needed to parse
* JPEG markers.
*/
#define JPEG_CJPEG_DJPEG /* to get the command-line config symbols */
#include "jinclude.h" /* get auto-config symbols, <stdio.h> */
#ifdef HAVE_LOCALE_H
#include <locale.h> /* Bill Allombert: use locale for isprint */
#endif
#include <ctype.h> /* to declare isupper(), tolower() */
#ifdef USE_SETMODE
#include <fcntl.h> /* to declare setmode()'s parameter macros */
/* If you have setmode() but not <io.h>, just delete this line: */
#include <io.h> /* to declare setmode() */
#endif
#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
#ifdef __MWERKS__
#include <SIOUX.h> /* Metrowerks needs this */
#include <console.h> /* ... and this */
#endif
#ifdef THINK_C
#include <console.h> /* Think declares it here */
#endif
#endif
#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
#define READ_BINARY "r"
#else
#ifdef VMS /* VMS is very nonstandard */
#define READ_BINARY "rb", "ctx=stm"
#else /* standard ANSI-compliant case */
#define READ_BINARY "rb"
#endif
#endif
#ifndef EXIT_FAILURE /* define exit() codes if not provided */
#define EXIT_FAILURE 1
#endif
#ifndef EXIT_SUCCESS
#ifdef VMS
#define EXIT_SUCCESS 1 /* VMS is very nonstandard */
#else
#define EXIT_SUCCESS 0
#endif
#endif
/*
* These macros are used to read the input file.
* To reuse this code in another application, you might need to change these.
*/
static FILE * infile; /* input JPEG file */
/* Return next input byte, or EOF if no more */
#define NEXTBYTE() getc(infile)
/* Error exit handler */
#define ERREXIT(msg) (fprintf(stderr, "%s\n", msg), exit(EXIT_FAILURE))
/* Read one byte, testing for EOF */
static int
read_1_byte (void)
{
int c;
c = NEXTBYTE();
if (c == EOF)
ERREXIT("Premature EOF in JPEG file");
return c;
}
/* Read 2 bytes, convert to unsigned int */
/* All 2-byte quantities in JPEG markers are MSB first */
static unsigned int
read_2_bytes (void)
{
int c1, c2;
c1 = NEXTBYTE();
if (c1 == EOF)
ERREXIT("Premature EOF in JPEG file");
c2 = NEXTBYTE();
if (c2 == EOF)
ERREXIT("Premature EOF in JPEG file");
return (((unsigned int) c1) << 8) + ((unsigned int) c2);
}
/*
* JPEG markers consist of one or more 0xFF bytes, followed by a marker
* code byte (which is not an FF). Here are the marker codes of interest
* in this program. (See jdmarker.c for a more complete list.)
*/
#define M_SOF0 0xC0 /* Start Of Frame N */
#define M_SOF1 0xC1 /* N indicates which compression process */
#define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */
#define M_SOF3 0xC3
#define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */
#define M_SOF6 0xC6
#define M_SOF7 0xC7
#define M_SOF9 0xC9
#define M_SOF10 0xCA
#define M_SOF11 0xCB
#define M_SOF13 0xCD
#define M_SOF14 0xCE
#define M_SOF15 0xCF
#define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */
#define M_EOI 0xD9 /* End Of Image (end of datastream) */
#define M_SOS 0xDA /* Start Of Scan (begins compressed data) */
#define M_APP0 0xE0 /* Application-specific marker, type N */
#define M_APP12 0xEC /* (we don't bother to list all 16 APPn's) */
#define M_COM 0xFE /* COMment */
/*
* Find the next JPEG marker and return its marker code.
* We expect at least one FF byte, possibly more if the compressor used FFs
* to pad the file.
* There could also be non-FF garbage between markers. The treatment of such
* garbage is unspecified; we choose to skip over it but emit a warning msg.
* NB: this routine must not be used after seeing SOS marker, since it will
* not deal correctly with FF/00 sequences in the compressed image data...
*/
static int
next_marker (void)
{
int c;
int discarded_bytes = 0;
/* Find 0xFF byte; count and skip any non-FFs. */
c = read_1_byte();
while (c != 0xFF) {
discarded_bytes++;
c = read_1_byte();
}
/* Get marker code byte, swallowing any duplicate FF bytes. Extra FFs
* are legal as pad bytes, so don't count them in discarded_bytes.
*/
do {
c = read_1_byte();
} while (c == 0xFF);
if (discarded_bytes != 0) {
fprintf(stderr, "Warning: garbage data found in JPEG file\n");
}
return c;
}
/*
* Read the initial marker, which should be SOI.
* For a JFIF file, the first two bytes of the file should be literally
* 0xFF M_SOI. To be more general, we could use next_marker, but if the
* input file weren't actually JPEG at all, next_marker might read the whole
* file and then return a misleading error message...
*/
static int
first_marker (void)
{
int c1, c2;
c1 = NEXTBYTE();
c2 = NEXTBYTE();
if (c1 != 0xFF || c2 != M_SOI)
ERREXIT("Not a JPEG file");
return c2;
}
/*
* Most types of marker are followed by a variable-length parameter segment.
* This routine skips over the parameters for any marker we don't otherwise
* want to process.
* Note that we MUST skip the parameter segment explicitly in order not to
* be fooled by 0xFF bytes that might appear within the parameter segment;
* such bytes do NOT introduce new markers.
*/
static void
skip_variable (void)
/* Skip over an unknown or uninteresting variable-length marker */
{
unsigned int length;
/* Get the marker parameter length count */
length = read_2_bytes();
/* Length includes itself, so must be at least 2 */
if (length < 2)
ERREXIT("Erroneous JPEG marker length");
length -= 2;
/* Skip over the remaining bytes */
while (length > 0) {
(void) read_1_byte();
length--;
}
}
/*
* Process a COM marker.
* We want to print out the marker contents as legible text;
* we must guard against non-text junk and varying newline representations.
*/
static void
process_COM (int raw)
{
unsigned int length;
int ch;
int lastch = 0;
/* Bill Allombert: set locale properly for isprint */
#ifdef HAVE_LOCALE_H
setlocale(LC_CTYPE, "");
#endif
/* Get the marker parameter length count */
length = read_2_bytes();
/* Length includes itself, so must be at least 2 */
if (length < 2)
ERREXIT("Erroneous JPEG marker length");
length -= 2;
while (length > 0) {
ch = read_1_byte();
if (raw) {
putc(ch, stdout);
/* Emit the character in a readable form.
* Nonprintables are converted to \nnn form,
* while \ is converted to \\.
* Newlines in CR, CR/LF, or LF form will be printed as one newline.
*/
} else if (ch == '\r') {
printf("\n");
} else if (ch == '\n') {
if (lastch != '\r')
printf("\n");
} else if (ch == '\\') {
printf("\\\\");
} else if (isprint(ch)) {
putc(ch, stdout);
} else {
printf("\\%03o", ch);
}
lastch = ch;
length--;
}
printf("\n");
/* Bill Allombert: revert to C locale */
#ifdef HAVE_LOCALE_H
setlocale(LC_CTYPE, "C");
#endif
}
/*
* Process a SOFn marker.
* This code is only needed if you want to know the image dimensions...
*/
static void
process_SOFn (int marker)
{
unsigned int length;
unsigned int image_height, image_width;
int data_precision, num_components;
const char * process;
int ci;
length = read_2_bytes(); /* usual parameter length count */
data_precision = read_1_byte();
image_height = read_2_bytes();
image_width = read_2_bytes();
num_components = read_1_byte();
switch (marker) {
case M_SOF0: process = "Baseline"; break;
case M_SOF1: process = "Extended sequential"; break;
case M_SOF2: process = "Progressive"; break;
case M_SOF3: process = "Lossless"; break;
case M_SOF5: process = "Differential sequential"; break;
case M_SOF6: process = "Differential progressive"; break;
case M_SOF7: process = "Differential lossless"; break;
case M_SOF9: process = "Extended sequential, arithmetic coding"; break;
case M_SOF10: process = "Progressive, arithmetic coding"; break;
case M_SOF11: process = "Lossless, arithmetic coding"; break;
case M_SOF13: process = "Differential sequential, arithmetic coding"; break;
case M_SOF14: process = "Differential progressive, arithmetic coding"; break;
case M_SOF15: process = "Differential lossless, arithmetic coding"; break;
default: process = "Unknown"; break;
}
printf("JPEG image is %uw * %uh, %d color components, %d bits per sample\n",
image_width, image_height, num_components, data_precision);
printf("JPEG process: %s\n", process);
if (length != (unsigned int) (8 + num_components * 3))
ERREXIT("Bogus SOF marker length");
for (ci = 0; ci < num_components; ci++) {
(void) read_1_byte(); /* Component ID code */
(void) read_1_byte(); /* H, V sampling factors */
(void) read_1_byte(); /* Quantization table number */
}
}
/*
* Parse the marker stream until SOS or EOI is seen;
* display any COM markers.
* While the companion program wrjpgcom will always insert COM markers before
* SOFn, other implementations might not, so we scan to SOS before stopping.
* If we were only interested in the image dimensions, we would stop at SOFn.
* (Conversely, if we only cared about COM markers, there would be no need
* for special code to handle SOFn; we could treat it like other markers.)
*/
static int
scan_JPEG_header (int verbose, int raw)
{
int marker;
/* Expect SOI at start of file */
if (first_marker() != M_SOI)
ERREXIT("Expected SOI marker first");
/* Scan miscellaneous markers until we reach SOS. */
for (;;) {
marker = next_marker();
switch (marker) {
/* Note that marker codes 0xC4, 0xC8, 0xCC are not, and must not be,
* treated as SOFn. C4 in particular is actually DHT.
*/
case M_SOF0: /* Baseline */
case M_SOF1: /* Extended sequential, Huffman */
case M_SOF2: /* Progressive, Huffman */
case M_SOF3: /* Lossless, Huffman */
case M_SOF5: /* Differential sequential, Huffman */
case M_SOF6: /* Differential progressive, Huffman */
case M_SOF7: /* Differential lossless, Huffman */
case M_SOF9: /* Extended sequential, arithmetic */
case M_SOF10: /* Progressive, arithmetic */
case M_SOF11: /* Lossless, arithmetic */
case M_SOF13: /* Differential sequential, arithmetic */
case M_SOF14: /* Differential progressive, arithmetic */
case M_SOF15: /* Differential lossless, arithmetic */
if (verbose)
process_SOFn(marker);
else
skip_variable();
break;
case M_SOS: /* stop before hitting compressed data */
return marker;
case M_EOI: /* in case it's a tables-only JPEG stream */
return marker;
case M_COM:
process_COM(raw);
break;
case M_APP12:
/* Some digital camera makers put useful textual information into
* APP12 markers, so we print those out too when in -verbose mode.
*/
if (verbose) {
printf("APP12 contains:\n");
process_COM(raw);
} else
skip_variable();
break;
default: /* Anything else just gets skipped */
skip_variable(); /* we assume it has a parameter count... */
break;
}
} /* end loop */
}
/* Command line parsing code */
static const char * progname; /* program name for error messages */
static void
usage (void)
/* complain about bad command line */
{
fprintf(stderr, "rdjpgcom displays any textual comments in a JPEG file.\n");
fprintf(stderr, "Usage: %s [switches] [inputfile]\n", progname);
fprintf(stderr, "Switches (names may be abbreviated):\n");
fprintf(stderr, " -raw Display non-printable characters in comments (unsafe)\n");
fprintf(stderr, " -verbose Also display dimensions of JPEG image\n");
exit(EXIT_FAILURE);
}
static int
keymatch (char * arg, const char * keyword, int minchars)
/* Case-insensitive matching of (possibly abbreviated) keyword switches. */
/* keyword is the constant keyword (must be lower case already), */
/* minchars is length of minimum legal abbreviation. */
{
register int ca, ck;
register int nmatched = 0;
while ((ca = *arg++) != '\0') {
if ((ck = *keyword++) == '\0')
return 0; /* arg longer than keyword, no good */
if (isupper(ca)) /* force arg to lcase (assume ck is already) */
ca = tolower(ca);
if (ca != ck)
return 0; /* no good */
nmatched++; /* count matched characters */
}
/* reached end of argument; fail if it's too short for unique abbrev */
if (nmatched < minchars)
return 0;
return 1; /* A-OK */
}
/*
* The main program.
*/
int
main (int argc, char **argv)
{
int argn;
char * arg;
int verbose = 0, raw = 0;
/* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
argc = ccommand(&argv);
#endif
progname = argv[0];
if (progname == NULL || progname[0] == 0)
progname = "rdjpgcom"; /* in case C library doesn't provide it */
/* Parse switches, if any */
for (argn = 1; argn < argc; argn++) {
arg = argv[argn];
if (arg[0] != '-')
break; /* not switch, must be file name */
arg++; /* advance over '-' */
if (keymatch(arg, "verbose", 1)) {
verbose++;
} else if (keymatch(arg, "raw", 1)) {
raw = 1;
} else
usage();
}
/* Open the input file. */
/* Unix style: expect zero or one file name */
if (argn < argc-1) {
fprintf(stderr, "%s: only one input file\n", progname);
usage();
}
if (argn < argc) {
if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
exit(EXIT_FAILURE);
}
} else {
/* default input file is stdin */
#ifdef USE_SETMODE /* need to hack file mode? */
setmode(fileno(stdin), O_BINARY);
#endif
#ifdef USE_FDOPEN /* need to re-open in binary mode? */
if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open stdin\n", progname);
exit(EXIT_FAILURE);
}
#else
infile = stdin;
#endif
}
/* Scan the JPEG headers. */
(void) scan_JPEG_header(verbose, raw);
/* All done. */
exit(EXIT_SUCCESS);
return 0; /* suppress no-return-value warnings */
}
|
1137519-player
|
jpeg-7/rdjpgcom.c
|
C
|
lgpl
| 14,466
|
/*
* jdtrans.c
*
* Copyright (C) 1995-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains library routines for transcoding decompression,
* that is, reading raw DCT coefficient arrays from an input JPEG file.
* The routines in jdapimin.c will also be needed by a transcoder.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/* Forward declarations */
LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
/*
* Read the coefficient arrays from a JPEG file.
* jpeg_read_header must be completed before calling this.
*
* The entire image is read into a set of virtual coefficient-block arrays,
* one per component. The return value is a pointer to the array of
* virtual-array descriptors. These can be manipulated directly via the
* JPEG memory manager, or handed off to jpeg_write_coefficients().
* To release the memory occupied by the virtual arrays, call
* jpeg_finish_decompress() when done with the data.
*
* An alternative usage is to simply obtain access to the coefficient arrays
* during a buffered-image-mode decompression operation. This is allowed
* after any jpeg_finish_output() call. The arrays can be accessed until
* jpeg_finish_decompress() is called. (Note that any call to the library
* may reposition the arrays, so don't rely on access_virt_barray() results
* to stay valid across library calls.)
*
* Returns NULL if suspended. This case need be checked only if
* a suspending data source is used.
*/
GLOBAL(jvirt_barray_ptr *)
jpeg_read_coefficients (j_decompress_ptr cinfo)
{
if (cinfo->global_state == DSTATE_READY) {
/* First call: initialize active modules */
transdecode_master_selection(cinfo);
cinfo->global_state = DSTATE_RDCOEFS;
}
if (cinfo->global_state == DSTATE_RDCOEFS) {
/* Absorb whole file into the coef buffer */
for (;;) {
int retcode;
/* Call progress monitor hook if present */
if (cinfo->progress != NULL)
(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
/* Absorb some more input */
retcode = (*cinfo->inputctl->consume_input) (cinfo);
if (retcode == JPEG_SUSPENDED)
return NULL;
if (retcode == JPEG_REACHED_EOI)
break;
/* Advance progress counter if appropriate */
if (cinfo->progress != NULL &&
(retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
/* startup underestimated number of scans; ratchet up one scan */
cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
}
}
}
/* Set state so that jpeg_finish_decompress does the right thing */
cinfo->global_state = DSTATE_STOPPING;
}
/* At this point we should be in state DSTATE_STOPPING if being used
* standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
* to the coefficients during a full buffered-image-mode decompression.
*/
if ((cinfo->global_state == DSTATE_STOPPING ||
cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
return cinfo->coef->coef_arrays;
}
/* Oops, improper usage */
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
return NULL; /* keep compiler happy */
}
/*
* Master selection of decompression modules for transcoding.
* This substitutes for jdmaster.c's initialization of the full decompressor.
*/
LOCAL(void)
transdecode_master_selection (j_decompress_ptr cinfo)
{
/* This is effectively a buffered-image operation. */
cinfo->buffered_image = TRUE;
/* Entropy decoding: either Huffman or arithmetic coding. */
if (cinfo->arith_code)
jinit_arith_decoder(cinfo);
else {
jinit_huff_decoder(cinfo);
}
/* Always get a full-image coefficient buffer. */
jinit_d_coef_controller(cinfo, TRUE);
/* We can now tell the memory manager to allocate virtual arrays. */
(*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
/* Initialize input side of decompressor to consume first scan. */
(*cinfo->inputctl->start_input_pass) (cinfo);
/* Initialize progress monitoring. */
if (cinfo->progress != NULL) {
int nscans;
/* Estimate number of scans to set pass_limit. */
if (cinfo->progressive_mode) {
/* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
nscans = 2 + 3 * cinfo->num_components;
} else if (cinfo->inputctl->has_multiple_scans) {
/* For a nonprogressive multiscan file, estimate 1 scan per component. */
nscans = cinfo->num_components;
} else {
nscans = 1;
}
cinfo->progress->pass_counter = 0L;
cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
cinfo->progress->completed_passes = 0;
cinfo->progress->total_passes = 1;
}
}
|
1137519-player
|
jpeg-7/jdtrans.c
|
C
|
lgpl
| 4,911
|
;
; jmemdosa.asm
;
; Copyright (C) 1992, Thomas G. Lane.
; This file is part of the Independent JPEG Group's software.
; For conditions of distribution and use, see the accompanying README file.
;
; This file contains low-level interface routines to support the MS-DOS
; backing store manager (jmemdos.c). Routines are provided to access disk
; files through direct DOS calls, and to access XMS and EMS drivers.
;
; This file should assemble with Microsoft's MASM or any compatible
; assembler (including Borland's Turbo Assembler). If you haven't got
; a compatible assembler, better fall back to jmemansi.c or jmemname.c.
;
; To minimize dependence on the C compiler's register usage conventions,
; we save and restore all 8086 registers, even though most compilers only
; require SI,DI,DS to be preserved. Also, we use only 16-bit-wide return
; values, which everybody returns in AX.
;
; Based on code contributed by Ge' Weijers.
;
JMEMDOSA_TXT segment byte public 'CODE'
assume cs:JMEMDOSA_TXT
public _jdos_open
public _jdos_close
public _jdos_seek
public _jdos_read
public _jdos_write
public _jxms_getdriver
public _jxms_calldriver
public _jems_available
public _jems_calldriver
;
; short far jdos_open (short far * handle, char far * filename)
;
; Create and open a temporary file
;
_jdos_open proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov cx,0 ; normal file attributes
lds dx,dword ptr [bp+10] ; get filename pointer
mov ah,3ch ; create file
int 21h
jc open_err ; if failed, return error code
lds bx,dword ptr [bp+6] ; get handle pointer
mov word ptr [bx],ax ; save the handle
xor ax,ax ; return zero for OK
open_err: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jdos_open endp
;
; short far jdos_close (short handle)
;
; Close the file handle
;
_jdos_close proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov bx,word ptr [bp+6] ; file handle
mov ah,3eh ; close file
int 21h
jc close_err ; if failed, return error code
xor ax,ax ; return zero for OK
close_err: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jdos_close endp
;
; short far jdos_seek (short handle, long offset)
;
; Set file position
;
_jdos_seek proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov bx,word ptr [bp+6] ; file handle
mov dx,word ptr [bp+8] ; LS offset
mov cx,word ptr [bp+10] ; MS offset
mov ax,4200h ; absolute seek
int 21h
jc seek_err ; if failed, return error code
xor ax,ax ; return zero for OK
seek_err: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jdos_seek endp
;
; short far jdos_read (short handle, void far * buffer, unsigned short count)
;
; Read from file
;
_jdos_read proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov bx,word ptr [bp+6] ; file handle
lds dx,dword ptr [bp+8] ; buffer address
mov cx,word ptr [bp+12] ; number of bytes
mov ah,3fh ; read file
int 21h
jc read_err ; if failed, return error code
cmp ax,word ptr [bp+12] ; make sure all bytes were read
je read_ok
mov ax,1 ; else return 1 for not OK
jmp short read_err
read_ok: xor ax,ax ; return zero for OK
read_err: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jdos_read endp
;
; short far jdos_write (short handle, void far * buffer, unsigned short count)
;
; Write to file
;
_jdos_write proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov bx,word ptr [bp+6] ; file handle
lds dx,dword ptr [bp+8] ; buffer address
mov cx,word ptr [bp+12] ; number of bytes
mov ah,40h ; write file
int 21h
jc write_err ; if failed, return error code
cmp ax,word ptr [bp+12] ; make sure all bytes written
je write_ok
mov ax,1 ; else return 1 for not OK
jmp short write_err
write_ok: xor ax,ax ; return zero for OK
write_err: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jdos_write endp
;
; void far jxms_getdriver (XMSDRIVER far *)
;
; Get the address of the XMS driver, or NULL if not available
;
_jxms_getdriver proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov ax,4300h ; call multiplex interrupt with
int 2fh ; a magic cookie, hex 4300
cmp al,80h ; AL should contain hex 80
je xmsavail
xor dx,dx ; no XMS driver available
xor ax,ax ; return a nil pointer
jmp short xmsavail_done
xmsavail: mov ax,4310h ; fetch driver address with
int 2fh ; another magic cookie
mov dx,es ; copy address to dx:ax
mov ax,bx
xmsavail_done: les bx,dword ptr [bp+6] ; get pointer to return value
mov word ptr es:[bx],ax
mov word ptr es:[bx+2],dx
pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jxms_getdriver endp
;
; void far jxms_calldriver (XMSDRIVER, XMScontext far *)
;
; The XMScontext structure contains values for the AX,DX,BX,SI,DS registers.
; These are loaded, the XMS call is performed, and the new values of the
; AX,DX,BX registers are written back to the context structure.
;
_jxms_calldriver proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
les bx,dword ptr [bp+10] ; get XMScontext pointer
mov ax,word ptr es:[bx] ; load registers
mov dx,word ptr es:[bx+2]
mov si,word ptr es:[bx+6]
mov ds,word ptr es:[bx+8]
mov bx,word ptr es:[bx+4]
call dword ptr [bp+6] ; call the driver
mov cx,bx ; save returned BX for a sec
les bx,dword ptr [bp+10] ; get XMScontext pointer
mov word ptr es:[bx],ax ; put back ax,dx,bx
mov word ptr es:[bx+2],dx
mov word ptr es:[bx+4],cx
pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jxms_calldriver endp
;
; short far jems_available (void)
;
; Have we got an EMS driver? (this comes straight from the EMS 4.0 specs)
;
_jems_available proc far
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov ax,3567h ; get interrupt vector 67h
int 21h
push cs
pop ds
mov di,000ah ; check offs 10 in returned seg
lea si,ASCII_device_name ; against literal string
mov cx,8
cld
repe cmpsb
jne no_ems
mov ax,1 ; match, it's there
jmp short avail_done
no_ems: xor ax,ax ; it's not there
avail_done: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
ret
ASCII_device_name db "EMMXXXX0"
_jems_available endp
;
; void far jems_calldriver (EMScontext far *)
;
; The EMScontext structure contains values for the AX,DX,BX,SI,DS registers.
; These are loaded, the EMS trap is performed, and the new values of the
; AX,DX,BX registers are written back to the context structure.
;
_jems_calldriver proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
les bx,dword ptr [bp+6] ; get EMScontext pointer
mov ax,word ptr es:[bx] ; load registers
mov dx,word ptr es:[bx+2]
mov si,word ptr es:[bx+6]
mov ds,word ptr es:[bx+8]
mov bx,word ptr es:[bx+4]
int 67h ; call the EMS driver
mov cx,bx ; save returned BX for a sec
les bx,dword ptr [bp+6] ; get EMScontext pointer
mov word ptr es:[bx],ax ; put back ax,dx,bx
mov word ptr es:[bx+2],dx
mov word ptr es:[bx+4],cx
pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jems_calldriver endp
JMEMDOSA_TXT ends
end
|
1137519-player
|
jpeg-7/jmemdosa.asm
|
Assembly
|
lgpl
| 8,314
|
/*
* jdmaster.c
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* Modified 2002-2008 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains master control logic for the JPEG decompressor.
* These routines are concerned with selecting the modules to be executed
* and with determining the number of passes and the work to be done in each
* pass.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/* Private state */
typedef struct {
struct jpeg_decomp_master pub; /* public fields */
int pass_number; /* # of passes completed */
boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
/* Saved references to initialized quantizer modules,
* in case we need to switch modes.
*/
struct jpeg_color_quantizer * quantizer_1pass;
struct jpeg_color_quantizer * quantizer_2pass;
} my_decomp_master;
typedef my_decomp_master * my_master_ptr;
/*
* Determine whether merged upsample/color conversion should be used.
* CRUCIAL: this must match the actual capabilities of jdmerge.c!
*/
LOCAL(boolean)
use_merged_upsample (j_decompress_ptr cinfo)
{
#ifdef UPSAMPLE_MERGING_SUPPORTED
// added by Tonsuke
if(cinfo->useMergedUpsampling){
return TRUE;
} else {
return FALSE;
}
/* Merging is the equivalent of plain box-filter upsampling */
if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
return FALSE;
/* jdmerge.c only supports YCC=>RGB color conversion */
if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
cinfo->out_color_space != JCS_RGB ||
cinfo->out_color_components != RGB_PIXELSIZE)
return FALSE;
/* and it only handles 2h1v or 2h2v sampling ratios */
if (cinfo->comp_info[0].h_samp_factor != 2 ||
cinfo->comp_info[1].h_samp_factor != 1 ||
cinfo->comp_info[2].h_samp_factor != 1 ||
cinfo->comp_info[0].v_samp_factor > 2 ||
cinfo->comp_info[1].v_samp_factor != 1 ||
cinfo->comp_info[2].v_samp_factor != 1)
return FALSE;
/* furthermore, it doesn't work if we've scaled the IDCTs differently */
if (cinfo->comp_info[0].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size ||
cinfo->comp_info[1].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size ||
cinfo->comp_info[2].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size ||
cinfo->comp_info[0].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size ||
cinfo->comp_info[1].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size ||
cinfo->comp_info[2].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size)
return FALSE;
/* ??? also need to test for upsample-time rescaling, when & if supported */
return TRUE; /* by golly, it'll work... */
#else
return FALSE;
#endif
}
/*
* Compute output image dimensions and related values.
* NOTE: this is exported for possible use by application.
* Hence it mustn't do anything that can't be done twice.
* Also note that it may be called before the master module is initialized!
*/
GLOBAL(void)
jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
/* Do computations that are needed before master selection phase */
{
#ifdef IDCT_SCALING_SUPPORTED
int ci;
jpeg_component_info *compptr;
#endif
/* Prevent application from calling me at wrong times */
if (cinfo->global_state != DSTATE_READY)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
/*
if(cinfo.useMergedUpsampling){
cinfo->output_width = cinfo->image_width;
cinfo->output_height = cinfo->image_height;
goto SKIP;
}
*/
#ifdef IDCT_SCALING_SUPPORTED
if(!cinfo->useMergedUpsampling){ // modified by Tonsuke
/* Compute actual output image dimensions and DCT scaling choices. */
if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
/* Provide 1/8 scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width, 8L);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height, 8L);
cinfo->min_DCT_h_scaled_size = 1;
cinfo->min_DCT_v_scaled_size = 1;
} else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
/* Provide 1/4 scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width, 4L);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height, 4L);
cinfo->min_DCT_h_scaled_size = 2;
cinfo->min_DCT_v_scaled_size = 2;
} else if (cinfo->scale_num * 8 <= cinfo->scale_denom * 3) {
/* Provide 3/8 scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 3L, 8L);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 3L, 8L);
cinfo->min_DCT_h_scaled_size = 3;
cinfo->min_DCT_v_scaled_size = 3;
} else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
/* Provide 1/2 scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width, 2L);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height, 2L);
cinfo->min_DCT_h_scaled_size = 4;
cinfo->min_DCT_v_scaled_size = 4;
} else if (cinfo->scale_num * 8 <= cinfo->scale_denom * 5) {
/* Provide 5/8 scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 5L, 8L);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 5L, 8L);
cinfo->min_DCT_h_scaled_size = 5;
cinfo->min_DCT_v_scaled_size = 5;
} else if (cinfo->scale_num * 4 <= cinfo->scale_denom * 3) {
/* Provide 3/4 scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 3L, 4L);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 3L, 4L);
cinfo->min_DCT_h_scaled_size = 6;
cinfo->min_DCT_v_scaled_size = 6;
} else if (cinfo->scale_num * 8 <= cinfo->scale_denom * 7) {
/* Provide 7/8 scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 7L, 8L);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 7L, 8L);
cinfo->min_DCT_h_scaled_size = 7;
cinfo->min_DCT_v_scaled_size = 7;
} else if (cinfo->scale_num <= cinfo->scale_denom) {
/* Provide 1/1 scaling */
cinfo->output_width = cinfo->image_width;
cinfo->output_height = cinfo->image_height;
cinfo->min_DCT_h_scaled_size = DCTSIZE;
cinfo->min_DCT_v_scaled_size = DCTSIZE;
} else if (cinfo->scale_num * 8 <= cinfo->scale_denom * 9) {
/* Provide 9/8 scaling */
cinfo->output_width = cinfo->image_width + (JDIMENSION)
jdiv_round_up((long) cinfo->image_width, 8L);
cinfo->output_height = cinfo->image_height + (JDIMENSION)
jdiv_round_up((long) cinfo->image_height, 8L);
cinfo->min_DCT_h_scaled_size = 9;
cinfo->min_DCT_v_scaled_size = 9;
} else if (cinfo->scale_num * 4 <= cinfo->scale_denom * 5) {
/* Provide 5/4 scaling */
cinfo->output_width = cinfo->image_width + (JDIMENSION)
jdiv_round_up((long) cinfo->image_width, 4L);
cinfo->output_height = cinfo->image_height + (JDIMENSION)
jdiv_round_up((long) cinfo->image_height, 4L);
cinfo->min_DCT_h_scaled_size = 10;
cinfo->min_DCT_v_scaled_size = 10;
} else if (cinfo->scale_num * 8 <= cinfo->scale_denom * 11) {
/* Provide 11/8 scaling */
cinfo->output_width = cinfo->image_width + (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 3L, 8L);
cinfo->output_height = cinfo->image_height + (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 3L, 8L);
cinfo->min_DCT_h_scaled_size = 11;
cinfo->min_DCT_v_scaled_size = 11;
} else if (cinfo->scale_num * 2 <= cinfo->scale_denom * 3) {
/* Provide 3/2 scaling */
cinfo->output_width = cinfo->image_width + (JDIMENSION)
jdiv_round_up((long) cinfo->image_width, 2L);
cinfo->output_height = cinfo->image_height + (JDIMENSION)
jdiv_round_up((long) cinfo->image_height, 2L);
cinfo->min_DCT_h_scaled_size = 12;
cinfo->min_DCT_v_scaled_size = 12;
} else if (cinfo->scale_num * 8 <= cinfo->scale_denom * 13) {
/* Provide 13/8 scaling */
cinfo->output_width = cinfo->image_width + (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 5L, 8L);
cinfo->output_height = cinfo->image_height + (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 5L, 8L);
cinfo->min_DCT_h_scaled_size = 13;
cinfo->min_DCT_v_scaled_size = 13;
} else if (cinfo->scale_num * 4 <= cinfo->scale_denom * 7) {
/* Provide 7/4 scaling */
cinfo->output_width = cinfo->image_width + (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 3L, 4L);
cinfo->output_height = cinfo->image_height + (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 3L, 4L);
cinfo->min_DCT_h_scaled_size = 14;
cinfo->min_DCT_v_scaled_size = 14;
} else if (cinfo->scale_num * 8 <= cinfo->scale_denom * 15) {
/* Provide 15/8 scaling */
cinfo->output_width = cinfo->image_width + (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 7L, 8L);
cinfo->output_height = cinfo->image_height + (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 7L, 8L);
cinfo->min_DCT_h_scaled_size = 15;
cinfo->min_DCT_v_scaled_size = 15;
} else {
/* Provide 2/1 scaling */
cinfo->output_width = cinfo->image_width << 1;
cinfo->output_height = cinfo->image_height << 1;
cinfo->min_DCT_h_scaled_size = 16;
cinfo->min_DCT_v_scaled_size = 16;
}
} else {
/* Provide 1/1 scaling */
cinfo->output_width = cinfo->image_width;
cinfo->output_height = cinfo->image_height;
cinfo->min_DCT_h_scaled_size = DCTSIZE;
cinfo->min_DCT_v_scaled_size = DCTSIZE;
}
/* In selecting the actual DCT scaling for each component, we try to
* scale up the chroma components via IDCT scaling rather than upsampling.
* This saves time if the upsampler gets to use 1:1 scaling.
* Note this code adapts subsampling ratios which are powers of 2.
*/
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
int ssize = 1;
while (cinfo->min_DCT_h_scaled_size * ssize <=
(cinfo->do_fancy_upsampling ? DCTSIZE : DCTSIZE / 2) &&
(cinfo->max_h_samp_factor % (compptr->h_samp_factor * ssize * 2)) == 0) {
ssize = ssize * 2;
}
compptr->DCT_h_scaled_size = cinfo->min_DCT_h_scaled_size * ssize;
ssize = 1;
while (cinfo->min_DCT_v_scaled_size * ssize <=
(cinfo->do_fancy_upsampling ? DCTSIZE : DCTSIZE / 2) &&
(cinfo->max_v_samp_factor % (compptr->v_samp_factor * ssize * 2)) == 0) {
ssize = ssize * 2;
}
compptr->DCT_v_scaled_size = cinfo->min_DCT_v_scaled_size * ssize;
/* We don't support IDCT ratios larger than 2. */
if (compptr->DCT_h_scaled_size > compptr->DCT_v_scaled_size * 2)
compptr->DCT_h_scaled_size = compptr->DCT_v_scaled_size * 2;
else if (compptr->DCT_v_scaled_size > compptr->DCT_h_scaled_size * 2)
compptr->DCT_v_scaled_size = compptr->DCT_h_scaled_size * 2;
}
/* Recompute downsampled dimensions of components;
* application needs to know these if using raw downsampled data.
*/
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
/* Size in samples, after IDCT scaling */
compptr->downsampled_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width *
(long) (compptr->h_samp_factor * compptr->DCT_h_scaled_size),
(long) (cinfo->max_h_samp_factor * DCTSIZE));
compptr->downsampled_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height *
(long) (compptr->v_samp_factor * compptr->DCT_v_scaled_size),
(long) (cinfo->max_v_samp_factor * DCTSIZE));
}
#else /* !IDCT_SCALING_SUPPORTED */
/* Hardwire it to "no scaling" */
cinfo->output_width = cinfo->image_width;
cinfo->output_height = cinfo->image_height;
/* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
* and has computed unscaled downsampled_width and downsampled_height.
*/
#endif /* IDCT_SCALING_SUPPORTED */
/* Report number of components in selected colorspace. */
/* Probably this should be in the color conversion module... */
switch (cinfo->out_color_space) {
case JCS_GRAYSCALE:
cinfo->out_color_components = 1;
break;
case JCS_RGB:
#if RGB_PIXELSIZE != 3
cinfo->out_color_components = RGB_PIXELSIZE;
break;
#endif /* else share code with YCbCr */
case JCS_YCbCr:
cinfo->out_color_components = 3;
break;
case JCS_CMYK:
case JCS_YCCK:
cinfo->out_color_components = 4;
break;
default: /* else must be same colorspace as in file */
cinfo->out_color_components = cinfo->num_components;
break;
}
cinfo->output_components = (cinfo->quantize_colors ? 1 :
cinfo->out_color_components);
/* See if upsampler will want to emit more than one row at a time */
if (use_merged_upsample(cinfo))
cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
else
cinfo->rec_outbuf_height = 1;
}
/*
* Several decompression processes need to range-limit values to the range
* 0..MAXJSAMPLE; the input value may fall somewhat outside this range
* due to noise introduced by quantization, roundoff error, etc. These
* processes are inner loops and need to be as fast as possible. On most
* machines, particularly CPUs with pipelines or instruction prefetch,
* a (subscript-check-less) C table lookup
* x = sample_range_limit[x];
* is faster than explicit tests
* if (x < 0) x = 0;
* else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
* These processes all use a common table prepared by the routine below.
*
* For most steps we can mathematically guarantee that the initial value
* of x is within MAXJSAMPLE+1 of the legal range, so a table running from
* -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
* limiting step (just after the IDCT), a wildly out-of-range value is
* possible if the input data is corrupt. To avoid any chance of indexing
* off the end of memory and getting a bad-pointer trap, we perform the
* post-IDCT limiting thus:
* x = range_limit[x & MASK];
* where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
* samples. Under normal circumstances this is more than enough range and
* a correct output will be generated; with bogus input data the mask will
* cause wraparound, and we will safely generate a bogus-but-in-range output.
* For the post-IDCT step, we want to convert the data from signed to unsigned
* representation by adding CENTERJSAMPLE at the same time that we limit it.
* So the post-IDCT limiting table ends up looking like this:
* CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
* MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
* 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
* 0,1,...,CENTERJSAMPLE-1
* Negative inputs select values from the upper half of the table after
* masking.
*
* We can save some space by overlapping the start of the post-IDCT table
* with the simpler range limiting table. The post-IDCT table begins at
* sample_range_limit + CENTERJSAMPLE.
*
* Note that the table is allocated in near data space on PCs; it's small
* enough and used often enough to justify this.
*/
LOCAL(void)
prepare_range_limit_table (j_decompress_ptr cinfo)
/* Allocate and fill in the sample_range_limit table */
{
JSAMPLE * table;
int i;
table = (JSAMPLE *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
(5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
cinfo->sample_range_limit = table;
/* First segment of "simple" table: limit[x] = 0 for x < 0 */
MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
/* Main part of "simple" table: limit[x] = x */
for (i = 0; i <= MAXJSAMPLE; i++)
table[i] = (JSAMPLE) i;
table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
/* End of simple table, rest of first half of post-IDCT table */
for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
table[i] = MAXJSAMPLE;
/* Second half of post-IDCT table */
MEMZERO(table + (2 * (MAXJSAMPLE+1)),
(2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
}
void
prepare_range_limit_table2 (JSAMPLE *jpeg_limit_table, j_decompress_ptr cinfo)
/* Allocate and fill in the sample_range_limit table */
{
JSAMPLE * table;
int i;
table = jpeg_limit_table;
table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
cinfo->sample_range_limit = table;
/* First segment of "simple" table: limit[x] = 0 for x < 0 */
MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
/* Main part of "simple" table: limit[x] = x */
for (i = 0; i <= MAXJSAMPLE; i++)
table[i] = (JSAMPLE) i;
table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
/* End of simple table, rest of first half of post-IDCT table */
for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
table[i] = MAXJSAMPLE;
/* Second half of post-IDCT table */
MEMZERO(table + (2 * (MAXJSAMPLE+1)),
(2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
}
/*
* Master selection of decompression modules.
* This is done once at jpeg_start_decompress time. We determine
* which modules will be used and give them appropriate initialization calls.
* We also initialize the decompressor input side to begin consuming data.
*
* Since jpeg_read_header has finished, we know what is in the SOF
* and (first) SOS markers. We also have all the application parameter
* settings.
*/
LOCAL(void)
master_selection (j_decompress_ptr cinfo)
{
my_master_ptr master = (my_master_ptr) cinfo->master;
boolean use_c_buffer;
long samplesperrow;
JDIMENSION jd_samplesperrow;
/* Initialize dimensions and other stuff */
if(cinfo->useMergedUpsampling){
cinfo->output_width = cinfo->image_width;
cinfo->output_height = cinfo->image_height;
cinfo->min_DCT_h_scaled_size = DCTSIZE;
cinfo->min_DCT_v_scaled_size = DCTSIZE;
} else {
jpeg_calc_output_dimensions(cinfo);
prepare_range_limit_table(cinfo);
}
/* Width of an output scanline must be representable as JDIMENSION. */
samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
jd_samplesperrow = (JDIMENSION) samplesperrow;
if ((long) jd_samplesperrow != samplesperrow)
ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
/* Initialize my private state */
master->pass_number = 0;
master->using_merged_upsample = use_merged_upsample(cinfo);
/* Color quantizer selection */
master->quantizer_1pass = NULL;
master->quantizer_2pass = NULL;
/* No mode changes if not using buffered-image mode. */
if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
cinfo->enable_1pass_quant = FALSE;
cinfo->enable_external_quant = FALSE;
cinfo->enable_2pass_quant = FALSE;
}
if (cinfo->quantize_colors) {
if (cinfo->raw_data_out)
ERREXIT(cinfo, JERR_NOTIMPL);
/* 2-pass quantizer only works in 3-component color space. */
if (cinfo->out_color_components != 3) {
cinfo->enable_1pass_quant = TRUE;
cinfo->enable_external_quant = FALSE;
cinfo->enable_2pass_quant = FALSE;
cinfo->colormap = NULL;
} else if (cinfo->colormap != NULL) {
cinfo->enable_external_quant = TRUE;
} else if (cinfo->two_pass_quantize) {
cinfo->enable_2pass_quant = TRUE;
} else {
cinfo->enable_1pass_quant = TRUE;
}
if (cinfo->enable_1pass_quant) {
#ifdef QUANT_1PASS_SUPPORTED
jinit_1pass_quantizer(cinfo);
master->quantizer_1pass = cinfo->cquantize;
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif
}
/* We use the 2-pass code to map to external colormaps. */
if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
#ifdef QUANT_2PASS_SUPPORTED
jinit_2pass_quantizer(cinfo);
master->quantizer_2pass = cinfo->cquantize;
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif
}
/* If both quantizers are initialized, the 2-pass one is left active;
* this is necessary for starting with quantization to an external map.
*/
}
/* Post-processing: in particular, color conversion first */
if (! cinfo->raw_data_out) {
if (master->using_merged_upsample) {
#ifdef UPSAMPLE_MERGING_SUPPORTED
jinit_merged_upsampler(cinfo); /* does color conversion too */
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif
} else {
jinit_color_deconverter(cinfo);
jinit_upsampler(cinfo);
}
jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
}
/* Inverse DCT */
jinit_inverse_dct(cinfo);
/* Entropy decoding: either Huffman or arithmetic coding. */
if (cinfo->arith_code) {
jinit_arith_decoder(cinfo);
} else {
jinit_huff_decoder(cinfo);
}
/* Initialize principal buffer controllers. */
use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
jinit_d_coef_controller(cinfo, use_c_buffer);
if (! cinfo->raw_data_out)
jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
/* We can now tell the memory manager to allocate virtual arrays. */
(*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
/* Initialize input side of decompressor to consume first scan. */
(*cinfo->inputctl->start_input_pass) (cinfo);
#ifdef D_MULTISCAN_FILES_SUPPORTED
/* If jpeg_start_decompress will read the whole file, initialize
* progress monitoring appropriately. The input step is counted
* as one pass.
*/
if (cinfo->progress != NULL && ! cinfo->buffered_image &&
cinfo->inputctl->has_multiple_scans) {
int nscans;
/* Estimate number of scans to set pass_limit. */
if (cinfo->progressive_mode) {
/* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
nscans = 2 + 3 * cinfo->num_components;
} else {
/* For a nonprogressive multiscan file, estimate 1 scan per component. */
nscans = cinfo->num_components;
}
cinfo->progress->pass_counter = 0L;
cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
cinfo->progress->completed_passes = 0;
cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
/* Count the input pass as done */
master->pass_number++;
}
#endif /* D_MULTISCAN_FILES_SUPPORTED */
}
/*
* Per-pass setup.
* This is called at the beginning of each output pass. We determine which
* modules will be active during this pass and give them appropriate
* start_pass calls. We also set is_dummy_pass to indicate whether this
* is a "real" output pass or a dummy pass for color quantization.
* (In the latter case, jdapistd.c will crank the pass to completion.)
*/
METHODDEF(void)
prepare_for_output_pass (j_decompress_ptr cinfo)
{
my_master_ptr master = (my_master_ptr) cinfo->master;
if (master->pub.is_dummy_pass) {
#ifdef QUANT_2PASS_SUPPORTED
/* Final pass of 2-pass quantization */
master->pub.is_dummy_pass = FALSE;
(*cinfo->cquantize->start_pass) (cinfo, FALSE);
(*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
(*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif /* QUANT_2PASS_SUPPORTED */
} else {
if (cinfo->quantize_colors && cinfo->colormap == NULL) {
/* Select new quantization method */
if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
cinfo->cquantize = master->quantizer_2pass;
master->pub.is_dummy_pass = TRUE;
} else if (cinfo->enable_1pass_quant) {
cinfo->cquantize = master->quantizer_1pass;
} else {
ERREXIT(cinfo, JERR_MODE_CHANGE);
}
}
(*cinfo->idct->start_pass) (cinfo);
(*cinfo->coef->start_output_pass) (cinfo);
if (! cinfo->raw_data_out) {
if (! master->using_merged_upsample)
(*cinfo->cconvert->start_pass) (cinfo);
(*cinfo->upsample->start_pass) (cinfo);
if (cinfo->quantize_colors)
(*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
(*cinfo->post->start_pass) (cinfo,
(master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
(*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
}
}
/* Set up progress monitor's pass info if present */
if (cinfo->progress != NULL) {
cinfo->progress->completed_passes = master->pass_number;
cinfo->progress->total_passes = master->pass_number +
(master->pub.is_dummy_pass ? 2 : 1);
/* In buffered-image mode, we assume one more output pass if EOI not
* yet reached, but no more passes if EOI has been reached.
*/
if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
}
}
}
/*
* Finish up at end of an output pass.
*/
METHODDEF(void)
finish_output_pass (j_decompress_ptr cinfo)
{
my_master_ptr master = (my_master_ptr) cinfo->master;
if (cinfo->quantize_colors)
(*cinfo->cquantize->finish_pass) (cinfo);
master->pass_number++;
}
#ifdef D_MULTISCAN_FILES_SUPPORTED
/*
* Switch to a new external colormap between output passes.
*/
GLOBAL(void)
jpeg_new_colormap (j_decompress_ptr cinfo)
{
my_master_ptr master = (my_master_ptr) cinfo->master;
/* Prevent application from calling me at wrong times */
if (cinfo->global_state != DSTATE_BUFIMAGE)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
if (cinfo->quantize_colors && cinfo->enable_external_quant &&
cinfo->colormap != NULL) {
/* Select 2-pass quantizer for external colormap use */
cinfo->cquantize = master->quantizer_2pass;
/* Notify quantizer of colormap change */
(*cinfo->cquantize->new_color_map) (cinfo);
master->pub.is_dummy_pass = FALSE; /* just in case */
} else
ERREXIT(cinfo, JERR_MODE_CHANGE);
}
#endif /* D_MULTISCAN_FILES_SUPPORTED */
/*
* Initialize master decompression control and select active modules.
* This is performed at the start of jpeg_start_decompress.
*/
GLOBAL(void)
jinit_master_decompress (j_decompress_ptr cinfo)
{
my_master_ptr master;
master = (my_master_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(my_decomp_master));
cinfo->master = (struct jpeg_decomp_master *) master;
master->pub.prepare_for_output_pass = prepare_for_output_pass;
master->pub.finish_output_pass = finish_output_pass;
master->pub.is_dummy_pass = FALSE;
master_selection(cinfo);
}
|
1137519-player
|
jpeg-7/jdmaster.c
|
C
|
lgpl
| 27,075
|
/*
* jdmarker.c
*
* Copyright (C) 1991-1998, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains routines to decode JPEG datastream markers.
* Most of the complexity arises from our desire to support input
* suspension: if not all of the data for a marker is available,
* we must exit back to the application. On resumption, we reprocess
* the marker.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
typedef enum { /* JPEG marker codes */
M_SOF0 = 0xc0,
M_SOF1 = 0xc1,
M_SOF2 = 0xc2,
M_SOF3 = 0xc3,
M_SOF5 = 0xc5,
M_SOF6 = 0xc6,
M_SOF7 = 0xc7,
M_JPG = 0xc8,
M_SOF9 = 0xc9,
M_SOF10 = 0xca,
M_SOF11 = 0xcb,
M_SOF13 = 0xcd,
M_SOF14 = 0xce,
M_SOF15 = 0xcf,
M_DHT = 0xc4,
M_DAC = 0xcc,
M_RST0 = 0xd0,
M_RST1 = 0xd1,
M_RST2 = 0xd2,
M_RST3 = 0xd3,
M_RST4 = 0xd4,
M_RST5 = 0xd5,
M_RST6 = 0xd6,
M_RST7 = 0xd7,
M_SOI = 0xd8,
M_EOI = 0xd9,
M_SOS = 0xda,
M_DQT = 0xdb,
M_DNL = 0xdc,
M_DRI = 0xdd,
M_DHP = 0xde,
M_EXP = 0xdf,
M_APP0 = 0xe0,
M_APP1 = 0xe1,
M_APP2 = 0xe2,
M_APP3 = 0xe3,
M_APP4 = 0xe4,
M_APP5 = 0xe5,
M_APP6 = 0xe6,
M_APP7 = 0xe7,
M_APP8 = 0xe8,
M_APP9 = 0xe9,
M_APP10 = 0xea,
M_APP11 = 0xeb,
M_APP12 = 0xec,
M_APP13 = 0xed,
M_APP14 = 0xee,
M_APP15 = 0xef,
M_JPG0 = 0xf0,
M_JPG13 = 0xfd,
M_COM = 0xfe,
M_TEM = 0x01,
M_ERROR = 0x100
} JPEG_MARKER;
/* Private state */
typedef struct {
struct jpeg_marker_reader pub; /* public fields */
/* Application-overridable marker processing methods */
jpeg_marker_parser_method process_COM;
jpeg_marker_parser_method process_APPn[16];
/* Limit on marker data length to save for each marker type */
unsigned int length_limit_COM;
unsigned int length_limit_APPn[16];
/* Status of COM/APPn marker saving */
jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
unsigned int bytes_read; /* data bytes read so far in marker */
/* Note: cur_marker is not linked into marker_list until it's all read. */
} my_marker_reader;
typedef my_marker_reader * my_marker_ptr;
/*
* Macros for fetching data from the data source module.
*
* At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
* the current restart point; we update them only when we have reached a
* suitable place to restart if a suspension occurs.
*/
/* Declare and initialize local copies of input pointer/count */
#define INPUT_VARS(cinfo) \
struct jpeg_source_mgr * datasrc = (cinfo)->src; \
const JOCTET * next_input_byte = datasrc->next_input_byte; \
size_t bytes_in_buffer = datasrc->bytes_in_buffer
/* Unload the local copies --- do this only at a restart boundary */
#define INPUT_SYNC(cinfo) \
( datasrc->next_input_byte = next_input_byte, \
datasrc->bytes_in_buffer = bytes_in_buffer )
/* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
#define INPUT_RELOAD(cinfo) \
( next_input_byte = datasrc->next_input_byte, \
bytes_in_buffer = datasrc->bytes_in_buffer )
/* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
* Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
* but we must reload the local copies after a successful fill.
*/
#define MAKE_BYTE_AVAIL(cinfo,action) \
if (bytes_in_buffer == 0) { \
if (! (*datasrc->fill_input_buffer) (cinfo)) \
{ action; } \
INPUT_RELOAD(cinfo); \
}
/* Read a byte into variable V.
* If must suspend, take the specified action (typically "return FALSE").
*/
#define INPUT_BYTE(cinfo,V,action) \
MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
bytes_in_buffer--; \
V = GETJOCTET(*next_input_byte++); )
/* As above, but read two bytes interpreted as an unsigned 16-bit integer.
* V should be declared unsigned int or perhaps INT32.
*/
#define INPUT_2BYTES(cinfo,V,action) \
MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
bytes_in_buffer--; \
V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
MAKE_BYTE_AVAIL(cinfo,action); \
bytes_in_buffer--; \
V += GETJOCTET(*next_input_byte++); )
/*
* Routines to process JPEG markers.
*
* Entry condition: JPEG marker itself has been read and its code saved
* in cinfo->unread_marker; input restart point is just after the marker.
*
* Exit: if return TRUE, have read and processed any parameters, and have
* updated the restart point to point after the parameters.
* If return FALSE, was forced to suspend before reaching end of
* marker parameters; restart point has not been moved. Same routine
* will be called again after application supplies more input data.
*
* This approach to suspension assumes that all of a marker's parameters
* can fit into a single input bufferload. This should hold for "normal"
* markers. Some COM/APPn markers might have large parameter segments
* that might not fit. If we are simply dropping such a marker, we use
* skip_input_data to get past it, and thereby put the problem on the
* source manager's shoulders. If we are saving the marker's contents
* into memory, we use a slightly different convention: when forced to
* suspend, the marker processor updates the restart point to the end of
* what it's consumed (ie, the end of the buffer) before returning FALSE.
* On resumption, cinfo->unread_marker still contains the marker code,
* but the data source will point to the next chunk of marker data.
* The marker processor must retain internal state to deal with this.
*
* Note that we don't bother to avoid duplicate trace messages if a
* suspension occurs within marker parameters. Other side effects
* require more care.
*/
LOCAL(boolean)
get_soi (j_decompress_ptr cinfo)
/* Process an SOI marker */
{
int i;
TRACEMS(cinfo, 1, JTRC_SOI);
if (cinfo->marker->saw_SOI)
ERREXIT(cinfo, JERR_SOI_DUPLICATE);
/* Reset all parameters that are defined to be reset by SOI */
for (i = 0; i < NUM_ARITH_TBLS; i++) {
cinfo->arith_dc_L[i] = 0;
cinfo->arith_dc_U[i] = 1;
cinfo->arith_ac_K[i] = 5;
}
cinfo->restart_interval = 0;
/* Set initial assumptions for colorspace etc */
cinfo->jpeg_color_space = JCS_UNKNOWN;
cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
cinfo->saw_JFIF_marker = FALSE;
cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
cinfo->JFIF_minor_version = 1;
cinfo->density_unit = 0;
cinfo->X_density = 1;
cinfo->Y_density = 1;
cinfo->saw_Adobe_marker = FALSE;
cinfo->Adobe_transform = 0;
cinfo->marker->saw_SOI = TRUE;
return TRUE;
}
LOCAL(boolean)
get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
/* Process a SOFn marker */
{
INT32 length;
int c, ci;
jpeg_component_info * compptr;
INPUT_VARS(cinfo);
cinfo->progressive_mode = is_prog;
cinfo->arith_code = is_arith;
INPUT_2BYTES(cinfo, length, return FALSE);
INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
length -= 8;
TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
(int) cinfo->image_width, (int) cinfo->image_height,
cinfo->num_components);
if (cinfo->marker->saw_SOF)
ERREXIT(cinfo, JERR_SOF_DUPLICATE);
/* We don't support files in which the image height is initially specified */
/* as 0 and is later redefined by DNL. As long as we have to check that, */
/* might as well have a general sanity check. */
if (cinfo->image_height <= 0 || cinfo->image_width <= 0
|| cinfo->num_components <= 0)
ERREXIT(cinfo, JERR_EMPTY_IMAGE);
if (length != (cinfo->num_components * 3))
ERREXIT(cinfo, JERR_BAD_LENGTH);
if (cinfo->comp_info == NULL) /* do only once, even if suspend */
cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo, JPOOL_IMAGE,
cinfo->num_components * SIZEOF(jpeg_component_info));
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
compptr->component_index = ci;
INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
INPUT_BYTE(cinfo, c, return FALSE);
compptr->h_samp_factor = (c >> 4) & 15;
compptr->v_samp_factor = (c ) & 15;
INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
compptr->component_id, compptr->h_samp_factor,
compptr->v_samp_factor, compptr->quant_tbl_no);
}
cinfo->marker->saw_SOF = TRUE;
INPUT_SYNC(cinfo);
return TRUE;
}
LOCAL(boolean)
get_sos (j_decompress_ptr cinfo)
/* Process a SOS marker */
{
INT32 length;
int i, ci, n, c, cc;
jpeg_component_info * compptr;
INPUT_VARS(cinfo);
if (! cinfo->marker->saw_SOF)
ERREXIT(cinfo, JERR_SOS_NO_SOF);
INPUT_2BYTES(cinfo, length, return FALSE);
INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
TRACEMS1(cinfo, 1, JTRC_SOS, n);
if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
ERREXIT(cinfo, JERR_BAD_LENGTH);
cinfo->comps_in_scan = n;
/* Collect the component-spec parameters */
for (i = 0; i < n; i++) {
INPUT_BYTE(cinfo, cc, return FALSE);
INPUT_BYTE(cinfo, c, return FALSE);
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
if (cc == compptr->component_id)
goto id_found;
}
ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
id_found:
cinfo->cur_comp_info[i] = compptr;
compptr->dc_tbl_no = (c >> 4) & 15;
compptr->ac_tbl_no = (c ) & 15;
TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
compptr->dc_tbl_no, compptr->ac_tbl_no);
}
/* Collect the additional scan parameters Ss, Se, Ah/Al. */
INPUT_BYTE(cinfo, c, return FALSE);
cinfo->Ss = c;
INPUT_BYTE(cinfo, c, return FALSE);
cinfo->Se = c;
INPUT_BYTE(cinfo, c, return FALSE);
cinfo->Ah = (c >> 4) & 15;
cinfo->Al = (c ) & 15;
TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
cinfo->Ah, cinfo->Al);
/* Prepare to scan data & restart markers */
cinfo->marker->next_restart_num = 0;
/* Count another SOS marker */
cinfo->input_scan_number++;
INPUT_SYNC(cinfo);
return TRUE;
}
#ifdef D_ARITH_CODING_SUPPORTED
LOCAL(boolean)
get_dac (j_decompress_ptr cinfo)
/* Process a DAC marker */
{
INT32 length;
int index, val;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
while (length > 0) {
INPUT_BYTE(cinfo, index, return FALSE);
INPUT_BYTE(cinfo, val, return FALSE);
length -= 2;
TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
if (index < 0 || index >= (2*NUM_ARITH_TBLS))
ERREXIT1(cinfo, JERR_DAC_INDEX, index);
if (index >= NUM_ARITH_TBLS) { /* define AC table */
cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
} else { /* define DC table */
cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
ERREXIT1(cinfo, JERR_DAC_VALUE, val);
}
}
if (length != 0)
ERREXIT(cinfo, JERR_BAD_LENGTH);
INPUT_SYNC(cinfo);
return TRUE;
}
#else /* ! D_ARITH_CODING_SUPPORTED */
#define get_dac(cinfo) skip_variable(cinfo)
#endif /* D_ARITH_CODING_SUPPORTED */
LOCAL(boolean)
get_dht (j_decompress_ptr cinfo)
/* Process a DHT marker */
{
INT32 length;
UINT8 bits[17];
UINT8 huffval[256];
int i, index, count;
JHUFF_TBL **htblptr;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
while (length > 16) {
INPUT_BYTE(cinfo, index, return FALSE);
TRACEMS1(cinfo, 1, JTRC_DHT, index);
bits[0] = 0;
count = 0;
for (i = 1; i <= 16; i++) {
INPUT_BYTE(cinfo, bits[i], return FALSE);
count += bits[i];
}
length -= 1 + 16;
TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
bits[1], bits[2], bits[3], bits[4],
bits[5], bits[6], bits[7], bits[8]);
TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
bits[9], bits[10], bits[11], bits[12],
bits[13], bits[14], bits[15], bits[16]);
/* Here we just do minimal validation of the counts to avoid walking
* off the end of our table space. jdhuff.c will check more carefully.
*/
if (count > 256 || ((INT32) count) > length)
ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
for (i = 0; i < count; i++)
INPUT_BYTE(cinfo, huffval[i], return FALSE);
length -= count;
if (index & 0x10) { /* AC table definition */
index -= 0x10;
htblptr = &cinfo->ac_huff_tbl_ptrs[index];
} else { /* DC table definition */
htblptr = &cinfo->dc_huff_tbl_ptrs[index];
}
if (index < 0 || index >= NUM_HUFF_TBLS)
ERREXIT1(cinfo, JERR_DHT_INDEX, index);
if (*htblptr == NULL)
*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
}
if (length != 0)
ERREXIT(cinfo, JERR_BAD_LENGTH);
INPUT_SYNC(cinfo);
return TRUE;
}
LOCAL(boolean)
get_dqt (j_decompress_ptr cinfo)
/* Process a DQT marker */
{
INT32 length;
int n, i, prec;
unsigned int tmp;
JQUANT_TBL *quant_ptr;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
while (length > 0) {
INPUT_BYTE(cinfo, n, return FALSE);
prec = n >> 4;
n &= 0x0F;
TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
if (n >= NUM_QUANT_TBLS)
ERREXIT1(cinfo, JERR_DQT_INDEX, n);
if (cinfo->quant_tbl_ptrs[n] == NULL)
cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
quant_ptr = cinfo->quant_tbl_ptrs[n];
for (i = 0; i < DCTSIZE2; i++) {
if (prec)
INPUT_2BYTES(cinfo, tmp, return FALSE);
else
INPUT_BYTE(cinfo, tmp, return FALSE);
/* We convert the zigzag-order table to natural array order. */
quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
}
if (cinfo->err->trace_level >= 2) {
for (i = 0; i < DCTSIZE2; i += 8) {
TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
quant_ptr->quantval[i], quant_ptr->quantval[i+1],
quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
}
}
length -= DCTSIZE2+1;
if (prec) length -= DCTSIZE2;
}
if (length != 0)
ERREXIT(cinfo, JERR_BAD_LENGTH);
INPUT_SYNC(cinfo);
return TRUE;
}
LOCAL(boolean)
get_dri (j_decompress_ptr cinfo)
/* Process a DRI marker */
{
INT32 length;
unsigned int tmp;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
if (length != 4)
ERREXIT(cinfo, JERR_BAD_LENGTH);
INPUT_2BYTES(cinfo, tmp, return FALSE);
TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
cinfo->restart_interval = tmp;
INPUT_SYNC(cinfo);
return TRUE;
}
/*
* Routines for processing APPn and COM markers.
* These are either saved in memory or discarded, per application request.
* APP0 and APP14 are specially checked to see if they are
* JFIF and Adobe markers, respectively.
*/
#define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
#define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
#define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
LOCAL(void)
examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
unsigned int datalen, INT32 remaining)
/* Examine first few bytes from an APP0.
* Take appropriate action if it is a JFIF marker.
* datalen is # of bytes at data[], remaining is length of rest of marker data.
*/
{
INT32 totallen = (INT32) datalen + remaining;
if (datalen >= APP0_DATA_LEN &&
GETJOCTET(data[0]) == 0x4A &&
GETJOCTET(data[1]) == 0x46 &&
GETJOCTET(data[2]) == 0x49 &&
GETJOCTET(data[3]) == 0x46 &&
GETJOCTET(data[4]) == 0) {
/* Found JFIF APP0 marker: save info */
cinfo->saw_JFIF_marker = TRUE;
cinfo->JFIF_major_version = GETJOCTET(data[5]);
cinfo->JFIF_minor_version = GETJOCTET(data[6]);
cinfo->density_unit = GETJOCTET(data[7]);
cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
/* Check version.
* Major version must be 1, anything else signals an incompatible change.
* (We used to treat this as an error, but now it's a nonfatal warning,
* because some bozo at Hijaak couldn't read the spec.)
* Minor version should be 0..2, but process anyway if newer.
*/
if (cinfo->JFIF_major_version != 1)
WARNMS2(cinfo, JWRN_JFIF_MAJOR,
cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
/* Generate trace messages */
TRACEMS5(cinfo, 1, JTRC_JFIF,
cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
/* Validate thumbnail dimensions and issue appropriate messages */
if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
GETJOCTET(data[12]), GETJOCTET(data[13]));
totallen -= APP0_DATA_LEN;
if (totallen !=
((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
} else if (datalen >= 6 &&
GETJOCTET(data[0]) == 0x4A &&
GETJOCTET(data[1]) == 0x46 &&
GETJOCTET(data[2]) == 0x58 &&
GETJOCTET(data[3]) == 0x58 &&
GETJOCTET(data[4]) == 0) {
/* Found JFIF "JFXX" extension APP0 marker */
/* The library doesn't actually do anything with these,
* but we try to produce a helpful trace message.
*/
switch (GETJOCTET(data[5])) {
case 0x10:
TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
break;
case 0x11:
TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
break;
case 0x13:
TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
break;
default:
TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
GETJOCTET(data[5]), (int) totallen);
break;
}
} else {
/* Start of APP0 does not match "JFIF" or "JFXX", or too short */
TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
}
}
LOCAL(void)
examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
unsigned int datalen, INT32 remaining)
/* Examine first few bytes from an APP14.
* Take appropriate action if it is an Adobe marker.
* datalen is # of bytes at data[], remaining is length of rest of marker data.
*/
{
unsigned int version, flags0, flags1, transform;
if (datalen >= APP14_DATA_LEN &&
GETJOCTET(data[0]) == 0x41 &&
GETJOCTET(data[1]) == 0x64 &&
GETJOCTET(data[2]) == 0x6F &&
GETJOCTET(data[3]) == 0x62 &&
GETJOCTET(data[4]) == 0x65) {
/* Found Adobe APP14 marker */
version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
transform = GETJOCTET(data[11]);
TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
cinfo->saw_Adobe_marker = TRUE;
cinfo->Adobe_transform = (UINT8) transform;
} else {
/* Start of APP14 does not match "Adobe", or too short */
TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
}
}
METHODDEF(boolean)
get_interesting_appn (j_decompress_ptr cinfo)
/* Process an APP0 or APP14 marker without saving it */
{
INT32 length;
JOCTET b[APPN_DATA_LEN];
unsigned int i, numtoread;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
/* get the interesting part of the marker data */
if (length >= APPN_DATA_LEN)
numtoread = APPN_DATA_LEN;
else if (length > 0)
numtoread = (unsigned int) length;
else
numtoread = 0;
for (i = 0; i < numtoread; i++)
INPUT_BYTE(cinfo, b[i], return FALSE);
length -= numtoread;
/* process it */
switch (cinfo->unread_marker) {
case M_APP0:
examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
break;
case M_APP14:
examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
break;
default:
/* can't get here unless jpeg_save_markers chooses wrong processor */
ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
break;
}
/* skip any remaining data -- could be lots */
INPUT_SYNC(cinfo);
if (length > 0)
(*cinfo->src->skip_input_data) (cinfo, (long) length);
return TRUE;
}
#ifdef SAVE_MARKERS_SUPPORTED
METHODDEF(boolean)
save_marker (j_decompress_ptr cinfo)
/* Save an APPn or COM marker into the marker list */
{
my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
unsigned int bytes_read, data_length;
JOCTET FAR * data;
INT32 length = 0;
INPUT_VARS(cinfo);
if (cur_marker == NULL) {
/* begin reading a marker */
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
if (length >= 0) { /* watch out for bogus length word */
/* figure out how much we want to save */
unsigned int limit;
if (cinfo->unread_marker == (int) M_COM)
limit = marker->length_limit_COM;
else
limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
if ((unsigned int) length < limit)
limit = (unsigned int) length;
/* allocate and initialize the marker item */
cur_marker = (jpeg_saved_marker_ptr)
(*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(struct jpeg_marker_struct) + limit);
cur_marker->next = NULL;
cur_marker->marker = (UINT8) cinfo->unread_marker;
cur_marker->original_length = (unsigned int) length;
cur_marker->data_length = limit;
/* data area is just beyond the jpeg_marker_struct */
data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
marker->cur_marker = cur_marker;
marker->bytes_read = 0;
bytes_read = 0;
data_length = limit;
} else {
/* deal with bogus length word */
bytes_read = data_length = 0;
data = NULL;
}
} else {
/* resume reading a marker */
bytes_read = marker->bytes_read;
data_length = cur_marker->data_length;
data = cur_marker->data + bytes_read;
}
while (bytes_read < data_length) {
INPUT_SYNC(cinfo); /* move the restart point to here */
marker->bytes_read = bytes_read;
/* If there's not at least one byte in buffer, suspend */
MAKE_BYTE_AVAIL(cinfo, return FALSE);
/* Copy bytes with reasonable rapidity */
while (bytes_read < data_length && bytes_in_buffer > 0) {
*data++ = *next_input_byte++;
bytes_in_buffer--;
bytes_read++;
}
}
/* Done reading what we want to read */
if (cur_marker != NULL) { /* will be NULL if bogus length word */
/* Add new marker to end of list */
if (cinfo->marker_list == NULL) {
cinfo->marker_list = cur_marker;
} else {
jpeg_saved_marker_ptr prev = cinfo->marker_list;
while (prev->next != NULL)
prev = prev->next;
prev->next = cur_marker;
}
/* Reset pointer & calc remaining data length */
data = cur_marker->data;
length = cur_marker->original_length - data_length;
}
/* Reset to initial state for next marker */
marker->cur_marker = NULL;
/* Process the marker if interesting; else just make a generic trace msg */
switch (cinfo->unread_marker) {
case M_APP0:
examine_app0(cinfo, data, data_length, length);
break;
case M_APP14:
examine_app14(cinfo, data, data_length, length);
break;
default:
TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
(int) (data_length + length));
break;
}
/* skip any remaining data -- could be lots */
INPUT_SYNC(cinfo); /* do before skip_input_data */
if (length > 0)
(*cinfo->src->skip_input_data) (cinfo, (long) length);
return TRUE;
}
#endif /* SAVE_MARKERS_SUPPORTED */
METHODDEF(boolean)
skip_variable (j_decompress_ptr cinfo)
/* Skip over an unknown or uninteresting variable-length marker */
{
INT32 length;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
INPUT_SYNC(cinfo); /* do before skip_input_data */
if (length > 0)
(*cinfo->src->skip_input_data) (cinfo, (long) length);
return TRUE;
}
/*
* Find the next JPEG marker, save it in cinfo->unread_marker.
* Returns FALSE if had to suspend before reaching a marker;
* in that case cinfo->unread_marker is unchanged.
*
* Note that the result might not be a valid marker code,
* but it will never be 0 or FF.
*/
LOCAL(boolean)
next_marker (j_decompress_ptr cinfo)
{
int c;
INPUT_VARS(cinfo);
for (;;) {
INPUT_BYTE(cinfo, c, return FALSE);
/* Skip any non-FF bytes.
* This may look a bit inefficient, but it will not occur in a valid file.
* We sync after each discarded byte so that a suspending data source
* can discard the byte from its buffer.
*/
while (c != 0xFF) {
cinfo->marker->discarded_bytes++;
INPUT_SYNC(cinfo);
INPUT_BYTE(cinfo, c, return FALSE);
}
/* This loop swallows any duplicate FF bytes. Extra FFs are legal as
* pad bytes, so don't count them in discarded_bytes. We assume there
* will not be so many consecutive FF bytes as to overflow a suspending
* data source's input buffer.
*/
do {
INPUT_BYTE(cinfo, c, return FALSE);
} while (c == 0xFF);
if (c != 0)
break; /* found a valid marker, exit loop */
/* Reach here if we found a stuffed-zero data sequence (FF/00).
* Discard it and loop back to try again.
*/
cinfo->marker->discarded_bytes += 2;
INPUT_SYNC(cinfo);
}
if (cinfo->marker->discarded_bytes != 0) {
WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
cinfo->marker->discarded_bytes = 0;
}
cinfo->unread_marker = c;
INPUT_SYNC(cinfo);
return TRUE;
}
LOCAL(boolean)
first_marker (j_decompress_ptr cinfo)
/* Like next_marker, but used to obtain the initial SOI marker. */
/* For this marker, we do not allow preceding garbage or fill; otherwise,
* we might well scan an entire input file before realizing it ain't JPEG.
* If an application wants to process non-JFIF files, it must seek to the
* SOI before calling the JPEG library.
*/
{
int c, c2;
INPUT_VARS(cinfo);
INPUT_BYTE(cinfo, c, return FALSE);
INPUT_BYTE(cinfo, c2, return FALSE);
if (c != 0xFF || c2 != (int) M_SOI)
ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
cinfo->unread_marker = c2;
INPUT_SYNC(cinfo);
return TRUE;
}
/*
* Read markers until SOS or EOI.
*
* Returns same codes as are defined for jpeg_consume_input:
* JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
*/
METHODDEF(int)
read_markers (j_decompress_ptr cinfo)
{
/* Outer loop repeats once for each marker. */
for (;;) {
/* Collect the marker proper, unless we already did. */
/* NB: first_marker() enforces the requirement that SOI appear first. */
if (cinfo->unread_marker == 0) {
if (! cinfo->marker->saw_SOI) {
if (! first_marker(cinfo))
return JPEG_SUSPENDED;
} else {
if (! next_marker(cinfo))
return JPEG_SUSPENDED;
}
}
/* At this point cinfo->unread_marker contains the marker code and the
* input point is just past the marker proper, but before any parameters.
* A suspension will cause us to return with this state still true.
*/
switch (cinfo->unread_marker) {
case M_SOI:
if (! get_soi(cinfo))
return JPEG_SUSPENDED;
break;
case M_SOF0: /* Baseline */
case M_SOF1: /* Extended sequential, Huffman */
if (! get_sof(cinfo, FALSE, FALSE))
return JPEG_SUSPENDED;
break;
case M_SOF2: /* Progressive, Huffman */
if (! get_sof(cinfo, TRUE, FALSE))
return JPEG_SUSPENDED;
break;
case M_SOF9: /* Extended sequential, arithmetic */
if (! get_sof(cinfo, FALSE, TRUE))
return JPEG_SUSPENDED;
break;
case M_SOF10: /* Progressive, arithmetic */
if (! get_sof(cinfo, TRUE, TRUE))
return JPEG_SUSPENDED;
break;
/* Currently unsupported SOFn types */
case M_SOF3: /* Lossless, Huffman */
case M_SOF5: /* Differential sequential, Huffman */
case M_SOF6: /* Differential progressive, Huffman */
case M_SOF7: /* Differential lossless, Huffman */
case M_JPG: /* Reserved for JPEG extensions */
case M_SOF11: /* Lossless, arithmetic */
case M_SOF13: /* Differential sequential, arithmetic */
case M_SOF14: /* Differential progressive, arithmetic */
case M_SOF15: /* Differential lossless, arithmetic */
ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
break;
case M_SOS:
if (! get_sos(cinfo))
return JPEG_SUSPENDED;
cinfo->unread_marker = 0; /* processed the marker */
return JPEG_REACHED_SOS;
case M_EOI:
TRACEMS(cinfo, 1, JTRC_EOI);
cinfo->unread_marker = 0; /* processed the marker */
return JPEG_REACHED_EOI;
case M_DAC:
if (! get_dac(cinfo))
return JPEG_SUSPENDED;
break;
case M_DHT:
if (! get_dht(cinfo))
return JPEG_SUSPENDED;
break;
case M_DQT:
if (! get_dqt(cinfo))
return JPEG_SUSPENDED;
break;
case M_DRI:
if (! get_dri(cinfo))
return JPEG_SUSPENDED;
break;
case M_APP0:
case M_APP1:
case M_APP2:
case M_APP3:
case M_APP4:
case M_APP5:
case M_APP6:
case M_APP7:
case M_APP8:
case M_APP9:
case M_APP10:
case M_APP11:
case M_APP12:
case M_APP13:
case M_APP14:
case M_APP15:
if (! (*((my_marker_ptr) cinfo->marker)->process_APPn[
cinfo->unread_marker - (int) M_APP0]) (cinfo))
return JPEG_SUSPENDED;
break;
case M_COM:
if (! (*((my_marker_ptr) cinfo->marker)->process_COM) (cinfo))
return JPEG_SUSPENDED;
break;
case M_RST0: /* these are all parameterless */
case M_RST1:
case M_RST2:
case M_RST3:
case M_RST4:
case M_RST5:
case M_RST6:
case M_RST7:
case M_TEM:
TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
break;
case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
if (! skip_variable(cinfo))
return JPEG_SUSPENDED;
break;
default: /* must be DHP, EXP, JPGn, or RESn */
/* For now, we treat the reserved markers as fatal errors since they are
* likely to be used to signal incompatible JPEG Part 3 extensions.
* Once the JPEG 3 version-number marker is well defined, this code
* ought to change!
*/
ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
break;
}
/* Successfully processed marker, so reset state variable */
cinfo->unread_marker = 0;
} /* end loop */
}
/*
* Read a restart marker, which is expected to appear next in the datastream;
* if the marker is not there, take appropriate recovery action.
* Returns FALSE if suspension is required.
*
* This is called by the entropy decoder after it has read an appropriate
* number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
* has already read a marker from the data source. Under normal conditions
* cinfo->unread_marker will be reset to 0 before returning; if not reset,
* it holds a marker which the decoder will be unable to read past.
*/
METHODDEF(boolean)
read_restart_marker (j_decompress_ptr cinfo)
{
/* Obtain a marker unless we already did. */
/* Note that next_marker will complain if it skips any data. */
if (cinfo->unread_marker == 0) {
if (! next_marker(cinfo))
return FALSE;
}
if (cinfo->unread_marker ==
((int) M_RST0 + cinfo->marker->next_restart_num)) {
/* Normal case --- swallow the marker and let entropy decoder continue */
TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
cinfo->unread_marker = 0;
} else {
/* Uh-oh, the restart markers have been messed up. */
/* Let the data source manager determine how to resync. */
if (! (*cinfo->src->resync_to_restart) (cinfo,
cinfo->marker->next_restart_num))
return FALSE;
}
/* Update next-restart state */
cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
return TRUE;
}
/*
* This is the default resync_to_restart method for data source managers
* to use if they don't have any better approach. Some data source managers
* may be able to back up, or may have additional knowledge about the data
* which permits a more intelligent recovery strategy; such managers would
* presumably supply their own resync method.
*
* read_restart_marker calls resync_to_restart if it finds a marker other than
* the restart marker it was expecting. (This code is *not* used unless
* a nonzero restart interval has been declared.) cinfo->unread_marker is
* the marker code actually found (might be anything, except 0 or FF).
* The desired restart marker number (0..7) is passed as a parameter.
* This routine is supposed to apply whatever error recovery strategy seems
* appropriate in order to position the input stream to the next data segment.
* Note that cinfo->unread_marker is treated as a marker appearing before
* the current data-source input point; usually it should be reset to zero
* before returning.
* Returns FALSE if suspension is required.
*
* This implementation is substantially constrained by wanting to treat the
* input as a data stream; this means we can't back up. Therefore, we have
* only the following actions to work with:
* 1. Simply discard the marker and let the entropy decoder resume at next
* byte of file.
* 2. Read forward until we find another marker, discarding intervening
* data. (In theory we could look ahead within the current bufferload,
* without having to discard data if we don't find the desired marker.
* This idea is not implemented here, in part because it makes behavior
* dependent on buffer size and chance buffer-boundary positions.)
* 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
* This will cause the entropy decoder to process an empty data segment,
* inserting dummy zeroes, and then we will reprocess the marker.
*
* #2 is appropriate if we think the desired marker lies ahead, while #3 is
* appropriate if the found marker is a future restart marker (indicating
* that we have missed the desired restart marker, probably because it got
* corrupted).
* We apply #2 or #3 if the found marker is a restart marker no more than
* two counts behind or ahead of the expected one. We also apply #2 if the
* found marker is not a legal JPEG marker code (it's certainly bogus data).
* If the found marker is a restart marker more than 2 counts away, we do #1
* (too much risk that the marker is erroneous; with luck we will be able to
* resync at some future point).
* For any valid non-restart JPEG marker, we apply #3. This keeps us from
* overrunning the end of a scan. An implementation limited to single-scan
* files might find it better to apply #2 for markers other than EOI, since
* any other marker would have to be bogus data in that case.
*/
GLOBAL(boolean)
jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
{
int marker = cinfo->unread_marker;
int action = 1;
/* Always put up a warning. */
WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
/* Outer loop handles repeated decision after scanning forward. */
for (;;) {
if (marker < (int) M_SOF0)
action = 2; /* invalid marker */
else if (marker < (int) M_RST0 || marker > (int) M_RST7)
action = 3; /* valid non-restart marker */
else {
if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
marker == ((int) M_RST0 + ((desired+2) & 7)))
action = 3; /* one of the next two expected restarts */
else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
marker == ((int) M_RST0 + ((desired-2) & 7)))
action = 2; /* a prior restart, so advance */
else
action = 1; /* desired restart or too far away */
}
TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
switch (action) {
case 1:
/* Discard marker and let entropy decoder resume processing. */
cinfo->unread_marker = 0;
return TRUE;
case 2:
/* Scan to the next marker, and repeat the decision loop. */
if (! next_marker(cinfo))
return FALSE;
marker = cinfo->unread_marker;
break;
case 3:
/* Return without advancing past this marker. */
/* Entropy decoder will be forced to process an empty segment. */
return TRUE;
}
} /* end loop */
}
/*
* Reset marker processing state to begin a fresh datastream.
*/
METHODDEF(void)
reset_marker_reader (j_decompress_ptr cinfo)
{
my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
cinfo->comp_info = NULL; /* until allocated by get_sof */
cinfo->input_scan_number = 0; /* no SOS seen yet */
cinfo->unread_marker = 0; /* no pending marker */
marker->pub.saw_SOI = FALSE; /* set internal state too */
marker->pub.saw_SOF = FALSE;
marker->pub.discarded_bytes = 0;
marker->cur_marker = NULL;
}
/*
* Initialize the marker reader module.
* This is called only once, when the decompression object is created.
*/
GLOBAL(void)
jinit_marker_reader (j_decompress_ptr cinfo)
{
my_marker_ptr marker;
int i;
/* Create subobject in permanent pool */
marker = (my_marker_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
SIZEOF(my_marker_reader));
cinfo->marker = (struct jpeg_marker_reader *) marker;
/* Initialize public method pointers */
marker->pub.reset_marker_reader = reset_marker_reader;
marker->pub.read_markers = read_markers;
marker->pub.read_restart_marker = read_restart_marker;
/* Initialize COM/APPn processing.
* By default, we examine and then discard APP0 and APP14,
* but simply discard COM and all other APPn.
*/
marker->process_COM = skip_variable;
marker->length_limit_COM = 0;
for (i = 0; i < 16; i++) {
marker->process_APPn[i] = skip_variable;
marker->length_limit_APPn[i] = 0;
}
marker->process_APPn[0] = get_interesting_appn;
marker->process_APPn[14] = get_interesting_appn;
/* Reset marker processing state */
reset_marker_reader(cinfo);
}
/*
* Control saving of COM and APPn markers into marker_list.
*/
#ifdef SAVE_MARKERS_SUPPORTED
GLOBAL(void)
jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
unsigned int length_limit)
{
my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
long maxlength;
jpeg_marker_parser_method processor;
/* Length limit mustn't be larger than what we can allocate
* (should only be a concern in a 16-bit environment).
*/
maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
if (((long) length_limit) > maxlength)
length_limit = (unsigned int) maxlength;
/* Choose processor routine to use.
* APP0/APP14 have special requirements.
*/
if (length_limit) {
processor = save_marker;
/* If saving APP0/APP14, save at least enough for our internal use. */
if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
length_limit = APP0_DATA_LEN;
else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
length_limit = APP14_DATA_LEN;
} else {
processor = skip_variable;
/* If discarding APP0/APP14, use our regular on-the-fly processor. */
if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
processor = get_interesting_appn;
}
if (marker_code == (int) M_COM) {
marker->process_COM = processor;
marker->length_limit_COM = length_limit;
} else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
marker->process_APPn[marker_code - (int) M_APP0] = processor;
marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
} else
ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
}
#endif /* SAVE_MARKERS_SUPPORTED */
/*
* Install a special processing method for COM or APPn markers.
*/
GLOBAL(void)
jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
jpeg_marker_parser_method routine)
{
my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
if (marker_code == (int) M_COM)
marker->process_COM = routine;
else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
marker->process_APPn[marker_code - (int) M_APP0] = routine;
else
ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
}
|
1137519-player
|
jpeg-7/jdmarker.c
|
C
|
lgpl
| 41,118
|
/*
* wrgif.c
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains routines to write output images in GIF format.
*
**************************************************************************
* NOTE: to avoid entanglements with Unisys' patent on LZW compression, *
* this code has been modified to output "uncompressed GIF" files. *
* There is no trace of the LZW algorithm in this file. *
**************************************************************************
*
* These routines may need modification for non-Unix environments or
* specialized applications. As they stand, they assume output to
* an ordinary stdio stream.
*/
/*
* This code is loosely based on ppmtogif from the PBMPLUS distribution
* of Feb. 1991. That file contains the following copyright notice:
* Based on GIFENCODE by David Rowley <mgardi@watdscu.waterloo.edu>.
* Lempel-Ziv compression based on "compress" by Spencer W. Thomas et al.
* Copyright (C) 1989 by Jef Poskanzer.
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation. This software is provided "as is" without express or
* implied warranty.
*
* We are also required to state that
* "The Graphics Interchange Format(c) is the Copyright property of
* CompuServe Incorporated. GIF(sm) is a Service Mark property of
* CompuServe Incorporated."
*/
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#ifdef GIF_SUPPORTED
/* Private version of data destination object */
typedef struct {
struct djpeg_dest_struct pub; /* public fields */
j_decompress_ptr cinfo; /* back link saves passing separate parm */
/* State for packing variable-width codes into a bitstream */
int n_bits; /* current number of bits/code */
int maxcode; /* maximum code, given n_bits */
INT32 cur_accum; /* holds bits not yet output */
int cur_bits; /* # of bits in cur_accum */
/* State for GIF code assignment */
int ClearCode; /* clear code (doesn't change) */
int EOFCode; /* EOF code (ditto) */
int code_counter; /* counts output symbols */
/* GIF data packet construction buffer */
int bytesinpkt; /* # of bytes in current packet */
char packetbuf[256]; /* workspace for accumulating packet */
} gif_dest_struct;
typedef gif_dest_struct * gif_dest_ptr;
/* Largest value that will fit in N bits */
#define MAXCODE(n_bits) ((1 << (n_bits)) - 1)
/*
* Routines to package finished data bytes into GIF data blocks.
* A data block consists of a count byte (1..255) and that many data bytes.
*/
LOCAL(void)
flush_packet (gif_dest_ptr dinfo)
/* flush any accumulated data */
{
if (dinfo->bytesinpkt > 0) { /* never write zero-length packet */
dinfo->packetbuf[0] = (char) dinfo->bytesinpkt++;
if (JFWRITE(dinfo->pub.output_file, dinfo->packetbuf, dinfo->bytesinpkt)
!= (size_t) dinfo->bytesinpkt)
ERREXIT(dinfo->cinfo, JERR_FILE_WRITE);
dinfo->bytesinpkt = 0;
}
}
/* Add a character to current packet; flush to disk if necessary */
#define CHAR_OUT(dinfo,c) \
{ (dinfo)->packetbuf[++(dinfo)->bytesinpkt] = (char) (c); \
if ((dinfo)->bytesinpkt >= 255) \
flush_packet(dinfo); \
}
/* Routine to convert variable-width codes into a byte stream */
LOCAL(void)
output (gif_dest_ptr dinfo, int code)
/* Emit a code of n_bits bits */
/* Uses cur_accum and cur_bits to reblock into 8-bit bytes */
{
dinfo->cur_accum |= ((INT32) code) << dinfo->cur_bits;
dinfo->cur_bits += dinfo->n_bits;
while (dinfo->cur_bits >= 8) {
CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
dinfo->cur_accum >>= 8;
dinfo->cur_bits -= 8;
}
}
/* The pseudo-compression algorithm.
*
* In this module we simply output each pixel value as a separate symbol;
* thus, no compression occurs. In fact, there is expansion of one bit per
* pixel, because we use a symbol width one bit wider than the pixel width.
*
* GIF ordinarily uses variable-width symbols, and the decoder will expect
* to ratchet up the symbol width after a fixed number of symbols.
* To simplify the logic and keep the expansion penalty down, we emit a
* GIF Clear code to reset the decoder just before the width would ratchet up.
* Thus, all the symbols in the output file will have the same bit width.
* Note that emitting the Clear codes at the right times is a mere matter of
* counting output symbols and is in no way dependent on the LZW patent.
*
* With a small basic pixel width (low color count), Clear codes will be
* needed very frequently, causing the file to expand even more. So this
* simplistic approach wouldn't work too well on bilevel images, for example.
* But for output of JPEG conversions the pixel width will usually be 8 bits
* (129 to 256 colors), so the overhead added by Clear symbols is only about
* one symbol in every 256.
*/
LOCAL(void)
compress_init (gif_dest_ptr dinfo, int i_bits)
/* Initialize pseudo-compressor */
{
/* init all the state variables */
dinfo->n_bits = i_bits;
dinfo->maxcode = MAXCODE(dinfo->n_bits);
dinfo->ClearCode = (1 << (i_bits - 1));
dinfo->EOFCode = dinfo->ClearCode + 1;
dinfo->code_counter = dinfo->ClearCode + 2;
/* init output buffering vars */
dinfo->bytesinpkt = 0;
dinfo->cur_accum = 0;
dinfo->cur_bits = 0;
/* GIF specifies an initial Clear code */
output(dinfo, dinfo->ClearCode);
}
LOCAL(void)
compress_pixel (gif_dest_ptr dinfo, int c)
/* Accept and "compress" one pixel value.
* The given value must be less than n_bits wide.
*/
{
/* Output the given pixel value as a symbol. */
output(dinfo, c);
/* Issue Clear codes often enough to keep the reader from ratcheting up
* its symbol size.
*/
if (dinfo->code_counter < dinfo->maxcode) {
dinfo->code_counter++;
} else {
output(dinfo, dinfo->ClearCode);
dinfo->code_counter = dinfo->ClearCode + 2; /* reset the counter */
}
}
LOCAL(void)
compress_term (gif_dest_ptr dinfo)
/* Clean up at end */
{
/* Send an EOF code */
output(dinfo, dinfo->EOFCode);
/* Flush the bit-packing buffer */
if (dinfo->cur_bits > 0) {
CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
}
/* Flush the packet buffer */
flush_packet(dinfo);
}
/* GIF header construction */
LOCAL(void)
put_word (gif_dest_ptr dinfo, unsigned int w)
/* Emit a 16-bit word, LSB first */
{
putc(w & 0xFF, dinfo->pub.output_file);
putc((w >> 8) & 0xFF, dinfo->pub.output_file);
}
LOCAL(void)
put_3bytes (gif_dest_ptr dinfo, int val)
/* Emit 3 copies of same byte value --- handy subr for colormap construction */
{
putc(val, dinfo->pub.output_file);
putc(val, dinfo->pub.output_file);
putc(val, dinfo->pub.output_file);
}
LOCAL(void)
emit_header (gif_dest_ptr dinfo, int num_colors, JSAMPARRAY colormap)
/* Output the GIF file header, including color map */
/* If colormap==NULL, synthesize a gray-scale colormap */
{
int BitsPerPixel, ColorMapSize, InitCodeSize, FlagByte;
int cshift = dinfo->cinfo->data_precision - 8;
int i;
if (num_colors > 256)
ERREXIT1(dinfo->cinfo, JERR_TOO_MANY_COLORS, num_colors);
/* Compute bits/pixel and related values */
BitsPerPixel = 1;
while (num_colors > (1 << BitsPerPixel))
BitsPerPixel++;
ColorMapSize = 1 << BitsPerPixel;
if (BitsPerPixel <= 1)
InitCodeSize = 2;
else
InitCodeSize = BitsPerPixel;
/*
* Write the GIF header.
* Note that we generate a plain GIF87 header for maximum compatibility.
*/
putc('G', dinfo->pub.output_file);
putc('I', dinfo->pub.output_file);
putc('F', dinfo->pub.output_file);
putc('8', dinfo->pub.output_file);
putc('7', dinfo->pub.output_file);
putc('a', dinfo->pub.output_file);
/* Write the Logical Screen Descriptor */
put_word(dinfo, (unsigned int) dinfo->cinfo->output_width);
put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
FlagByte = 0x80; /* Yes, there is a global color table */
FlagByte |= (BitsPerPixel-1) << 4; /* color resolution */
FlagByte |= (BitsPerPixel-1); /* size of global color table */
putc(FlagByte, dinfo->pub.output_file);
putc(0, dinfo->pub.output_file); /* Background color index */
putc(0, dinfo->pub.output_file); /* Reserved (aspect ratio in GIF89) */
/* Write the Global Color Map */
/* If the color map is more than 8 bits precision, */
/* we reduce it to 8 bits by shifting */
for (i=0; i < ColorMapSize; i++) {
if (i < num_colors) {
if (colormap != NULL) {
if (dinfo->cinfo->out_color_space == JCS_RGB) {
/* Normal case: RGB color map */
putc(GETJSAMPLE(colormap[0][i]) >> cshift, dinfo->pub.output_file);
putc(GETJSAMPLE(colormap[1][i]) >> cshift, dinfo->pub.output_file);
putc(GETJSAMPLE(colormap[2][i]) >> cshift, dinfo->pub.output_file);
} else {
/* Grayscale "color map": possible if quantizing grayscale image */
put_3bytes(dinfo, GETJSAMPLE(colormap[0][i]) >> cshift);
}
} else {
/* Create a gray-scale map of num_colors values, range 0..255 */
put_3bytes(dinfo, (i * 255 + (num_colors-1)/2) / (num_colors-1));
}
} else {
/* fill out the map to a power of 2 */
put_3bytes(dinfo, 0);
}
}
/* Write image separator and Image Descriptor */
putc(',', dinfo->pub.output_file); /* separator */
put_word(dinfo, 0); /* left/top offset */
put_word(dinfo, 0);
put_word(dinfo, (unsigned int) dinfo->cinfo->output_width); /* image size */
put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
/* flag byte: not interlaced, no local color map */
putc(0x00, dinfo->pub.output_file);
/* Write Initial Code Size byte */
putc(InitCodeSize, dinfo->pub.output_file);
/* Initialize for "compression" of image data */
compress_init(dinfo, InitCodeSize+1);
}
/*
* Startup: write the file header.
*/
METHODDEF(void)
start_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
{
gif_dest_ptr dest = (gif_dest_ptr) dinfo;
if (cinfo->quantize_colors)
emit_header(dest, cinfo->actual_number_of_colors, cinfo->colormap);
else
emit_header(dest, 256, (JSAMPARRAY) NULL);
}
/*
* Write some pixel data.
* In this module rows_supplied will always be 1.
*/
METHODDEF(void)
put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied)
{
gif_dest_ptr dest = (gif_dest_ptr) dinfo;
register JSAMPROW ptr;
register JDIMENSION col;
ptr = dest->pub.buffer[0];
for (col = cinfo->output_width; col > 0; col--) {
compress_pixel(dest, GETJSAMPLE(*ptr++));
}
}
/*
* Finish up at the end of the file.
*/
METHODDEF(void)
finish_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
{
gif_dest_ptr dest = (gif_dest_ptr) dinfo;
/* Flush "compression" mechanism */
compress_term(dest);
/* Write a zero-length data block to end the series */
putc(0, dest->pub.output_file);
/* Write the GIF terminator mark */
putc(';', dest->pub.output_file);
/* Make sure we wrote the output file OK */
fflush(dest->pub.output_file);
if (ferror(dest->pub.output_file))
ERREXIT(cinfo, JERR_FILE_WRITE);
}
/*
* The module selection routine for GIF format output.
*/
GLOBAL(djpeg_dest_ptr)
jinit_write_gif (j_decompress_ptr cinfo)
{
gif_dest_ptr dest;
/* Create module interface object, fill in method pointers */
dest = (gif_dest_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(gif_dest_struct));
dest->cinfo = cinfo; /* make back link for subroutines */
dest->pub.start_output = start_output_gif;
dest->pub.put_pixel_rows = put_pixel_rows;
dest->pub.finish_output = finish_output_gif;
if (cinfo->out_color_space != JCS_GRAYSCALE &&
cinfo->out_color_space != JCS_RGB)
ERREXIT(cinfo, JERR_GIF_COLORSPACE);
/* Force quantization if color or if > 8 bits input */
if (cinfo->out_color_space != JCS_GRAYSCALE || cinfo->data_precision > 8) {
/* Force quantization to at most 256 colors */
cinfo->quantize_colors = TRUE;
if (cinfo->desired_number_of_colors > 256)
cinfo->desired_number_of_colors = 256;
}
/* Calculate output image dimensions so we can allocate space */
jpeg_calc_output_dimensions(cinfo);
if (cinfo->output_components != 1) /* safety check: just one component? */
ERREXIT(cinfo, JERR_GIF_BUG);
/* Create decompressor output buffer. */
dest->pub.buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width, (JDIMENSION) 1);
dest->pub.buffer_height = 1;
return (djpeg_dest_ptr) dest;
}
#endif /* GIF_SUPPORTED */
|
1137519-player
|
jpeg-7/wrgif.c
|
C
|
lgpl
| 12,888
|
/*
* jdapistd.c
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains application interface code for the decompression half
* of the JPEG library. These are the "standard" API routines that are
* used in the normal full-decompression case. They are not used by a
* transcoding-only application. Note that if an application links in
* jpeg_start_decompress, it will end up linking in the entire decompressor.
* We thus must separate this file from jdapimin.c to avoid linking the
* whole decompression library into a transcoder.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/* Forward declarations */
LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
/*
* Decompression initialization.
* jpeg_read_header must be completed before calling this.
*
* If a multipass operating mode was selected, this will do all but the
* last pass, and thus may take a great deal of time.
*
* Returns FALSE if suspended. The return value need be inspected only if
* a suspending data source is used.
*/
GLOBAL(boolean)
jpeg_start_decompress (j_decompress_ptr cinfo)
{
if (cinfo->global_state == DSTATE_READY) {
/* First call: initialize master control, select active modules */
jinit_master_decompress(cinfo);
if (cinfo->buffered_image) {
/* No more work here; expecting jpeg_start_output next */
cinfo->global_state = DSTATE_BUFIMAGE;
return TRUE;
}
cinfo->global_state = DSTATE_PRELOAD;
}
if (cinfo->global_state == DSTATE_PRELOAD) {
/* If file has multiple scans, absorb them all into the coef buffer */
if (cinfo->inputctl->has_multiple_scans) {
#ifdef D_MULTISCAN_FILES_SUPPORTED
for (;;) {
int retcode;
/* Call progress monitor hook if present */
if (cinfo->progress != NULL)
(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
/* Absorb some more input */
retcode = (*cinfo->inputctl->consume_input) (cinfo);
if (retcode == JPEG_SUSPENDED)
return FALSE;
if (retcode == JPEG_REACHED_EOI)
break;
/* Advance progress counter if appropriate */
if (cinfo->progress != NULL &&
(retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
/* jdmaster underestimated number of scans; ratchet up one scan */
cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
}
}
}
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif /* D_MULTISCAN_FILES_SUPPORTED */
}
cinfo->output_scan_number = cinfo->input_scan_number;
} else if (cinfo->global_state != DSTATE_PRESCAN)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
/* Perform any dummy output passes, and set up for the final pass */
return output_pass_setup(cinfo);
}
/*
* Set up for an output pass, and perform any dummy pass(es) needed.
* Common subroutine for jpeg_start_decompress and jpeg_start_output.
* Entry: global_state = DSTATE_PRESCAN only if previously suspended.
* Exit: If done, returns TRUE and sets global_state for proper output mode.
* If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
*/
LOCAL(boolean)
output_pass_setup (j_decompress_ptr cinfo)
{
if (cinfo->global_state != DSTATE_PRESCAN) {
/* First call: do pass setup */
(*cinfo->master->prepare_for_output_pass) (cinfo);
cinfo->output_scanline = 0;
cinfo->global_state = DSTATE_PRESCAN;
}
/* Loop over any required dummy passes */
while (cinfo->master->is_dummy_pass) {
#ifdef QUANT_2PASS_SUPPORTED
/* Crank through the dummy pass */
while (cinfo->output_scanline < cinfo->output_height) {
JDIMENSION last_scanline;
/* Call progress monitor hook if present */
if (cinfo->progress != NULL) {
cinfo->progress->pass_counter = (long) cinfo->output_scanline;
cinfo->progress->pass_limit = (long) cinfo->output_height;
(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
}
/* Process some data */
last_scanline = cinfo->output_scanline;
(*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
&cinfo->output_scanline, (JDIMENSION) 0);
if (cinfo->output_scanline == last_scanline)
return FALSE; /* No progress made, must suspend */
}
/* Finish up dummy pass, and set up for another one */
(*cinfo->master->finish_output_pass) (cinfo);
(*cinfo->master->prepare_for_output_pass) (cinfo);
cinfo->output_scanline = 0;
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif /* QUANT_2PASS_SUPPORTED */
}
/* Ready for application to drive output pass through
* jpeg_read_scanlines or jpeg_read_raw_data.
*/
cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
return TRUE;
}
/*
* Read some scanlines of data from the JPEG decompressor.
*
* The return value will be the number of lines actually read.
* This may be less than the number requested in several cases,
* including bottom of image, data source suspension, and operating
* modes that emit multiple scanlines at a time.
*
* Note: we warn about excess calls to jpeg_read_scanlines() since
* this likely signals an application programmer error. However,
* an oversize buffer (max_lines > scanlines remaining) is not an error.
*/
GLOBAL(JDIMENSION)
jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
JDIMENSION max_lines)
{
JDIMENSION row_ctr;
if (cinfo->global_state != DSTATE_SCANNING)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
if (cinfo->output_scanline >= cinfo->output_height) {
WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
return 0;
}
/* Call progress monitor hook if present */
/* if (cinfo->progress != NULL) {
cinfo->progress->pass_counter = (long) cinfo->output_scanline;
cinfo->progress->pass_limit = (long) cinfo->output_height;
// (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
}
*/
/* Process some data */
row_ctr = 0;
(*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
cinfo->output_scanline += row_ctr;
return row_ctr;
}
/*
* Alternate entry point to read raw data.
* Processes exactly one iMCU row per call, unless suspended.
*/
GLOBAL(JDIMENSION)
jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
JDIMENSION max_lines)
{
JDIMENSION lines_per_iMCU_row;
if (cinfo->global_state != DSTATE_RAW_OK)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
if (cinfo->output_scanline >= cinfo->output_height) {
WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
return 0;
}
/* Call progress monitor hook if present */
if (cinfo->progress != NULL) {
cinfo->progress->pass_counter = (long) cinfo->output_scanline;
cinfo->progress->pass_limit = (long) cinfo->output_height;
(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
}
/* Verify that at least one iMCU row can be returned. */
lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_v_scaled_size;
if (max_lines < lines_per_iMCU_row)
ERREXIT(cinfo, JERR_BUFFER_SIZE);
/* Decompress directly into user's buffer. */
if (! (*cinfo->coef->decompress_data) (cinfo, data))
return 0; /* suspension forced, can do nothing more */
/* OK, we processed one iMCU row. */
cinfo->output_scanline += lines_per_iMCU_row;
return lines_per_iMCU_row;
}
/* Additional entry points for buffered-image mode. */
#ifdef D_MULTISCAN_FILES_SUPPORTED
/*
* Initialize for an output pass in buffered-image mode.
*/
GLOBAL(boolean)
jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
{
if (cinfo->global_state != DSTATE_BUFIMAGE &&
cinfo->global_state != DSTATE_PRESCAN)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
/* Limit scan number to valid range */
if (scan_number <= 0)
scan_number = 1;
if (cinfo->inputctl->eoi_reached &&
scan_number > cinfo->input_scan_number)
scan_number = cinfo->input_scan_number;
cinfo->output_scan_number = scan_number;
/* Perform any dummy output passes, and set up for the real pass */
return output_pass_setup(cinfo);
}
/*
* Finish up after an output pass in buffered-image mode.
*
* Returns FALSE if suspended. The return value need be inspected only if
* a suspending data source is used.
*/
GLOBAL(boolean)
jpeg_finish_output (j_decompress_ptr cinfo)
{
if ((cinfo->global_state == DSTATE_SCANNING ||
cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
/* Terminate this pass. */
/* We do not require the whole pass to have been completed. */
(*cinfo->master->finish_output_pass) (cinfo);
cinfo->global_state = DSTATE_BUFPOST;
} else if (cinfo->global_state != DSTATE_BUFPOST) {
/* BUFPOST = repeat call after a suspension, anything else is error */
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
}
/* Read markers looking for SOS or EOI */
while (cinfo->input_scan_number <= cinfo->output_scan_number &&
! cinfo->inputctl->eoi_reached) {
if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
return FALSE; /* Suspend, come back later */
}
cinfo->global_state = DSTATE_BUFIMAGE;
return TRUE;
}
#endif /* D_MULTISCAN_FILES_SUPPORTED */
|
1137519-player
|
jpeg-7/jdapistd.c
|
C
|
lgpl
| 9,359
|
/*
* jcprepct.c
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains the compression preprocessing controller.
* This controller manages the color conversion, downsampling,
* and edge expansion steps.
*
* Most of the complexity here is associated with buffering input rows
* as required by the downsampler. See the comments at the head of
* jcsample.c for the downsampler's needs.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/* At present, jcsample.c can request context rows only for smoothing.
* In the future, we might also need context rows for CCIR601 sampling
* or other more-complex downsampling procedures. The code to support
* context rows should be compiled only if needed.
*/
#ifdef INPUT_SMOOTHING_SUPPORTED
#define CONTEXT_ROWS_SUPPORTED
#endif
/*
* For the simple (no-context-row) case, we just need to buffer one
* row group's worth of pixels for the downsampling step. At the bottom of
* the image, we pad to a full row group by replicating the last pixel row.
* The downsampler's last output row is then replicated if needed to pad
* out to a full iMCU row.
*
* When providing context rows, we must buffer three row groups' worth of
* pixels. Three row groups are physically allocated, but the row pointer
* arrays are made five row groups high, with the extra pointers above and
* below "wrapping around" to point to the last and first real row groups.
* This allows the downsampler to access the proper context rows.
* At the top and bottom of the image, we create dummy context rows by
* copying the first or last real pixel row. This copying could be avoided
* by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
* trouble on the compression side.
*/
/* Private buffer controller object */
typedef struct {
struct jpeg_c_prep_controller pub; /* public fields */
/* Downsampling input buffer. This buffer holds color-converted data
* until we have enough to do a downsample step.
*/
JSAMPARRAY color_buf[MAX_COMPONENTS];
JDIMENSION rows_to_go; /* counts rows remaining in source image */
int next_buf_row; /* index of next row to store in color_buf */
#ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
int this_row_group; /* starting row index of group to process */
int next_buf_stop; /* downsample when we reach this index */
#endif
} my_prep_controller;
typedef my_prep_controller * my_prep_ptr;
/*
* Initialize for a processing pass.
*/
METHODDEF(void)
start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
{
my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
if (pass_mode != JBUF_PASS_THRU)
ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
/* Initialize total-height counter for detecting bottom of image */
prep->rows_to_go = cinfo->image_height;
/* Mark the conversion buffer empty */
prep->next_buf_row = 0;
#ifdef CONTEXT_ROWS_SUPPORTED
/* Preset additional state variables for context mode.
* These aren't used in non-context mode, so we needn't test which mode.
*/
prep->this_row_group = 0;
/* Set next_buf_stop to stop after two row groups have been read in. */
prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
#endif
}
/*
* Expand an image vertically from height input_rows to height output_rows,
* by duplicating the bottom row.
*/
LOCAL(void)
expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
int input_rows, int output_rows)
{
register int row;
for (row = input_rows; row < output_rows; row++) {
jcopy_sample_rows(image_data, input_rows-1, image_data, row,
1, num_cols);
}
}
/*
* Process some data in the simple no-context case.
*
* Preprocessor output data is counted in "row groups". A row group
* is defined to be v_samp_factor sample rows of each component.
* Downsampling will produce this much data from each max_v_samp_factor
* input rows.
*/
METHODDEF(void)
pre_process_data (j_compress_ptr cinfo,
JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
JDIMENSION in_rows_avail,
JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
JDIMENSION out_row_groups_avail)
{
my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
int numrows, ci;
JDIMENSION inrows;
jpeg_component_info * compptr;
while (*in_row_ctr < in_rows_avail &&
*out_row_group_ctr < out_row_groups_avail) {
/* Do color conversion to fill the conversion buffer. */
inrows = in_rows_avail - *in_row_ctr;
numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
numrows = (int) MIN((JDIMENSION) numrows, inrows);
(*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
prep->color_buf,
(JDIMENSION) prep->next_buf_row,
numrows);
*in_row_ctr += numrows;
prep->next_buf_row += numrows;
prep->rows_to_go -= numrows;
/* If at bottom of image, pad to fill the conversion buffer. */
if (prep->rows_to_go == 0 &&
prep->next_buf_row < cinfo->max_v_samp_factor) {
for (ci = 0; ci < cinfo->num_components; ci++) {
expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
prep->next_buf_row, cinfo->max_v_samp_factor);
}
prep->next_buf_row = cinfo->max_v_samp_factor;
}
/* If we've filled the conversion buffer, empty it. */
if (prep->next_buf_row == cinfo->max_v_samp_factor) {
(*cinfo->downsample->downsample) (cinfo,
prep->color_buf, (JDIMENSION) 0,
output_buf, *out_row_group_ctr);
prep->next_buf_row = 0;
(*out_row_group_ctr)++;
}
/* If at bottom of image, pad the output to a full iMCU height.
* Note we assume the caller is providing a one-iMCU-height output buffer!
*/
if (prep->rows_to_go == 0 &&
*out_row_group_ctr < out_row_groups_avail) {
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
numrows = (compptr->v_samp_factor * compptr->DCT_v_scaled_size) /
cinfo->min_DCT_v_scaled_size;
expand_bottom_edge(output_buf[ci],
compptr->width_in_blocks * compptr->DCT_h_scaled_size,
(int) (*out_row_group_ctr * numrows),
(int) (out_row_groups_avail * numrows));
}
*out_row_group_ctr = out_row_groups_avail;
break; /* can exit outer loop without test */
}
}
}
#ifdef CONTEXT_ROWS_SUPPORTED
/*
* Process some data in the context case.
*/
METHODDEF(void)
pre_process_context (j_compress_ptr cinfo,
JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
JDIMENSION in_rows_avail,
JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
JDIMENSION out_row_groups_avail)
{
my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
int numrows, ci;
int buf_height = cinfo->max_v_samp_factor * 3;
JDIMENSION inrows;
while (*out_row_group_ctr < out_row_groups_avail) {
if (*in_row_ctr < in_rows_avail) {
/* Do color conversion to fill the conversion buffer. */
inrows = in_rows_avail - *in_row_ctr;
numrows = prep->next_buf_stop - prep->next_buf_row;
numrows = (int) MIN((JDIMENSION) numrows, inrows);
(*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
prep->color_buf,
(JDIMENSION) prep->next_buf_row,
numrows);
/* Pad at top of image, if first time through */
if (prep->rows_to_go == cinfo->image_height) {
for (ci = 0; ci < cinfo->num_components; ci++) {
int row;
for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
jcopy_sample_rows(prep->color_buf[ci], 0,
prep->color_buf[ci], -row,
1, cinfo->image_width);
}
}
}
*in_row_ctr += numrows;
prep->next_buf_row += numrows;
prep->rows_to_go -= numrows;
} else {
/* Return for more data, unless we are at the bottom of the image. */
if (prep->rows_to_go != 0)
break;
/* When at bottom of image, pad to fill the conversion buffer. */
if (prep->next_buf_row < prep->next_buf_stop) {
for (ci = 0; ci < cinfo->num_components; ci++) {
expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
prep->next_buf_row, prep->next_buf_stop);
}
prep->next_buf_row = prep->next_buf_stop;
}
}
/* If we've gotten enough data, downsample a row group. */
if (prep->next_buf_row == prep->next_buf_stop) {
(*cinfo->downsample->downsample) (cinfo,
prep->color_buf,
(JDIMENSION) prep->this_row_group,
output_buf, *out_row_group_ctr);
(*out_row_group_ctr)++;
/* Advance pointers with wraparound as necessary. */
prep->this_row_group += cinfo->max_v_samp_factor;
if (prep->this_row_group >= buf_height)
prep->this_row_group = 0;
if (prep->next_buf_row >= buf_height)
prep->next_buf_row = 0;
prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
}
}
}
/*
* Create the wrapped-around downsampling input buffer needed for context mode.
*/
LOCAL(void)
create_context_buffer (j_compress_ptr cinfo)
{
my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
int rgroup_height = cinfo->max_v_samp_factor;
int ci, i;
jpeg_component_info * compptr;
JSAMPARRAY true_buffer, fake_buffer;
/* Grab enough space for fake row pointers for all the components;
* we need five row groups' worth of pointers for each component.
*/
fake_buffer = (JSAMPARRAY)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
(cinfo->num_components * 5 * rgroup_height) *
SIZEOF(JSAMPROW));
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
/* Allocate the actual buffer space (3 row groups) for this component.
* We make the buffer wide enough to allow the downsampler to edge-expand
* horizontally within the buffer, if it so chooses.
*/
true_buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE,
(JDIMENSION) (((long) compptr->width_in_blocks *
cinfo->min_DCT_h_scaled_size *
cinfo->max_h_samp_factor) / compptr->h_samp_factor),
(JDIMENSION) (3 * rgroup_height));
/* Copy true buffer row pointers into the middle of the fake row array */
MEMCOPY(fake_buffer + rgroup_height, true_buffer,
3 * rgroup_height * SIZEOF(JSAMPROW));
/* Fill in the above and below wraparound pointers */
for (i = 0; i < rgroup_height; i++) {
fake_buffer[i] = true_buffer[2 * rgroup_height + i];
fake_buffer[4 * rgroup_height + i] = true_buffer[i];
}
prep->color_buf[ci] = fake_buffer + rgroup_height;
fake_buffer += 5 * rgroup_height; /* point to space for next component */
}
}
#endif /* CONTEXT_ROWS_SUPPORTED */
/*
* Initialize preprocessing controller.
*/
GLOBAL(void)
jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
{
my_prep_ptr prep;
int ci;
jpeg_component_info * compptr;
if (need_full_buffer) /* safety check */
ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
prep = (my_prep_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(my_prep_controller));
cinfo->prep = (struct jpeg_c_prep_controller *) prep;
prep->pub.start_pass = start_pass_prep;
/* Allocate the color conversion buffer.
* We make the buffer wide enough to allow the downsampler to edge-expand
* horizontally within the buffer, if it so chooses.
*/
if (cinfo->downsample->need_context_rows) {
/* Set up to provide context rows */
#ifdef CONTEXT_ROWS_SUPPORTED
prep->pub.pre_process_data = pre_process_context;
create_context_buffer(cinfo);
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif
} else {
/* No context, just make it tall enough for one row group */
prep->pub.pre_process_data = pre_process_data;
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE,
(JDIMENSION) (((long) compptr->width_in_blocks *
cinfo->min_DCT_h_scaled_size *
cinfo->max_h_samp_factor) / compptr->h_samp_factor),
(JDIMENSION) cinfo->max_v_samp_factor);
}
}
}
|
1137519-player
|
jpeg-7/jcprepct.c
|
C
|
lgpl
| 12,216
|
/*
* jmemmac.c
*
* Copyright (C) 1992-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* jmemmac.c provides an Apple Macintosh implementation of the system-
* dependent portion of the JPEG memory manager.
*
* If you use jmemmac.c, then you must define USE_MAC_MEMMGR in the
* JPEG_INTERNALS part of jconfig.h.
*
* jmemmac.c uses the Macintosh toolbox routines NewPtr and DisposePtr
* instead of malloc and free. It accurately determines the amount of
* memory available by using CompactMem. Notice that if left to its
* own devices, this code can chew up all available space in the
* application's zone, with the exception of the rather small "slop"
* factor computed in jpeg_mem_available(). The application can ensure
* that more space is left over by reducing max_memory_to_use.
*
* Large images are swapped to disk using temporary files and System 7.0+'s
* temporary folder functionality.
*
* Note that jmemmac.c depends on two features of MacOS that were first
* introduced in System 7: FindFolder and the FSSpec-based calls.
* If your application uses jmemmac.c and is run under System 6 or earlier,
* and the jpeg library decides it needs a temporary file, it will abort,
* printing error messages about requiring System 7. (If no temporary files
* are created, it will run fine.)
*
* If you want to use jmemmac.c in an application that might be used with
* System 6 or earlier, then you should remove dependencies on FindFolder
* and the FSSpec calls. You will need to replace FindFolder with some
* other mechanism for finding a place to put temporary files, and you
* should replace the FSSpec calls with their HFS equivalents:
*
* FSpDelete -> HDelete
* FSpGetFInfo -> HGetFInfo
* FSpCreate -> HCreate
* FSpOpenDF -> HOpen *** Note: not HOpenDF ***
* FSMakeFSSpec -> (fill in spec by hand.)
*
* (Use HOpen instead of HOpenDF. HOpen is just a glue-interface to PBHOpen,
* which is on all HFS macs. HOpenDF is a System 7 addition which avoids the
* ages-old problem of names starting with a period.)
*
* Contributed by Sam Bushell (jsam@iagu.on.net) and
* Dan Gildor (gyld@in-touch.com).
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jmemsys.h" /* import the system-dependent declarations */
#ifndef USE_MAC_MEMMGR /* make sure user got configuration right */
You forgot to define USE_MAC_MEMMGR in jconfig.h. /* deliberate syntax error */
#endif
#include <Memory.h> /* we use the MacOS memory manager */
#include <Files.h> /* we use the MacOS File stuff */
#include <Folders.h> /* we use the MacOS HFS stuff */
#include <Script.h> /* for smSystemScript */
#include <Gestalt.h> /* we use Gestalt to test for specific functionality */
#ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */
#define TEMP_FILE_NAME "JPG%03d.TMP"
#endif
static int next_file_num; /* to distinguish among several temp files */
/*
* Memory allocation and freeing are controlled by the MacOS library
* routines NewPtr() and DisposePtr(), which allocate fixed-address
* storage. Unfortunately, the IJG library isn't smart enough to cope
* with relocatable storage.
*/
GLOBAL(void *)
jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
{
return (void *) NewPtr(sizeofobject);
}
GLOBAL(void)
jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
{
DisposePtr((Ptr) object);
}
/*
* "Large" objects are treated the same as "small" ones.
* NB: we include FAR keywords in the routine declarations simply for
* consistency with the rest of the IJG code; FAR should expand to empty
* on rational architectures like the Mac.
*/
GLOBAL(void FAR *)
jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
{
return (void FAR *) NewPtr(sizeofobject);
}
GLOBAL(void)
jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
{
DisposePtr((Ptr) object);
}
/*
* This routine computes the total memory space available for allocation.
*/
GLOBAL(long)
jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
long max_bytes_needed, long already_allocated)
{
long limit = cinfo->mem->max_memory_to_use - already_allocated;
long slop, mem;
/* Don't ask for more than what application has told us we may use */
if (max_bytes_needed > limit && limit > 0)
max_bytes_needed = limit;
/* Find whether there's a big enough free block in the heap.
* CompactMem tries to create a contiguous block of the requested size,
* and then returns the size of the largest free block (which could be
* much more or much less than we asked for).
* We add some slop to ensure we don't use up all available memory.
*/
slop = max_bytes_needed / 16 + 32768L;
mem = CompactMem(max_bytes_needed + slop) - slop;
if (mem < 0)
mem = 0; /* sigh, couldn't even get the slop */
/* Don't take more than the application says we can have */
if (mem > limit && limit > 0)
mem = limit;
return mem;
}
/*
* Backing store (temporary file) management.
* Backing store objects are only used when the value returned by
* jpeg_mem_available is less than the total space needed. You can dispense
* with these routines if you have plenty of virtual memory; see jmemnobs.c.
*/
METHODDEF(void)
read_backing_store (j_common_ptr cinfo, backing_store_ptr info,
void FAR * buffer_address,
long file_offset, long byte_count)
{
long bytes = byte_count;
long retVal;
if ( SetFPos ( info->temp_file, fsFromStart, file_offset ) != noErr )
ERREXIT(cinfo, JERR_TFILE_SEEK);
retVal = FSRead ( info->temp_file, &bytes,
(unsigned char *) buffer_address );
if ( retVal != noErr || bytes != byte_count )
ERREXIT(cinfo, JERR_TFILE_READ);
}
METHODDEF(void)
write_backing_store (j_common_ptr cinfo, backing_store_ptr info,
void FAR * buffer_address,
long file_offset, long byte_count)
{
long bytes = byte_count;
long retVal;
if ( SetFPos ( info->temp_file, fsFromStart, file_offset ) != noErr )
ERREXIT(cinfo, JERR_TFILE_SEEK);
retVal = FSWrite ( info->temp_file, &bytes,
(unsigned char *) buffer_address );
if ( retVal != noErr || bytes != byte_count )
ERREXIT(cinfo, JERR_TFILE_WRITE);
}
METHODDEF(void)
close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
{
FSClose ( info->temp_file );
FSpDelete ( &(info->tempSpec) );
}
/*
* Initial opening of a backing-store object.
*
* This version uses FindFolder to find the Temporary Items folder,
* and puts the temporary file in there.
*/
GLOBAL(void)
jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
long total_bytes_needed)
{
short tmpRef, vRefNum;
long dirID;
FInfo finderInfo;
FSSpec theSpec;
Str255 fName;
OSErr osErr;
long gestaltResponse = 0;
/* Check that FSSpec calls are available. */
osErr = Gestalt( gestaltFSAttr, &gestaltResponse );
if ( ( osErr != noErr )
|| !( gestaltResponse & (1<<gestaltHasFSSpecCalls) ) )
ERREXITS(cinfo, JERR_TFILE_CREATE, "- System 7.0 or later required");
/* TO DO: add a proper error message to jerror.h. */
/* Check that FindFolder is available. */
osErr = Gestalt( gestaltFindFolderAttr, &gestaltResponse );
if ( ( osErr != noErr )
|| !( gestaltResponse & (1<<gestaltFindFolderPresent) ) )
ERREXITS(cinfo, JERR_TFILE_CREATE, "- System 7.0 or later required.");
/* TO DO: add a proper error message to jerror.h. */
osErr = FindFolder ( kOnSystemDisk, kTemporaryFolderType, kCreateFolder,
&vRefNum, &dirID );
if ( osErr != noErr )
ERREXITS(cinfo, JERR_TFILE_CREATE, "- temporary items folder unavailable");
/* TO DO: Try putting the temp files somewhere else. */
/* Keep generating file names till we find one that's not in use */
for (;;) {
next_file_num++; /* advance counter */
sprintf(info->temp_name, TEMP_FILE_NAME, next_file_num);
strcpy ( (Ptr)fName+1, info->temp_name );
*fName = strlen (info->temp_name);
osErr = FSMakeFSSpec ( vRefNum, dirID, fName, &theSpec );
if ( (osErr = FSpGetFInfo ( &theSpec, &finderInfo ) ) != noErr )
break;
}
osErr = FSpCreate ( &theSpec, '????', '????', smSystemScript );
if ( osErr != noErr )
ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
osErr = FSpOpenDF ( &theSpec, fsRdWrPerm, &(info->temp_file) );
if ( osErr != noErr )
ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
info->tempSpec = theSpec;
info->read_backing_store = read_backing_store;
info->write_backing_store = write_backing_store;
info->close_backing_store = close_backing_store;
TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name);
}
/*
* These routines take care of any system-dependent initialization and
* cleanup required.
*/
GLOBAL(long)
jpeg_mem_init (j_common_ptr cinfo)
{
next_file_num = 0;
/* max_memory_to_use will be initialized to FreeMem()'s result;
* the calling application might later reduce it, for example
* to leave room to invoke multiple JPEG objects.
* Note that FreeMem returns the total number of free bytes;
* it may not be possible to allocate a single block of this size.
*/
return FreeMem();
}
GLOBAL(void)
jpeg_mem_term (j_common_ptr cinfo)
{
/* no work */
}
|
1137519-player
|
jpeg-7/jmemmac.c
|
C
|
lgpl
| 9,507
|
/*
* jfdctflt.c
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* Modified 2003-2009 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains a floating-point implementation of the
* forward DCT (Discrete Cosine Transform).
*
* This implementation should be more accurate than either of the integer
* DCT implementations. However, it may not give the same results on all
* machines because of differences in roundoff behavior. Speed will depend
* on the hardware's floating point capacity.
*
* A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
* on each column. Direct algorithms are also available, but they are
* much more complex and seem not to be any faster when reduced to code.
*
* This implementation is based on Arai, Agui, and Nakajima's algorithm for
* scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
* Japanese, but the algorithm is described in the Pennebaker & Mitchell
* JPEG textbook (see REFERENCES section in file README). The following code
* is based directly on figure 4-8 in P&M.
* While an 8-point DCT cannot be done in less than 11 multiplies, it is
* possible to arrange the computation so that many of the multiplies are
* simple scalings of the final outputs. These multiplies can then be
* folded into the multiplications or divisions by the JPEG quantization
* table entries. The AA&N method leaves only 5 multiplies and 29 adds
* to be done in the DCT itself.
* The primary disadvantage of this method is that with a fixed-point
* implementation, accuracy is lost due to imprecise representation of the
* scaled quantization values. However, that problem does not arise if
* we use floating point arithmetic.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jdct.h" /* Private declarations for DCT subsystem */
#ifdef DCT_FLOAT_SUPPORTED
/*
* This module is specialized to the case DCTSIZE = 8.
*/
#if DCTSIZE != 8
Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
#endif
/*
* Perform the forward DCT on one block of samples.
*/
GLOBAL(void)
jpeg_fdct_float (FAST_FLOAT * data, JSAMPARRAY sample_data, JDIMENSION start_col)
{
FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
FAST_FLOAT *dataptr;
JSAMPROW elemptr;
int ctr;
/* Pass 1: process rows. */
dataptr = data;
for (ctr = 0; ctr < DCTSIZE; ctr++) {
elemptr = sample_data[ctr] + start_col;
/* Load data into workspace */
tmp0 = (FAST_FLOAT) (GETJSAMPLE(elemptr[0]) + GETJSAMPLE(elemptr[7]));
tmp7 = (FAST_FLOAT) (GETJSAMPLE(elemptr[0]) - GETJSAMPLE(elemptr[7]));
tmp1 = (FAST_FLOAT) (GETJSAMPLE(elemptr[1]) + GETJSAMPLE(elemptr[6]));
tmp6 = (FAST_FLOAT) (GETJSAMPLE(elemptr[1]) - GETJSAMPLE(elemptr[6]));
tmp2 = (FAST_FLOAT) (GETJSAMPLE(elemptr[2]) + GETJSAMPLE(elemptr[5]));
tmp5 = (FAST_FLOAT) (GETJSAMPLE(elemptr[2]) - GETJSAMPLE(elemptr[5]));
tmp3 = (FAST_FLOAT) (GETJSAMPLE(elemptr[3]) + GETJSAMPLE(elemptr[4]));
tmp4 = (FAST_FLOAT) (GETJSAMPLE(elemptr[3]) - GETJSAMPLE(elemptr[4]));
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
/* Apply unsigned->signed conversion */
dataptr[0] = tmp10 + tmp11 - 8 * CENTERJSAMPLE; /* phase 3 */
dataptr[4] = tmp10 - tmp11;
z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
dataptr[2] = tmp13 + z1; /* phase 5 */
dataptr[6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
dataptr[5] = z13 + z2; /* phase 6 */
dataptr[3] = z13 - z2;
dataptr[1] = z11 + z4;
dataptr[7] = z11 - z4;
dataptr += DCTSIZE; /* advance pointer to next row */
}
/* Pass 2: process columns. */
dataptr = data;
for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
dataptr[DCTSIZE*4] = tmp10 - tmp11;
z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
dataptr[DCTSIZE*6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
dataptr[DCTSIZE*3] = z13 - z2;
dataptr[DCTSIZE*1] = z11 + z4;
dataptr[DCTSIZE*7] = z11 - z4;
dataptr++; /* advance pointer to next column */
}
}
#endif /* DCT_FLOAT_SUPPORTED */
|
1137519-player
|
jpeg-7/jfdctflt.c
|
C
|
lgpl
| 6,008
|
/*
* cdjpeg.h
*
* Copyright (C) 1994-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains common declarations for the sample applications
* cjpeg and djpeg. It is NOT used by the core JPEG library.
*/
#define JPEG_CJPEG_DJPEG /* define proper options in jconfig.h */
#define JPEG_INTERNAL_OPTIONS /* cjpeg.c,djpeg.c need to see xxx_SUPPORTED */
#include "jinclude.h"
#include "jpeglib.h"
#include "jerror.h" /* get library error codes too */
#include "cderror.h" /* get application-specific error codes */
/*
* Object interface for cjpeg's source file decoding modules
*/
typedef struct cjpeg_source_struct * cjpeg_source_ptr;
struct cjpeg_source_struct {
JMETHOD(void, start_input, (j_compress_ptr cinfo,
cjpeg_source_ptr sinfo));
JMETHOD(JDIMENSION, get_pixel_rows, (j_compress_ptr cinfo,
cjpeg_source_ptr sinfo));
JMETHOD(void, finish_input, (j_compress_ptr cinfo,
cjpeg_source_ptr sinfo));
FILE *input_file;
JSAMPARRAY buffer;
JDIMENSION buffer_height;
};
/*
* Object interface for djpeg's output file encoding modules
*/
typedef struct djpeg_dest_struct * djpeg_dest_ptr;
struct djpeg_dest_struct {
/* start_output is called after jpeg_start_decompress finishes.
* The color map will be ready at this time, if one is needed.
*/
JMETHOD(void, start_output, (j_decompress_ptr cinfo,
djpeg_dest_ptr dinfo));
/* Emit the specified number of pixel rows from the buffer. */
JMETHOD(void, put_pixel_rows, (j_decompress_ptr cinfo,
djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied));
/* Finish up at the end of the image. */
JMETHOD(void, finish_output, (j_decompress_ptr cinfo,
djpeg_dest_ptr dinfo));
/* Target file spec; filled in by djpeg.c after object is created. */
FILE * output_file;
/* Output pixel-row buffer. Created by module init or start_output.
* Width is cinfo->output_width * cinfo->output_components;
* height is buffer_height.
*/
JSAMPARRAY buffer;
JDIMENSION buffer_height;
};
/*
* cjpeg/djpeg may need to perform extra passes to convert to or from
* the source/destination file format. The JPEG library does not know
* about these passes, but we'd like them to be counted by the progress
* monitor. We use an expanded progress monitor object to hold the
* additional pass count.
*/
struct cdjpeg_progress_mgr {
struct jpeg_progress_mgr pub; /* fields known to JPEG library */
int completed_extra_passes; /* extra passes completed */
int total_extra_passes; /* total extra */
/* last printed percentage stored here to avoid multiple printouts */
int percent_done;
};
typedef struct cdjpeg_progress_mgr * cd_progress_ptr;
/* Short forms of external names for systems with brain-damaged linkers. */
#ifdef NEED_SHORT_EXTERNAL_NAMES
#define jinit_read_bmp jIRdBMP
#define jinit_write_bmp jIWrBMP
#define jinit_read_gif jIRdGIF
#define jinit_write_gif jIWrGIF
#define jinit_read_ppm jIRdPPM
#define jinit_write_ppm jIWrPPM
#define jinit_read_rle jIRdRLE
#define jinit_write_rle jIWrRLE
#define jinit_read_targa jIRdTarga
#define jinit_write_targa jIWrTarga
#define read_quant_tables RdQTables
#define read_scan_script RdScnScript
#define set_quality_ratings SetQRates
#define set_quant_slots SetQSlots
#define set_sample_factors SetSFacts
#define read_color_map RdCMap
#define enable_signal_catcher EnSigCatcher
#define start_progress_monitor StProgMon
#define end_progress_monitor EnProgMon
#define read_stdin RdStdin
#define write_stdout WrStdout
#endif /* NEED_SHORT_EXTERNAL_NAMES */
/* Module selection routines for I/O modules. */
EXTERN(cjpeg_source_ptr) jinit_read_bmp JPP((j_compress_ptr cinfo));
EXTERN(djpeg_dest_ptr) jinit_write_bmp JPP((j_decompress_ptr cinfo,
boolean is_os2));
EXTERN(cjpeg_source_ptr) jinit_read_gif JPP((j_compress_ptr cinfo));
EXTERN(djpeg_dest_ptr) jinit_write_gif JPP((j_decompress_ptr cinfo));
EXTERN(cjpeg_source_ptr) jinit_read_ppm JPP((j_compress_ptr cinfo));
EXTERN(djpeg_dest_ptr) jinit_write_ppm JPP((j_decompress_ptr cinfo));
EXTERN(cjpeg_source_ptr) jinit_read_rle JPP((j_compress_ptr cinfo));
EXTERN(djpeg_dest_ptr) jinit_write_rle JPP((j_decompress_ptr cinfo));
EXTERN(cjpeg_source_ptr) jinit_read_targa JPP((j_compress_ptr cinfo));
EXTERN(djpeg_dest_ptr) jinit_write_targa JPP((j_decompress_ptr cinfo));
/* cjpeg support routines (in rdswitch.c) */
EXTERN(boolean) read_quant_tables JPP((j_compress_ptr cinfo, char * filename,
boolean force_baseline));
EXTERN(boolean) read_scan_script JPP((j_compress_ptr cinfo, char * filename));
EXTERN(boolean) set_quality_ratings JPP((j_compress_ptr cinfo, char *arg,
boolean force_baseline));
EXTERN(boolean) set_quant_slots JPP((j_compress_ptr cinfo, char *arg));
EXTERN(boolean) set_sample_factors JPP((j_compress_ptr cinfo, char *arg));
/* djpeg support routines (in rdcolmap.c) */
EXTERN(void) read_color_map JPP((j_decompress_ptr cinfo, FILE * infile));
/* common support routines (in cdjpeg.c) */
EXTERN(void) enable_signal_catcher JPP((j_common_ptr cinfo));
EXTERN(void) start_progress_monitor JPP((j_common_ptr cinfo,
cd_progress_ptr progress));
EXTERN(void) end_progress_monitor JPP((j_common_ptr cinfo));
EXTERN(boolean) keymatch JPP((char * arg, const char * keyword, int minchars));
EXTERN(FILE *) read_stdin JPP((void));
EXTERN(FILE *) write_stdout JPP((void));
/* miscellaneous useful macros */
#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
#define READ_BINARY "r"
#define WRITE_BINARY "w"
#else
#ifdef VMS /* VMS is very nonstandard */
#define READ_BINARY "rb", "ctx=stm"
#define WRITE_BINARY "wb", "ctx=stm"
#else /* standard ANSI-compliant case */
#define READ_BINARY "rb"
#define WRITE_BINARY "wb"
#endif
#endif
#ifndef EXIT_FAILURE /* define exit() codes if not provided */
#define EXIT_FAILURE 1
#endif
#ifndef EXIT_SUCCESS
#ifdef VMS
#define EXIT_SUCCESS 1 /* VMS is very nonstandard */
#else
#define EXIT_SUCCESS 0
#endif
#endif
#ifndef EXIT_WARNING
#ifdef VMS
#define EXIT_WARNING 1 /* VMS is very nonstandard */
#else
#define EXIT_WARNING 2
#endif
#endif
|
1137519-player
|
jpeg-7/cdjpeg.h
|
C
|
lgpl
| 6,256
|
/*
* jdatadst.c
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains compression data destination routines for the case of
* emitting JPEG data to a file (or any stdio stream). While these routines
* are sufficient for most applications, some will want to use a different
* destination manager.
* IMPORTANT: we assume that fwrite() will correctly transcribe an array of
* JOCTETs into 8-bit-wide elements on external storage. If char is wider
* than 8 bits on your machine, you may need to do some tweaking.
*/
/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
#include "jinclude.h"
#include "jpeglib.h"
#include "jerror.h"
/* Expanded data destination object for stdio output */
typedef struct {
struct jpeg_destination_mgr pub; /* public fields */
FILE * outfile; /* target stream */
JOCTET * buffer; /* start of buffer */
} my_destination_mgr;
typedef my_destination_mgr * my_dest_ptr;
#define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
/*
* Initialize destination --- called by jpeg_start_compress
* before any data is actually written.
*/
METHODDEF(void)
init_destination (j_compress_ptr cinfo)
{
my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
/* Allocate the output buffer --- it will be released when done with image */
dest->buffer = (JOCTET *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
OUTPUT_BUF_SIZE * SIZEOF(JOCTET));
dest->pub.next_output_byte = dest->buffer;
dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
}
/*
* Empty the output buffer --- called whenever buffer fills up.
*
* In typical applications, this should write the entire output buffer
* (ignoring the current state of next_output_byte & free_in_buffer),
* reset the pointer & count to the start of the buffer, and return TRUE
* indicating that the buffer has been dumped.
*
* In applications that need to be able to suspend compression due to output
* overrun, a FALSE return indicates that the buffer cannot be emptied now.
* In this situation, the compressor will return to its caller (possibly with
* an indication that it has not accepted all the supplied scanlines). The
* application should resume compression after it has made more room in the
* output buffer. Note that there are substantial restrictions on the use of
* suspension --- see the documentation.
*
* When suspending, the compressor will back up to a convenient restart point
* (typically the start of the current MCU). next_output_byte & free_in_buffer
* indicate where the restart point will be if the current call returns FALSE.
* Data beyond this point will be regenerated after resumption, so do not
* write it out when emptying the buffer externally.
*/
METHODDEF(boolean)
empty_output_buffer (j_compress_ptr cinfo)
{
my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
if (JFWRITE(dest->outfile, dest->buffer, OUTPUT_BUF_SIZE) !=
(size_t) OUTPUT_BUF_SIZE)
ERREXIT(cinfo, JERR_FILE_WRITE);
dest->pub.next_output_byte = dest->buffer;
dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
return TRUE;
}
/*
* Terminate destination --- called by jpeg_finish_compress
* after all data has been written. Usually needs to flush buffer.
*
* NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
* application must deal with any cleanup that should happen even
* for error exit.
*/
METHODDEF(void)
term_destination (j_compress_ptr cinfo)
{
my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
/* Write any data remaining in the buffer */
if (datacount > 0) {
if (JFWRITE(dest->outfile, dest->buffer, datacount) != datacount)
ERREXIT(cinfo, JERR_FILE_WRITE);
}
fflush(dest->outfile);
/* Make sure we wrote the output file OK */
if (ferror(dest->outfile))
ERREXIT(cinfo, JERR_FILE_WRITE);
}
/*
* Prepare for output to a stdio stream.
* The caller must have already opened the stream, and is responsible
* for closing it after finishing compression.
*/
GLOBAL(void)
jpeg_stdio_dest (j_compress_ptr cinfo, MY_FILE * outfile)
{
my_dest_ptr dest;
/* The destination object is made permanent so that multiple JPEG images
* can be written to the same file without re-executing jpeg_stdio_dest.
* This makes it dangerous to use this manager and a different destination
* manager serially with the same JPEG object, because their private object
* sizes may be different. Caveat programmer.
*/
if (cinfo->dest == NULL) { /* first time for this JPEG object? */
cinfo->dest = (struct jpeg_destination_mgr *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
SIZEOF(my_destination_mgr));
}
dest = (my_dest_ptr) cinfo->dest;
dest->pub.init_destination = init_destination;
dest->pub.empty_output_buffer = empty_output_buffer;
dest->pub.term_destination = term_destination;
dest->outfile = outfile;
}
|
1137519-player
|
jpeg-7/jdatadst.c
|
C
|
lgpl
| 5,122
|
/*
* wrtarga.c
*
* Copyright (C) 1991-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains routines to write output images in Targa format.
*
* These routines may need modification for non-Unix environments or
* specialized applications. As they stand, they assume output to
* an ordinary stdio stream.
*
* Based on code contributed by Lee Daniel Crocker.
*/
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#ifdef TARGA_SUPPORTED
/*
* To support 12-bit JPEG data, we'd have to scale output down to 8 bits.
* This is not yet implemented.
*/
#if BITS_IN_JSAMPLE != 8
Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
#endif
/*
* The output buffer needs to be writable by fwrite(). On PCs, we must
* allocate the buffer in near data space, because we are assuming small-data
* memory model, wherein fwrite() can't reach far memory. If you need to
* process very wide images on a PC, you might have to compile in large-memory
* model, or else replace fwrite() with a putc() loop --- which will be much
* slower.
*/
/* Private version of data destination object */
typedef struct {
struct djpeg_dest_struct pub; /* public fields */
char *iobuffer; /* physical I/O buffer */
JDIMENSION buffer_width; /* width of one row */
} tga_dest_struct;
typedef tga_dest_struct * tga_dest_ptr;
LOCAL(void)
write_header (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, int num_colors)
/* Create and write a Targa header */
{
char targaheader[18];
/* Set unused fields of header to 0 */
MEMZERO(targaheader, SIZEOF(targaheader));
if (num_colors > 0) {
targaheader[1] = 1; /* color map type 1 */
targaheader[5] = (char) (num_colors & 0xFF);
targaheader[6] = (char) (num_colors >> 8);
targaheader[7] = 24; /* 24 bits per cmap entry */
}
targaheader[12] = (char) (cinfo->output_width & 0xFF);
targaheader[13] = (char) (cinfo->output_width >> 8);
targaheader[14] = (char) (cinfo->output_height & 0xFF);
targaheader[15] = (char) (cinfo->output_height >> 8);
targaheader[17] = 0x20; /* Top-down, non-interlaced */
if (cinfo->out_color_space == JCS_GRAYSCALE) {
targaheader[2] = 3; /* image type = uncompressed gray-scale */
targaheader[16] = 8; /* bits per pixel */
} else { /* must be RGB */
if (num_colors > 0) {
targaheader[2] = 1; /* image type = colormapped RGB */
targaheader[16] = 8;
} else {
targaheader[2] = 2; /* image type = uncompressed RGB */
targaheader[16] = 24;
}
}
if (JFWRITE(dinfo->output_file, targaheader, 18) != (size_t) 18)
ERREXIT(cinfo, JERR_FILE_WRITE);
}
/*
* Write some pixel data.
* In this module rows_supplied will always be 1.
*/
METHODDEF(void)
put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied)
/* used for unquantized full-color output */
{
tga_dest_ptr dest = (tga_dest_ptr) dinfo;
register JSAMPROW inptr;
register char * outptr;
register JDIMENSION col;
inptr = dest->pub.buffer[0];
outptr = dest->iobuffer;
for (col = cinfo->output_width; col > 0; col--) {
outptr[0] = (char) GETJSAMPLE(inptr[2]); /* RGB to BGR order */
outptr[1] = (char) GETJSAMPLE(inptr[1]);
outptr[2] = (char) GETJSAMPLE(inptr[0]);
inptr += 3, outptr += 3;
}
(void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
}
METHODDEF(void)
put_gray_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied)
/* used for grayscale OR quantized color output */
{
tga_dest_ptr dest = (tga_dest_ptr) dinfo;
register JSAMPROW inptr;
register char * outptr;
register JDIMENSION col;
inptr = dest->pub.buffer[0];
outptr = dest->iobuffer;
for (col = cinfo->output_width; col > 0; col--) {
*outptr++ = (char) GETJSAMPLE(*inptr++);
}
(void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
}
/*
* Write some demapped pixel data when color quantization is in effect.
* For Targa, this is only applied to grayscale data.
*/
METHODDEF(void)
put_demapped_gray (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied)
{
tga_dest_ptr dest = (tga_dest_ptr) dinfo;
register JSAMPROW inptr;
register char * outptr;
register JSAMPROW color_map0 = cinfo->colormap[0];
register JDIMENSION col;
inptr = dest->pub.buffer[0];
outptr = dest->iobuffer;
for (col = cinfo->output_width; col > 0; col--) {
*outptr++ = (char) GETJSAMPLE(color_map0[GETJSAMPLE(*inptr++)]);
}
(void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
}
/*
* Startup: write the file header.
*/
METHODDEF(void)
start_output_tga (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
{
tga_dest_ptr dest = (tga_dest_ptr) dinfo;
int num_colors, i;
FILE *outfile;
if (cinfo->out_color_space == JCS_GRAYSCALE) {
/* Targa doesn't have a mapped grayscale format, so we will */
/* demap quantized gray output. Never emit a colormap. */
write_header(cinfo, dinfo, 0);
if (cinfo->quantize_colors)
dest->pub.put_pixel_rows = put_demapped_gray;
else
dest->pub.put_pixel_rows = put_gray_rows;
} else if (cinfo->out_color_space == JCS_RGB) {
if (cinfo->quantize_colors) {
/* We only support 8-bit colormap indexes, so only 256 colors */
num_colors = cinfo->actual_number_of_colors;
if (num_colors > 256)
ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, num_colors);
write_header(cinfo, dinfo, num_colors);
/* Write the colormap. Note Targa uses BGR byte order */
outfile = dest->pub.output_file;
for (i = 0; i < num_colors; i++) {
putc(GETJSAMPLE(cinfo->colormap[2][i]), outfile);
putc(GETJSAMPLE(cinfo->colormap[1][i]), outfile);
putc(GETJSAMPLE(cinfo->colormap[0][i]), outfile);
}
dest->pub.put_pixel_rows = put_gray_rows;
} else {
write_header(cinfo, dinfo, 0);
dest->pub.put_pixel_rows = put_pixel_rows;
}
} else {
ERREXIT(cinfo, JERR_TGA_COLORSPACE);
}
}
/*
* Finish up at the end of the file.
*/
METHODDEF(void)
finish_output_tga (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
{
/* Make sure we wrote the output file OK */
fflush(dinfo->output_file);
if (ferror(dinfo->output_file))
ERREXIT(cinfo, JERR_FILE_WRITE);
}
/*
* The module selection routine for Targa format output.
*/
GLOBAL(djpeg_dest_ptr)
jinit_write_targa (j_decompress_ptr cinfo)
{
tga_dest_ptr dest;
/* Create module interface object, fill in method pointers */
dest = (tga_dest_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(tga_dest_struct));
dest->pub.start_output = start_output_tga;
dest->pub.finish_output = finish_output_tga;
/* Calculate output image dimensions so we can allocate space */
jpeg_calc_output_dimensions(cinfo);
/* Create I/O buffer. Note we make this near on a PC. */
dest->buffer_width = cinfo->output_width * cinfo->output_components;
dest->iobuffer = (char *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
(size_t) (dest->buffer_width * SIZEOF(char)));
/* Create decompressor output buffer. */
dest->pub.buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE, dest->buffer_width, (JDIMENSION) 1);
dest->pub.buffer_height = 1;
return (djpeg_dest_ptr) dest;
}
#endif /* TARGA_SUPPORTED */
|
1137519-player
|
jpeg-7/wrtarga.c
|
C
|
lgpl
| 7,524
|
# Makefile for Independent JPEG Group's software
# This makefile is for Amiga systems using SAS C 6.0 and up.
# Thanks to Ed Hanway, Mark Rinfret, and Jim Zepeda.
# Read installation instructions before saying "make" !!
# The name of your C compiler:
CC= sc
# You may need to adjust these cc options:
# Uncomment the following lines for generic 680x0 version
ARCHFLAGS= cpu=any
SUFFIX=
# Uncomment the following lines for 68030-only version
#ARCHFLAGS= cpu=68030
#SUFFIX=.030
CFLAGS= nostackcheck data=near parms=register optimize $(ARCHFLAGS) \
ignore=104 ignore=304 ignore=306
# ignore=104 disables warnings for mismatched const qualifiers
# ignore=304 disables warnings for variables being optimized out
# ignore=306 disables warnings for the inlining of functions
# Generally, we recommend defining any configuration symbols in jconfig.h,
# NOT via define switches here.
# Link-time cc options:
LDFLAGS= SC SD ND BATCH
# To link any special libraries, add the necessary commands here.
LDLIBS= LIB:scm.lib LIB:sc.lib
# Put here the object file name for the correct system-dependent memory
# manager file. For Amiga we recommend jmemname.o.
SYSDEPMEM= jmemname.o
# miscellaneous OS-dependent stuff
# linker
LN= slink
# file deletion command
RM= delete quiet
# library (.lib) file creation command
AR= oml
# End of configurable options.
# source files: JPEG library proper
LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \
jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \
jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \
jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \
jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \
jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \
jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \
jquant2.c jutils.c jmemmgr.c
# memmgr back ends: compile only one of these into a working library
SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
# files included by source files
INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h \
jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
# documentation, test, and support files
DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt \
coderules.txt filelist.txt change.log
MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.bcc \
makefile.mc6 makefile.dj makefile.wat makefile.vc makejdsw.vc6 \
makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 makecdep.vc6 \
makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 makedmak.vc6 \
maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 makerdsp.vc6 \
makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 makejsln.vc9 \
makeasln.vc9 makejvcp.vc9 makecvcp.vc9 makedvcp.vc9 maketvcp.vc9 \
makervcp.vc9 makewvcp.vc9 makeproj.mac makcjpeg.st makdjpeg.st \
makljpeg.st maktjpeg.st makefile.manx makefile.sas makefile.mms \
makefile.vms makvms.opt
CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
jconfig.vms
CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp missing
OTHERFILES= jconfig.txt ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm \
libjpeg.map
TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
testimgp.jpg
DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
$(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
# library object files common to compression and decompression
COMOBJECTS= jaricom.o jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM)
# compression library object files
CLIBOBJECTS= jcapimin.o jcapistd.o jcarith.o jctrans.o jcparam.o \
jdatadst.o jcinit.o jcmaster.o jcmarker.o jcmainct.o jcprepct.o \
jccoefct.o jccolor.o jcsample.o jchuff.o jcdctmgr.o jfdctfst.o \
jfdctflt.o jfdctint.o
# decompression library object files
DLIBOBJECTS= jdapimin.o jdapistd.o jdarith.o jdtrans.o jdatasrc.o \
jdmaster.o jdinput.o jdmarker.o jdhuff.o jdmainct.o \
jdcoefct.o jdpostct.o jddctmgr.o jidctfst.o jidctflt.o \
jidctint.o jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o
# These objectfiles are included in libjpeg.lib
LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
# object files for sample applications (excluding library files)
COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \
cdjpeg.o
DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \
cdjpeg.o
TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o
all: libjpeg.lib cjpeg$(SUFFIX) djpeg$(SUFFIX) jpegtran$(SUFFIX) rdjpgcom$(SUFFIX) wrjpgcom$(SUFFIX)
# note: do several AR steps to avoid command line length limitations
libjpeg.lib: $(LIBOBJECTS)
-$(RM) libjpeg.lib
$(AR) libjpeg.lib r $(CLIBOBJECTS)
$(AR) libjpeg.lib r $(DLIBOBJECTS)
$(AR) libjpeg.lib r $(COMOBJECTS)
cjpeg$(SUFFIX): $(COBJECTS) libjpeg.lib
$(LN) <WITH <
$(LDFLAGS)
TO cjpeg$(SUFFIX)
FROM LIB:c.o $(COBJECTS)
LIB libjpeg.lib $(LDLIBS)
<
djpeg$(SUFFIX): $(DOBJECTS) libjpeg.lib
$(LN) <WITH <
$(LDFLAGS)
TO djpeg$(SUFFIX)
FROM LIB:c.o $(DOBJECTS)
LIB libjpeg.lib $(LDLIBS)
<
jpegtran$(SUFFIX): $(TROBJECTS) libjpeg.lib
$(LN) <WITH <
$(LDFLAGS)
TO jpegtran$(SUFFIX)
FROM LIB:c.o $(TROBJECTS)
LIB libjpeg.lib $(LDLIBS)
<
rdjpgcom$(SUFFIX): rdjpgcom.o
$(LN) <WITH <
$(LDFLAGS)
TO rdjpgcom$(SUFFIX)
FROM LIB:c.o rdjpgcom.o
LIB $(LDLIBS)
<
wrjpgcom$(SUFFIX): wrjpgcom.o
$(LN) <WITH <
$(LDFLAGS)
TO wrjpgcom$(SUFFIX)
FROM LIB:c.o wrjpgcom.o
LIB $(LDLIBS)
<
jconfig.h: jconfig.txt
echo You must prepare a system-dependent jconfig.h file.
echo Please read the installation directions in install.txt.
exit 1
clean:
-$(RM) *.o cjpeg djpeg jpegtran cjpeg.030 djpeg.030 jpegtran.030
-$(RM) rdjpgcom wrjpgcom rdjpgcom.030 wrjpgcom.030
-$(RM) libjpeg.lib core testout*.*
test: cjpeg djpeg jpegtran
-$(RM) testout*.*
djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
cjpeg -dct int -outfile testout.jpg testimg.ppm
djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
jpegtran -outfile testoutt.jpg testprog.jpg
cmp testimg.ppm testout.ppm
cmp testimg.bmp testout.bmp
cmp testimg.jpg testout.jpg
cmp testimg.ppm testoutp.ppm
cmp testimgp.jpg testoutp.jpg
cmp testorig.jpg testoutt.jpg
jaricom.o: jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcapimin.o: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcapistd.o: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcarith.o: jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jccoefct.o: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jccolor.o: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcdctmgr.o: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jchuff.o: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcinit.o: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcmainct.o: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcmarker.o: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcmaster.o: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcomapi.o: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcparam.o: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcprepct.o: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcsample.o: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jctrans.o: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdapimin.o: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdapistd.o: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdarith.o: jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdatadst.o: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
jdatasrc.o: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
jdcoefct.o: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdcolor.o: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jddctmgr.o: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jdhuff.o: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdinput.o: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdmainct.o: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdmarker.o: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdmaster.o: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdmerge.o: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdpostct.o: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdsample.o: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdtrans.o: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jerror.o: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
jfdctflt.o: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jfdctfst.o: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jfdctint.o: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jidctflt.o: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jidctfst.o: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jidctint.o: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jquant1.o: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jquant2.o: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jutils.o: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jmemmgr.o: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
jmemansi.o: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
jmemname.o: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
jmemnobs.o: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
jmemdos.o: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
jmemmac.o: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
cjpeg.o: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
djpeg.o: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
jpegtran.o: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
rdjpgcom.o: rdjpgcom.c jinclude.h jconfig.h
wrjpgcom.o: wrjpgcom.c jinclude.h jconfig.h
cdjpeg.o: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdcolmap.o: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdswitch.o: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
transupp.o: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
rdppm.o: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
wrppm.o: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdgif.o: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
wrgif.o: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdtarga.o: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
wrtarga.o: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdbmp.o: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
wrbmp.o: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdrle.o: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
wrrle.o: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
|
1137519-player
|
jpeg-7/makefile.sas
|
SAS
|
lgpl
| 12,940
|
/* jconfig.sas --- jconfig.h for Amiga systems using SAS C 6.0 and up. */
/* see jconfig.txt for explanations */
#define HAVE_PROTOTYPES
#define HAVE_UNSIGNED_CHAR
#define HAVE_UNSIGNED_SHORT
/* #define void char */
/* #define const */
#undef CHAR_IS_UNSIGNED
#define HAVE_STDDEF_H
#define HAVE_STDLIB_H
#undef NEED_BSD_STRINGS
#undef NEED_SYS_TYPES_H
#undef NEED_FAR_POINTERS
#undef NEED_SHORT_EXTERNAL_NAMES
#undef INCOMPLETE_TYPES_BROKEN
#ifdef JPEG_INTERNALS
#undef RIGHT_SHIFT_IS_UNSIGNED
#define TEMP_DIRECTORY "JPEGTMP:" /* recommended setting for Amiga */
#define NO_MKTEMP /* SAS C doesn't have mktemp() */
#define SHORTxSHORT_32 /* produces better DCT code with SAS C */
#endif /* JPEG_INTERNALS */
#ifdef JPEG_CJPEG_DJPEG
#define BMP_SUPPORTED /* BMP image file format */
#define GIF_SUPPORTED /* GIF image file format */
#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
#undef RLE_SUPPORTED /* Utah RLE image file format */
#define TARGA_SUPPORTED /* Targa image file format */
#define TWO_FILE_COMMANDLINE
#define NEED_SIGNAL_CATCHER
#undef DONT_USE_B_MODE
#undef PROGRESS_REPORT /* optional */
#endif /* JPEG_CJPEG_DJPEG */
|
1137519-player
|
jpeg-7/jconfig.sas
|
SAS
|
lgpl
| 1,170
|
/*
* transupp.h
*
* Copyright (C) 1997-2001, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains declarations for image transformation routines and
* other utility code used by the jpegtran sample application. These are
* NOT part of the core JPEG library. But we keep these routines separate
* from jpegtran.c to ease the task of maintaining jpegtran-like programs
* that have other user interfaces.
*
* NOTE: all the routines declared here have very specific requirements
* about when they are to be executed during the reading and writing of the
* source and destination files. See the comments in transupp.c, or see
* jpegtran.c for an example of correct usage.
*/
/* If you happen not to want the image transform support, disable it here */
#ifndef TRANSFORMS_SUPPORTED
#define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
#endif
/*
* Although rotating and flipping data expressed as DCT coefficients is not
* hard, there is an asymmetry in the JPEG format specification for images
* whose dimensions aren't multiples of the iMCU size. The right and bottom
* image edges are padded out to the next iMCU boundary with junk data; but
* no padding is possible at the top and left edges. If we were to flip
* the whole image including the pad data, then pad garbage would become
* visible at the top and/or left, and real pixels would disappear into the
* pad margins --- perhaps permanently, since encoders & decoders may not
* bother to preserve DCT blocks that appear to be completely outside the
* nominal image area. So, we have to exclude any partial iMCUs from the
* basic transformation.
*
* Transpose is the only transformation that can handle partial iMCUs at the
* right and bottom edges completely cleanly. flip_h can flip partial iMCUs
* at the bottom, but leaves any partial iMCUs at the right edge untouched.
* Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
* The other transforms are defined as combinations of these basic transforms
* and process edge blocks in a way that preserves the equivalence.
*
* The "trim" option causes untransformable partial iMCUs to be dropped;
* this is not strictly lossless, but it usually gives the best-looking
* result for odd-size images. Note that when this option is active,
* the expected mathematical equivalences between the transforms may not hold.
* (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
* followed by -rot 180 -trim trims both edges.)
*
* We also offer a lossless-crop option, which discards data outside a given
* image region but losslessly preserves what is inside. Like the rotate and
* flip transforms, lossless crop is restricted by the JPEG format: the upper
* left corner of the selected region must fall on an iMCU boundary. If this
* does not hold for the given crop parameters, we silently move the upper left
* corner up and/or left to make it so, simultaneously increasing the region
* dimensions to keep the lower right crop corner unchanged. (Thus, the
* output image covers at least the requested region, but may cover more.)
*
* If both crop and a rotate/flip transform are requested, the crop is applied
* last --- that is, the crop region is specified in terms of the destination
* image.
*
* We also offer a "force to grayscale" option, which simply discards the
* chrominance channels of a YCbCr image. This is lossless in the sense that
* the luminance channel is preserved exactly. It's not the same kind of
* thing as the rotate/flip transformations, but it's convenient to handle it
* as part of this package, mainly because the transformation routines have to
* be aware of the option to know how many components to work on.
*/
/* Short forms of external names for systems with brain-damaged linkers. */
#ifdef NEED_SHORT_EXTERNAL_NAMES
#define jtransform_parse_crop_spec jTrParCrop
#define jtransform_request_workspace jTrRequest
#define jtransform_adjust_parameters jTrAdjust
#define jtransform_execute_transform jTrExec
#define jtransform_perfect_transform jTrPerfect
#define jcopy_markers_setup jCMrkSetup
#define jcopy_markers_execute jCMrkExec
#endif /* NEED_SHORT_EXTERNAL_NAMES */
/*
* Codes for supported types of image transformations.
*/
typedef enum {
JXFORM_NONE, /* no transformation */
JXFORM_FLIP_H, /* horizontal flip */
JXFORM_FLIP_V, /* vertical flip */
JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
JXFORM_ROT_90, /* 90-degree clockwise rotation */
JXFORM_ROT_180, /* 180-degree rotation */
JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
} JXFORM_CODE;
/*
* Codes for crop parameters, which can individually be unspecified,
* positive, or negative. (Negative width or height makes no sense, though.)
*/
typedef enum {
JCROP_UNSET,
JCROP_POS,
JCROP_NEG
} JCROP_CODE;
/*
* Transform parameters struct.
* NB: application must not change any elements of this struct after
* calling jtransform_request_workspace.
*/
typedef struct {
/* Options: set by caller */
JXFORM_CODE transform; /* image transform operator */
boolean perfect; /* if TRUE, fail if partial MCUs are requested */
boolean trim; /* if TRUE, trim partial MCUs as needed */
boolean force_grayscale; /* if TRUE, convert color image to grayscale */
boolean crop; /* if TRUE, crop source image */
/* Crop parameters: application need not set these unless crop is TRUE.
* These can be filled in by jtransform_parse_crop_spec().
*/
JDIMENSION crop_width; /* Width of selected region */
JCROP_CODE crop_width_set;
JDIMENSION crop_height; /* Height of selected region */
JCROP_CODE crop_height_set;
JDIMENSION crop_xoffset; /* X offset of selected region */
JCROP_CODE crop_xoffset_set; /* (negative measures from right edge) */
JDIMENSION crop_yoffset; /* Y offset of selected region */
JCROP_CODE crop_yoffset_set; /* (negative measures from bottom edge) */
/* Internal workspace: caller should not touch these */
int num_components; /* # of components in workspace */
jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
JDIMENSION output_width; /* cropped destination dimensions */
JDIMENSION output_height;
JDIMENSION x_crop_offset; /* destination crop offsets measured in iMCUs */
JDIMENSION y_crop_offset;
int max_h_samp_factor; /* destination iMCU size */
int max_v_samp_factor;
} jpeg_transform_info;
#if TRANSFORMS_SUPPORTED
/* Parse a crop specification (written in X11 geometry style) */
EXTERN(boolean) jtransform_parse_crop_spec
JPP((jpeg_transform_info *info, const char *spec));
/* Request any required workspace */
EXTERN(void) jtransform_request_workspace
JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
/* Adjust output image parameters */
EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
jvirt_barray_ptr *src_coef_arrays,
jpeg_transform_info *info));
/* Execute the actual transformation, if any */
EXTERN(void) jtransform_execute_transform
JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
jvirt_barray_ptr *src_coef_arrays,
jpeg_transform_info *info));
/* Determine whether lossless transformation is perfectly
* possible for a specified image and transformation.
*/
EXTERN(boolean) jtransform_perfect_transform
JPP((JDIMENSION image_width, JDIMENSION image_height,
int MCU_width, int MCU_height,
JXFORM_CODE transform));
/* jtransform_execute_transform used to be called
* jtransform_execute_transformation, but some compilers complain about
* routine names that long. This macro is here to avoid breaking any
* old source code that uses the original name...
*/
#define jtransform_execute_transformation jtransform_execute_transform
#endif /* TRANSFORMS_SUPPORTED */
/*
* Support for copying optional markers from source to destination file.
*/
typedef enum {
JCOPYOPT_NONE, /* copy no optional markers */
JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
JCOPYOPT_ALL /* copy all optional markers */
} JCOPY_OPTION;
#define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
/* Setup decompression object to save desired markers in memory */
EXTERN(void) jcopy_markers_setup
JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
/* Copy markers saved in the given source object to the destination object */
EXTERN(void) jcopy_markers_execute
JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
JCOPY_OPTION option));
|
1137519-player
|
jpeg-7/transupp.h
|
C
|
lgpl
| 8,751
|
/*
* wrjpgcom.c
*
* Copyright (C) 1994-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains a very simple stand-alone application that inserts
* user-supplied text as a COM (comment) marker in a JFIF file.
* This may be useful as an example of the minimum logic needed to parse
* JPEG markers.
*/
#define JPEG_CJPEG_DJPEG /* to get the command-line config symbols */
#include "jinclude.h" /* get auto-config symbols, <stdio.h> */
#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc() */
extern void * malloc ();
#endif
#include <ctype.h> /* to declare isupper(), tolower() */
#ifdef USE_SETMODE
#include <fcntl.h> /* to declare setmode()'s parameter macros */
/* If you have setmode() but not <io.h>, just delete this line: */
#include <io.h> /* to declare setmode() */
#endif
#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
#ifdef __MWERKS__
#include <SIOUX.h> /* Metrowerks needs this */
#include <console.h> /* ... and this */
#endif
#ifdef THINK_C
#include <console.h> /* Think declares it here */
#endif
#endif
#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
#define READ_BINARY "r"
#define WRITE_BINARY "w"
#else
#ifdef VMS /* VMS is very nonstandard */
#define READ_BINARY "rb", "ctx=stm"
#define WRITE_BINARY "wb", "ctx=stm"
#else /* standard ANSI-compliant case */
#define READ_BINARY "rb"
#define WRITE_BINARY "wb"
#endif
#endif
#ifndef EXIT_FAILURE /* define exit() codes if not provided */
#define EXIT_FAILURE 1
#endif
#ifndef EXIT_SUCCESS
#ifdef VMS
#define EXIT_SUCCESS 1 /* VMS is very nonstandard */
#else
#define EXIT_SUCCESS 0
#endif
#endif
/* Reduce this value if your malloc() can't allocate blocks up to 64K.
* On DOS, compiling in large model is usually a better solution.
*/
#ifndef MAX_COM_LENGTH
#define MAX_COM_LENGTH 65000L /* must be <= 65533 in any case */
#endif
/*
* These macros are used to read the input file and write the output file.
* To reuse this code in another application, you might need to change these.
*/
static FILE * infile; /* input JPEG file */
/* Return next input byte, or EOF if no more */
#define NEXTBYTE() getc(infile)
static FILE * outfile; /* output JPEG file */
/* Emit an output byte */
#define PUTBYTE(x) putc((x), outfile)
/* Error exit handler */
#define ERREXIT(msg) (fprintf(stderr, "%s\n", msg), exit(EXIT_FAILURE))
/* Read one byte, testing for EOF */
static int
read_1_byte (void)
{
int c;
c = NEXTBYTE();
if (c == EOF)
ERREXIT("Premature EOF in JPEG file");
return c;
}
/* Read 2 bytes, convert to unsigned int */
/* All 2-byte quantities in JPEG markers are MSB first */
static unsigned int
read_2_bytes (void)
{
int c1, c2;
c1 = NEXTBYTE();
if (c1 == EOF)
ERREXIT("Premature EOF in JPEG file");
c2 = NEXTBYTE();
if (c2 == EOF)
ERREXIT("Premature EOF in JPEG file");
return (((unsigned int) c1) << 8) + ((unsigned int) c2);
}
/* Routines to write data to output file */
static void
write_1_byte (int c)
{
PUTBYTE(c);
}
static void
write_2_bytes (unsigned int val)
{
PUTBYTE((val >> 8) & 0xFF);
PUTBYTE(val & 0xFF);
}
static void
write_marker (int marker)
{
PUTBYTE(0xFF);
PUTBYTE(marker);
}
static void
copy_rest_of_file (void)
{
int c;
while ((c = NEXTBYTE()) != EOF)
PUTBYTE(c);
}
/*
* JPEG markers consist of one or more 0xFF bytes, followed by a marker
* code byte (which is not an FF). Here are the marker codes of interest
* in this program. (See jdmarker.c for a more complete list.)
*/
#define M_SOF0 0xC0 /* Start Of Frame N */
#define M_SOF1 0xC1 /* N indicates which compression process */
#define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */
#define M_SOF3 0xC3
#define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */
#define M_SOF6 0xC6
#define M_SOF7 0xC7
#define M_SOF9 0xC9
#define M_SOF10 0xCA
#define M_SOF11 0xCB
#define M_SOF13 0xCD
#define M_SOF14 0xCE
#define M_SOF15 0xCF
#define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */
#define M_EOI 0xD9 /* End Of Image (end of datastream) */
#define M_SOS 0xDA /* Start Of Scan (begins compressed data) */
#define M_COM 0xFE /* COMment */
/*
* Find the next JPEG marker and return its marker code.
* We expect at least one FF byte, possibly more if the compressor used FFs
* to pad the file. (Padding FFs will NOT be replicated in the output file.)
* There could also be non-FF garbage between markers. The treatment of such
* garbage is unspecified; we choose to skip over it but emit a warning msg.
* NB: this routine must not be used after seeing SOS marker, since it will
* not deal correctly with FF/00 sequences in the compressed image data...
*/
static int
next_marker (void)
{
int c;
int discarded_bytes = 0;
/* Find 0xFF byte; count and skip any non-FFs. */
c = read_1_byte();
while (c != 0xFF) {
discarded_bytes++;
c = read_1_byte();
}
/* Get marker code byte, swallowing any duplicate FF bytes. Extra FFs
* are legal as pad bytes, so don't count them in discarded_bytes.
*/
do {
c = read_1_byte();
} while (c == 0xFF);
if (discarded_bytes != 0) {
fprintf(stderr, "Warning: garbage data found in JPEG file\n");
}
return c;
}
/*
* Read the initial marker, which should be SOI.
* For a JFIF file, the first two bytes of the file should be literally
* 0xFF M_SOI. To be more general, we could use next_marker, but if the
* input file weren't actually JPEG at all, next_marker might read the whole
* file and then return a misleading error message...
*/
static int
first_marker (void)
{
int c1, c2;
c1 = NEXTBYTE();
c2 = NEXTBYTE();
if (c1 != 0xFF || c2 != M_SOI)
ERREXIT("Not a JPEG file");
return c2;
}
/*
* Most types of marker are followed by a variable-length parameter segment.
* This routine skips over the parameters for any marker we don't otherwise
* want to process.
* Note that we MUST skip the parameter segment explicitly in order not to
* be fooled by 0xFF bytes that might appear within the parameter segment;
* such bytes do NOT introduce new markers.
*/
static void
copy_variable (void)
/* Copy an unknown or uninteresting variable-length marker */
{
unsigned int length;
/* Get the marker parameter length count */
length = read_2_bytes();
write_2_bytes(length);
/* Length includes itself, so must be at least 2 */
if (length < 2)
ERREXIT("Erroneous JPEG marker length");
length -= 2;
/* Skip over the remaining bytes */
while (length > 0) {
write_1_byte(read_1_byte());
length--;
}
}
static void
skip_variable (void)
/* Skip over an unknown or uninteresting variable-length marker */
{
unsigned int length;
/* Get the marker parameter length count */
length = read_2_bytes();
/* Length includes itself, so must be at least 2 */
if (length < 2)
ERREXIT("Erroneous JPEG marker length");
length -= 2;
/* Skip over the remaining bytes */
while (length > 0) {
(void) read_1_byte();
length--;
}
}
/*
* Parse the marker stream until SOFn or EOI is seen;
* copy data to output, but discard COM markers unless keep_COM is true.
*/
static int
scan_JPEG_header (int keep_COM)
{
int marker;
/* Expect SOI at start of file */
if (first_marker() != M_SOI)
ERREXIT("Expected SOI marker first");
write_marker(M_SOI);
/* Scan miscellaneous markers until we reach SOFn. */
for (;;) {
marker = next_marker();
switch (marker) {
/* Note that marker codes 0xC4, 0xC8, 0xCC are not, and must not be,
* treated as SOFn. C4 in particular is actually DHT.
*/
case M_SOF0: /* Baseline */
case M_SOF1: /* Extended sequential, Huffman */
case M_SOF2: /* Progressive, Huffman */
case M_SOF3: /* Lossless, Huffman */
case M_SOF5: /* Differential sequential, Huffman */
case M_SOF6: /* Differential progressive, Huffman */
case M_SOF7: /* Differential lossless, Huffman */
case M_SOF9: /* Extended sequential, arithmetic */
case M_SOF10: /* Progressive, arithmetic */
case M_SOF11: /* Lossless, arithmetic */
case M_SOF13: /* Differential sequential, arithmetic */
case M_SOF14: /* Differential progressive, arithmetic */
case M_SOF15: /* Differential lossless, arithmetic */
return marker;
case M_SOS: /* should not see compressed data before SOF */
ERREXIT("SOS without prior SOFn");
break;
case M_EOI: /* in case it's a tables-only JPEG stream */
return marker;
case M_COM: /* Existing COM: conditionally discard */
if (keep_COM) {
write_marker(marker);
copy_variable();
} else {
skip_variable();
}
break;
default: /* Anything else just gets copied */
write_marker(marker);
copy_variable(); /* we assume it has a parameter count... */
break;
}
} /* end loop */
}
/* Command line parsing code */
static const char * progname; /* program name for error messages */
static void
usage (void)
/* complain about bad command line */
{
fprintf(stderr, "wrjpgcom inserts a textual comment in a JPEG file.\n");
fprintf(stderr, "You can add to or replace any existing comment(s).\n");
fprintf(stderr, "Usage: %s [switches] ", progname);
#ifdef TWO_FILE_COMMANDLINE
fprintf(stderr, "inputfile outputfile\n");
#else
fprintf(stderr, "[inputfile]\n");
#endif
fprintf(stderr, "Switches (names may be abbreviated):\n");
fprintf(stderr, " -replace Delete any existing comments\n");
fprintf(stderr, " -comment \"text\" Insert comment with given text\n");
fprintf(stderr, " -cfile name Read comment from named file\n");
fprintf(stderr, "Notice that you must put quotes around the comment text\n");
fprintf(stderr, "when you use -comment.\n");
fprintf(stderr, "If you do not give either -comment or -cfile on the command line,\n");
fprintf(stderr, "then the comment text is read from standard input.\n");
fprintf(stderr, "It can be multiple lines, up to %u characters total.\n",
(unsigned int) MAX_COM_LENGTH);
#ifndef TWO_FILE_COMMANDLINE
fprintf(stderr, "You must specify an input JPEG file name when supplying\n");
fprintf(stderr, "comment text from standard input.\n");
#endif
exit(EXIT_FAILURE);
}
static int
keymatch (char * arg, const char * keyword, int minchars)
/* Case-insensitive matching of (possibly abbreviated) keyword switches. */
/* keyword is the constant keyword (must be lower case already), */
/* minchars is length of minimum legal abbreviation. */
{
register int ca, ck;
register int nmatched = 0;
while ((ca = *arg++) != '\0') {
if ((ck = *keyword++) == '\0')
return 0; /* arg longer than keyword, no good */
if (isupper(ca)) /* force arg to lcase (assume ck is already) */
ca = tolower(ca);
if (ca != ck)
return 0; /* no good */
nmatched++; /* count matched characters */
}
/* reached end of argument; fail if it's too short for unique abbrev */
if (nmatched < minchars)
return 0;
return 1; /* A-OK */
}
/*
* The main program.
*/
int
main (int argc, char **argv)
{
int argn;
char * arg;
int keep_COM = 1;
char * comment_arg = NULL;
FILE * comment_file = NULL;
unsigned int comment_length = 0;
int marker;
/* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
argc = ccommand(&argv);
#endif
progname = argv[0];
if (progname == NULL || progname[0] == 0)
progname = "wrjpgcom"; /* in case C library doesn't provide it */
/* Parse switches, if any */
for (argn = 1; argn < argc; argn++) {
arg = argv[argn];
if (arg[0] != '-')
break; /* not switch, must be file name */
arg++; /* advance over '-' */
if (keymatch(arg, "replace", 1)) {
keep_COM = 0;
} else if (keymatch(arg, "cfile", 2)) {
if (++argn >= argc) usage();
if ((comment_file = fopen(argv[argn], "r")) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
exit(EXIT_FAILURE);
}
} else if (keymatch(arg, "comment", 1)) {
if (++argn >= argc) usage();
comment_arg = argv[argn];
/* If the comment text starts with '"', then we are probably running
* under MS-DOG and must parse out the quoted string ourselves. Sigh.
*/
if (comment_arg[0] == '"') {
comment_arg = (char *) malloc((size_t) MAX_COM_LENGTH);
if (comment_arg == NULL)
ERREXIT("Insufficient memory");
strcpy(comment_arg, argv[argn]+1);
for (;;) {
comment_length = (unsigned int) strlen(comment_arg);
if (comment_length > 0 && comment_arg[comment_length-1] == '"') {
comment_arg[comment_length-1] = '\0'; /* zap terminating quote */
break;
}
if (++argn >= argc)
ERREXIT("Missing ending quote mark");
strcat(comment_arg, " ");
strcat(comment_arg, argv[argn]);
}
}
comment_length = (unsigned int) strlen(comment_arg);
} else
usage();
}
/* Cannot use both -comment and -cfile. */
if (comment_arg != NULL && comment_file != NULL)
usage();
/* If there is neither -comment nor -cfile, we will read the comment text
* from stdin; in this case there MUST be an input JPEG file name.
*/
if (comment_arg == NULL && comment_file == NULL && argn >= argc)
usage();
/* Open the input file. */
if (argn < argc) {
if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
exit(EXIT_FAILURE);
}
} else {
/* default input file is stdin */
#ifdef USE_SETMODE /* need to hack file mode? */
setmode(fileno(stdin), O_BINARY);
#endif
#ifdef USE_FDOPEN /* need to re-open in binary mode? */
if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open stdin\n", progname);
exit(EXIT_FAILURE);
}
#else
infile = stdin;
#endif
}
/* Open the output file. */
#ifdef TWO_FILE_COMMANDLINE
/* Must have explicit output file name */
if (argn != argc-2) {
fprintf(stderr, "%s: must name one input and one output file\n",
progname);
usage();
}
if ((outfile = fopen(argv[argn+1], WRITE_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, argv[argn+1]);
exit(EXIT_FAILURE);
}
#else
/* Unix style: expect zero or one file name */
if (argn < argc-1) {
fprintf(stderr, "%s: only one input file\n", progname);
usage();
}
/* default output file is stdout */
#ifdef USE_SETMODE /* need to hack file mode? */
setmode(fileno(stdout), O_BINARY);
#endif
#ifdef USE_FDOPEN /* need to re-open in binary mode? */
if ((outfile = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open stdout\n", progname);
exit(EXIT_FAILURE);
}
#else
outfile = stdout;
#endif
#endif /* TWO_FILE_COMMANDLINE */
/* Collect comment text from comment_file or stdin, if necessary */
if (comment_arg == NULL) {
FILE * src_file;
int c;
comment_arg = (char *) malloc((size_t) MAX_COM_LENGTH);
if (comment_arg == NULL)
ERREXIT("Insufficient memory");
comment_length = 0;
src_file = (comment_file != NULL ? comment_file : stdin);
while ((c = getc(src_file)) != EOF) {
if (comment_length >= (unsigned int) MAX_COM_LENGTH) {
fprintf(stderr, "Comment text may not exceed %u bytes\n",
(unsigned int) MAX_COM_LENGTH);
exit(EXIT_FAILURE);
}
comment_arg[comment_length++] = (char) c;
}
if (comment_file != NULL)
fclose(comment_file);
}
/* Copy JPEG headers until SOFn marker;
* we will insert the new comment marker just before SOFn.
* This (a) causes the new comment to appear after, rather than before,
* existing comments; and (b) ensures that comments come after any JFIF
* or JFXX markers, as required by the JFIF specification.
*/
marker = scan_JPEG_header(keep_COM);
/* Insert the new COM marker, but only if nonempty text has been supplied */
if (comment_length > 0) {
write_marker(M_COM);
write_2_bytes(comment_length + 2);
while (comment_length > 0) {
write_1_byte(*comment_arg++);
comment_length--;
}
}
/* Duplicate the remainder of the source file.
* Note that any COM markers occuring after SOF will not be touched.
*/
write_marker(marker);
copy_rest_of_file();
/* All done. */
exit(EXIT_SUCCESS);
return 0; /* suppress no-return-value warnings */
}
|
1137519-player
|
jpeg-7/wrjpgcom.c
|
C
|
lgpl
| 16,563
|
/* Copyright (C) 1989, 2000 Aladdin Enterprises. All rights reserved. */
/*$Id: ansi2knr.c,v 1.14 2003/09/06 05:36:56 eggert Exp $*/
/* Convert ANSI C function definitions to K&R ("traditional C") syntax */
/*
ansi2knr is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY. No author or distributor accepts responsibility to anyone for the
consequences of using it or for whether it serves any particular purpose or
works at all, unless he says so in writing. Refer to the GNU General Public
License (the "GPL") for full details.
Everyone is granted permission to copy, modify and redistribute ansi2knr,
but only under the conditions described in the GPL. A copy of this license
is supposed to have been given to you along with ansi2knr so you can know
your rights and responsibilities. It should be in a file named COPYLEFT,
or, if there is no file named COPYLEFT, a file named COPYING. Among other
things, the copyright notice and this notice must be preserved on all
copies.
We explicitly state here what we believe is already implied by the GPL: if
the ansi2knr program is distributed as a separate set of sources and a
separate executable file which are aggregated on a storage medium together
with another program, this in itself does not bring the other program under
the GPL, nor does the mere fact that such a program or the procedures for
constructing it invoke the ansi2knr executable bring any other part of the
program under the GPL.
*/
/*
* Usage:
ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]
* --filename provides the file name for the #line directive in the output,
* overriding input_file (if present).
* If no input_file is supplied, input is read from stdin.
* If no output_file is supplied, output goes to stdout.
* There are no error messages.
*
* ansi2knr recognizes function definitions by seeing a non-keyword
* identifier at the left margin, followed by a left parenthesis, with a
* right parenthesis as the last character on the line, and with a left
* brace as the first token on the following line (ignoring possible
* intervening comments and/or preprocessor directives), except that a line
* consisting of only
* identifier1(identifier2)
* will not be considered a function definition unless identifier2 is
* the word "void", and a line consisting of
* identifier1(identifier2, <<arbitrary>>)
* will not be considered a function definition.
* ansi2knr will recognize a multi-line header provided that no intervening
* line ends with a left or right brace or a semicolon. These algorithms
* ignore whitespace, comments, and preprocessor directives, except that
* the function name must be the first thing on the line. The following
* constructs will confuse it:
* - Any other construct that starts at the left margin and
* follows the above syntax (such as a macro or function call).
* - Some macros that tinker with the syntax of function headers.
*/
/*
* The original and principal author of ansi2knr is L. Peter Deutsch
* <ghost@aladdin.com>. Other authors are noted in the change history
* that follows (in reverse chronological order):
lpd 2000-04-12 backs out Eggert's changes because of bugs:
- concatlits didn't declare the type of its bufend argument;
- concatlits didn't recognize when it was inside a comment;
- scanstring could scan backward past the beginning of the string; when
- the check for \ + newline in scanstring was unnecessary.
2000-03-05 Paul Eggert <eggert@twinsun.com>
Add support for concatenated string literals.
* ansi2knr.c (concatlits): New decl.
(main): Invoke concatlits to concatenate string literals.
(scanstring): Handle backslash-newline correctly. Work with
character constants. Fix bug when scanning backwards through
backslash-quote. Check for unterminated strings.
(convert1): Parse character constants, too.
(appendline, concatlits): New functions.
* ansi2knr.1: Document this.
lpd 1999-08-17 added code to allow preprocessor directives
wherever comments are allowed
lpd 1999-04-12 added minor fixes from Pavel Roskin
<pavel_roskin@geocities.com> for clean compilation with
gcc -W -Wall
lpd 1999-03-22 added hack to recognize lines consisting of
identifier1(identifier2, xxx) as *not* being procedures
lpd 1999-02-03 made indentation of preprocessor commands consistent
lpd 1999-01-28 fixed two bugs: a '/' in an argument list caused an
endless loop; quoted strings within an argument list
confused the parser
lpd 1999-01-24 added a check for write errors on the output,
suggested by Jim Meyering <meyering@ascend.com>
lpd 1998-11-09 added further hack to recognize identifier(void)
as being a procedure
lpd 1998-10-23 added hack to recognize lines consisting of
identifier1(identifier2) as *not* being procedures
lpd 1997-12-08 made input_file optional; only closes input and/or
output file if not stdin or stdout respectively; prints
usage message on stderr rather than stdout; adds
--filename switch (changes suggested by
<ceder@lysator.liu.se>)
lpd 1996-01-21 added code to cope with not HAVE_CONFIG_H and with
compilers that don't understand void, as suggested by
Tom Lane
lpd 1996-01-15 changed to require that the first non-comment token
on the line following a function header be a left brace,
to reduce sensitivity to macros, as suggested by Tom Lane
<tgl@sss.pgh.pa.us>
lpd 1995-06-22 removed #ifndefs whose sole purpose was to define
undefined preprocessor symbols as 0; changed all #ifdefs
for configuration symbols to #ifs
lpd 1995-04-05 changed copyright notice to make it clear that
including ansi2knr in a program does not bring the entire
program under the GPL
lpd 1994-12-18 added conditionals for systems where ctype macros
don't handle 8-bit characters properly, suggested by
Francois Pinard <pinard@iro.umontreal.ca>;
removed --varargs switch (this is now the default)
lpd 1994-10-10 removed CONFIG_BROKETS conditional
lpd 1994-07-16 added some conditionals to help GNU `configure',
suggested by Francois Pinard <pinard@iro.umontreal.ca>;
properly erase prototype args in function parameters,
contributed by Jim Avera <jima@netcom.com>;
correct error in writeblanks (it shouldn't erase EOLs)
lpd 1989-xx-xx original version
*/
/* Most of the conditionals here are to make ansi2knr work with */
/* or without the GNU configure machinery. */
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <ctype.h>
#if HAVE_CONFIG_H
/*
For properly autoconfiguring ansi2knr, use AC_CONFIG_HEADER(config.h).
This will define HAVE_CONFIG_H and so, activate the following lines.
*/
# if STDC_HEADERS || HAVE_STRING_H
# include <string.h>
# else
# include <strings.h>
# endif
#else /* not HAVE_CONFIG_H */
/* Otherwise do it the hard way */
# ifdef BSD
# include <strings.h>
# else
# ifdef VMS
extern int strlen(), strncmp();
# else
# include <string.h>
# endif
# endif
#endif /* not HAVE_CONFIG_H */
#if STDC_HEADERS
# include <stdlib.h>
#else
/*
malloc and free should be declared in stdlib.h,
but if you've got a K&R compiler, they probably aren't.
*/
# ifdef MSDOS
# include <malloc.h>
# else
# ifdef VMS
extern char *malloc();
extern void free();
# else
extern char *malloc();
extern int free();
# endif
# endif
#endif
/* Define NULL (for *very* old compilers). */
#ifndef NULL
# define NULL (0)
#endif
/*
* The ctype macros don't always handle 8-bit characters correctly.
* Compensate for this here.
*/
#ifdef isascii
# undef HAVE_ISASCII /* just in case */
# define HAVE_ISASCII 1
#else
#endif
#if STDC_HEADERS || !HAVE_ISASCII
# define is_ascii(c) 1
#else
# define is_ascii(c) isascii(c)
#endif
#define is_space(c) (is_ascii(c) && isspace(c))
#define is_alpha(c) (is_ascii(c) && isalpha(c))
#define is_alnum(c) (is_ascii(c) && isalnum(c))
/* Scanning macros */
#define isidchar(ch) (is_alnum(ch) || (ch) == '_')
#define isidfirstchar(ch) (is_alpha(ch) || (ch) == '_')
/* Forward references */
char *ppdirforward();
char *ppdirbackward();
char *skipspace();
char *scanstring();
int writeblanks();
int test1();
int convert1();
/* The main program */
int
main(argc, argv)
int argc;
char *argv[];
{ FILE *in = stdin;
FILE *out = stdout;
char *filename = 0;
char *program_name = argv[0];
char *output_name = 0;
#define bufsize 5000 /* arbitrary size */
char *buf;
char *line;
char *more;
char *usage =
"Usage: ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]\n";
/*
* In previous versions, ansi2knr recognized a --varargs switch.
* If this switch was supplied, ansi2knr would attempt to convert
* a ... argument to va_alist and va_dcl; if this switch was not
* supplied, ansi2knr would simply drop any such arguments.
* Now, ansi2knr always does this conversion, and we only
* check for this switch for backward compatibility.
*/
int convert_varargs = 1;
int output_error;
while ( argc > 1 && argv[1][0] == '-' ) {
if ( !strcmp(argv[1], "--varargs") ) {
convert_varargs = 1;
argc--;
argv++;
continue;
}
if ( !strcmp(argv[1], "--filename") && argc > 2 ) {
filename = argv[2];
argc -= 2;
argv += 2;
continue;
}
fprintf(stderr, "%s: Unrecognized switch: %s\n", program_name,
argv[1]);
fprintf(stderr, usage);
exit(1);
}
switch ( argc )
{
default:
fprintf(stderr, usage);
exit(0);
case 3:
output_name = argv[2];
out = fopen(output_name, "w");
if ( out == NULL ) {
fprintf(stderr, "%s: Cannot open output file %s\n",
program_name, output_name);
exit(1);
}
/* falls through */
case 2:
in = fopen(argv[1], "r");
if ( in == NULL ) {
fprintf(stderr, "%s: Cannot open input file %s\n",
program_name, argv[1]);
exit(1);
}
if ( filename == 0 )
filename = argv[1];
/* falls through */
case 1:
break;
}
if ( filename )
fprintf(out, "#line 1 \"%s\"\n", filename);
buf = malloc(bufsize);
if ( buf == NULL )
{
fprintf(stderr, "Unable to allocate read buffer!\n");
exit(1);
}
line = buf;
while ( fgets(line, (unsigned)(buf + bufsize - line), in) != NULL )
{
test: line += strlen(line);
switch ( test1(buf) )
{
case 2: /* a function header */
convert1(buf, out, 1, convert_varargs);
break;
case 1: /* a function */
/* Check for a { at the start of the next line. */
more = ++line;
f: if ( line >= buf + (bufsize - 1) ) /* overflow check */
goto wl;
if ( fgets(line, (unsigned)(buf + bufsize - line), in) == NULL )
goto wl;
switch ( *skipspace(ppdirforward(more), 1) )
{
case '{':
/* Definitely a function header. */
convert1(buf, out, 0, convert_varargs);
fputs(more, out);
break;
case 0:
/* The next line was blank or a comment: */
/* keep scanning for a non-comment. */
line += strlen(line);
goto f;
default:
/* buf isn't a function header, but */
/* more might be. */
fputs(buf, out);
strcpy(buf, more);
line = buf;
goto test;
}
break;
case -1: /* maybe the start of a function */
if ( line != buf + (bufsize - 1) ) /* overflow check */
continue;
/* falls through */
default: /* not a function */
wl: fputs(buf, out);
break;
}
line = buf;
}
if ( line != buf )
fputs(buf, out);
free(buf);
if ( output_name ) {
output_error = ferror(out);
output_error |= fclose(out);
} else { /* out == stdout */
fflush(out);
output_error = ferror(out);
}
if ( output_error ) {
fprintf(stderr, "%s: error writing to %s\n", program_name,
(output_name ? output_name : "stdout"));
exit(1);
}
if ( in != stdin )
fclose(in);
return 0;
}
/*
* Skip forward or backward over one or more preprocessor directives.
*/
char *
ppdirforward(p)
char *p;
{
for (; *p == '#'; ++p) {
for (; *p != '\r' && *p != '\n'; ++p)
if (*p == 0)
return p;
if (*p == '\r' && p[1] == '\n')
++p;
}
return p;
}
char *
ppdirbackward(p, limit)
char *p;
char *limit;
{
char *np = p;
for (;; p = --np) {
if (*np == '\n' && np[-1] == '\r')
--np;
for (; np > limit && np[-1] != '\r' && np[-1] != '\n'; --np)
if (np[-1] == 0)
return np;
if (*np != '#')
return p;
}
}
/*
* Skip over whitespace, comments, and preprocessor directives,
* in either direction.
*/
char *
skipspace(p, dir)
char *p;
int dir; /* 1 for forward, -1 for backward */
{
for ( ; ; ) {
while ( is_space(*p) )
p += dir;
if ( !(*p == '/' && p[dir] == '*') )
break;
p += dir; p += dir;
while ( !(*p == '*' && p[dir] == '/') ) {
if ( *p == 0 )
return p; /* multi-line comment?? */
p += dir;
}
p += dir; p += dir;
}
return p;
}
/* Scan over a quoted string, in either direction. */
char *
scanstring(p, dir)
char *p;
int dir;
{
for (p += dir; ; p += dir)
if (*p == '"' && p[-dir] != '\\')
return p + dir;
}
/*
* Write blanks over part of a string.
* Don't overwrite end-of-line characters.
*/
int
writeblanks(start, end)
char *start;
char *end;
{ char *p;
for ( p = start; p < end; p++ )
if ( *p != '\r' && *p != '\n' )
*p = ' ';
return 0;
}
/*
* Test whether the string in buf is a function definition.
* The string may contain and/or end with a newline.
* Return as follows:
* 0 - definitely not a function definition;
* 1 - definitely a function definition;
* 2 - definitely a function prototype (NOT USED);
* -1 - may be the beginning of a function definition,
* append another line and look again.
* The reason we don't attempt to convert function prototypes is that
* Ghostscript's declaration-generating macros look too much like
* prototypes, and confuse the algorithms.
*/
int
test1(buf)
char *buf;
{ char *p = buf;
char *bend;
char *endfn;
int contin;
if ( !isidfirstchar(*p) )
return 0; /* no name at left margin */
bend = skipspace(ppdirbackward(buf + strlen(buf) - 1, buf), -1);
switch ( *bend )
{
case ';': contin = 0 /*2*/; break;
case ')': contin = 1; break;
case '{': return 0; /* not a function */
case '}': return 0; /* not a function */
default: contin = -1;
}
while ( isidchar(*p) )
p++;
endfn = p;
p = skipspace(p, 1);
if ( *p++ != '(' )
return 0; /* not a function */
p = skipspace(p, 1);
if ( *p == ')' )
return 0; /* no parameters */
/* Check that the apparent function name isn't a keyword. */
/* We only need to check for keywords that could be followed */
/* by a left parenthesis (which, unfortunately, is most of them). */
{ static char *words[] =
{ "asm", "auto", "case", "char", "const", "double",
"extern", "float", "for", "if", "int", "long",
"register", "return", "short", "signed", "sizeof",
"static", "switch", "typedef", "unsigned",
"void", "volatile", "while", 0
};
char **key = words;
char *kp;
unsigned len = endfn - buf;
while ( (kp = *key) != 0 )
{ if ( strlen(kp) == len && !strncmp(kp, buf, len) )
return 0; /* name is a keyword */
key++;
}
}
{
char *id = p;
int len;
/*
* Check for identifier1(identifier2) and not
* identifier1(void), or identifier1(identifier2, xxxx).
*/
while ( isidchar(*p) )
p++;
len = p - id;
p = skipspace(p, 1);
if (*p == ',' ||
(*p == ')' && (len != 4 || strncmp(id, "void", 4)))
)
return 0; /* not a function */
}
/*
* If the last significant character was a ), we need to count
* parentheses, because it might be part of a formal parameter
* that is a procedure.
*/
if (contin > 0) {
int level = 0;
for (p = skipspace(buf, 1); *p; p = skipspace(p + 1, 1))
level += (*p == '(' ? 1 : *p == ')' ? -1 : 0);
if (level > 0)
contin = -1;
}
return contin;
}
/* Convert a recognized function definition or header to K&R syntax. */
int
convert1(buf, out, header, convert_varargs)
char *buf;
FILE *out;
int header; /* Boolean */
int convert_varargs; /* Boolean */
{ char *endfn;
char *p;
/*
* The breaks table contains pointers to the beginning and end
* of each argument.
*/
char **breaks;
unsigned num_breaks = 2; /* for testing */
char **btop;
char **bp;
char **ap;
char *vararg = 0;
/* Pre-ANSI implementations don't agree on whether strchr */
/* is called strchr or index, so we open-code it here. */
for ( endfn = buf; *(endfn++) != '('; )
;
top: p = endfn;
breaks = (char **)malloc(sizeof(char *) * num_breaks * 2);
if ( breaks == NULL )
{ /* Couldn't allocate break table, give up */
fprintf(stderr, "Unable to allocate break table!\n");
fputs(buf, out);
return -1;
}
btop = breaks + num_breaks * 2 - 2;
bp = breaks;
/* Parse the argument list */
do
{ int level = 0;
char *lp = NULL;
char *rp = NULL;
char *end = NULL;
if ( bp >= btop )
{ /* Filled up break table. */
/* Allocate a bigger one and start over. */
free((char *)breaks);
num_breaks <<= 1;
goto top;
}
*bp++ = p;
/* Find the end of the argument */
for ( ; end == NULL; p++ )
{ switch(*p)
{
case ',':
if ( !level ) end = p;
break;
case '(':
if ( !level ) lp = p;
level++;
break;
case ')':
if ( --level < 0 ) end = p;
else rp = p;
break;
case '/':
if (p[1] == '*')
p = skipspace(p, 1) - 1;
break;
case '"':
p = scanstring(p, 1) - 1;
break;
default:
;
}
}
/* Erase any embedded prototype parameters. */
if ( lp && rp )
writeblanks(lp + 1, rp);
p--; /* back up over terminator */
/* Find the name being declared. */
/* This is complicated because of procedure and */
/* array modifiers. */
for ( ; ; )
{ p = skipspace(p - 1, -1);
switch ( *p )
{
case ']': /* skip array dimension(s) */
case ')': /* skip procedure args OR name */
{ int level = 1;
while ( level )
switch ( *--p )
{
case ']': case ')':
level++;
break;
case '[': case '(':
level--;
break;
case '/':
if (p > buf && p[-1] == '*')
p = skipspace(p, -1) + 1;
break;
case '"':
p = scanstring(p, -1) + 1;
break;
default: ;
}
}
if ( *p == '(' && *skipspace(p + 1, 1) == '*' )
{ /* We found the name being declared */
while ( !isidfirstchar(*p) )
p = skipspace(p, 1) + 1;
goto found;
}
break;
default:
goto found;
}
}
found: if ( *p == '.' && p[-1] == '.' && p[-2] == '.' )
{ if ( convert_varargs )
{ *bp++ = "va_alist";
vararg = p-2;
}
else
{ p++;
if ( bp == breaks + 1 ) /* sole argument */
writeblanks(breaks[0], p);
else
writeblanks(bp[-1] - 1, p);
bp--;
}
}
else
{ while ( isidchar(*p) ) p--;
*bp++ = p+1;
}
p = end;
}
while ( *p++ == ',' );
*bp = p;
/* Make a special check for 'void' arglist */
if ( bp == breaks+2 )
{ p = skipspace(breaks[0], 1);
if ( !strncmp(p, "void", 4) )
{ p = skipspace(p+4, 1);
if ( p == breaks[2] - 1 )
{ bp = breaks; /* yup, pretend arglist is empty */
writeblanks(breaks[0], p + 1);
}
}
}
/* Put out the function name and left parenthesis. */
p = buf;
while ( p != endfn ) putc(*p, out), p++;
/* Put out the declaration. */
if ( header )
{ fputs(");", out);
for ( p = breaks[0]; *p; p++ )
if ( *p == '\r' || *p == '\n' )
putc(*p, out);
}
else
{ for ( ap = breaks+1; ap < bp; ap += 2 )
{ p = *ap;
while ( isidchar(*p) )
putc(*p, out), p++;
if ( ap < bp - 1 )
fputs(", ", out);
}
fputs(") ", out);
/* Put out the argument declarations */
for ( ap = breaks+2; ap <= bp; ap += 2 )
(*ap)[-1] = ';';
if ( vararg != 0 )
{ *vararg = 0;
fputs(breaks[0], out); /* any prior args */
fputs("va_dcl", out); /* the final arg */
fputs(bp[0], out);
}
else
fputs(breaks[0], out);
}
free((char *)breaks);
return 0;
}
|
1137519-player
|
jpeg-7/ansi2knr.c
|
C
|
lgpl
| 20,271
|
# Makefile for Independent JPEG Group's software
# This makefile is suitable for Watcom C/C++ 10.0 on MS-DOS (using
# dos4g extender), OS/2, and Windows NT console mode.
# Thanks to Janos Haide, jhaide@btrvtech.com.
# Read installation instructions before saying "wmake" !!
# Uncomment line for desired system
SYSTEM=DOS
#SYSTEM=OS2
#SYSTEM=NT
# The name of your C compiler:
CC= wcl386
# You may need to adjust these cc options:
CFLAGS= -4r -ort -wx -zq -bt=$(SYSTEM)
# Caution: avoid -ol or -ox; these generate bad code with 10.0 or 10.0a.
# Generally, we recommend defining any configuration symbols in jconfig.h,
# NOT via -D switches here.
# Link-time cc options:
!ifeq SYSTEM DOS
LDFLAGS= -zq -l=dos4g
!else ifeq SYSTEM OS2
LDFLAGS= -zq -l=os2v2
!else ifeq SYSTEM NT
LDFLAGS= -zq -l=nt
!endif
# Put here the object file name for the correct system-dependent memory
# manager file. jmemnobs should work fine for dos4g or OS/2 environment.
SYSDEPMEM= jmemnobs.obj
# End of configurable options.
# source files: JPEG library proper
LIBSOURCES= jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c &
jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c &
jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c &
jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c &
jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c &
jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c &
jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c &
jquant2.c jutils.c jmemmgr.c
# memmgr back ends: compile only one of these into a working library
SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c &
rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c &
rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
# files included by source files
INCLUDES= jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h jpegint.h &
jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
# documentation, test, and support files
DOCS= README install.txt usage.txt cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 &
wrjpgcom.1 wizard.txt example.c libjpeg.txt structure.txt &
coderules.txt filelist.txt change.log
MKFILES= configure Makefile.in makefile.ansi makefile.unix makefile.bcc &
makefile.mc6 makefile.dj makefile.wat makefile.vc makejdsw.vc6 &
makeadsw.vc6 makejdep.vc6 makejdsp.vc6 makejmak.vc6 makecdep.vc6 &
makecdsp.vc6 makecmak.vc6 makeddep.vc6 makeddsp.vc6 makedmak.vc6 &
maketdep.vc6 maketdsp.vc6 maketmak.vc6 makerdep.vc6 makerdsp.vc6 &
makermak.vc6 makewdep.vc6 makewdsp.vc6 makewmak.vc6 makejsln.vc9 &
makeasln.vc9 makejvcp.vc9 makecvcp.vc9 makedvcp.vc9 maketvcp.vc9 &
makervcp.vc9 makewvcp.vc9 makeproj.mac makcjpeg.st makdjpeg.st &
makljpeg.st maktjpeg.st makefile.manx makefile.sas makefile.mms &
makefile.vms makvms.opt
CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat &
jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas &
jconfig.vms
CONFIGUREFILES= config.guess config.sub install-sh ltmain.sh depcomp missing
OTHERFILES= jconfig.txt ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm &
libjpeg.map
TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg &
testimgp.jpg
DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) &
$(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
# library object files common to compression and decompression
COMOBJECTS= jaricom.obj jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM)
# compression library object files
CLIBOBJECTS= jcapimin.obj jcapistd.obj jcarith.obj jctrans.obj jcparam.obj &
jdatadst.obj jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj &
jcprepct.obj jccoefct.obj jccolor.obj jcsample.obj jchuff.obj &
jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj
# decompression library object files
DLIBOBJECTS= jdapimin.obj jdapistd.obj jdarith.obj jdtrans.obj jdatasrc.obj &
jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdmainct.obj &
jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj jidctflt.obj &
jidctint.obj jdsample.obj jdcolor.obj jquant1.obj jquant2.obj &
jdmerge.obj
# These objectfiles are included in libjpeg.lib
LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
# object files for sample applications (excluding library files)
COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj &
rdswitch.obj cdjpeg.obj
DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj &
rdcolmap.obj cdjpeg.obj
TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj
all: libjpeg.lib cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe
libjpeg.lib: $(LIBOBJECTS)
- del libjpeg.lib
* wlib -n libjpeg.lib $(LIBOBJECTS)
cjpeg.exe: $(COBJECTS) libjpeg.lib
$(CC) $(LDFLAGS) $(COBJECTS) libjpeg.lib
djpeg.exe: $(DOBJECTS) libjpeg.lib
$(CC) $(LDFLAGS) $(DOBJECTS) libjpeg.lib
jpegtran.exe: $(TROBJECTS) libjpeg.lib
$(CC) $(LDFLAGS) $(TROBJECTS) libjpeg.lib
rdjpgcom.exe: rdjpgcom.c
$(CC) $(CFLAGS) $(LDFLAGS) rdjpgcom.c
wrjpgcom.exe: wrjpgcom.c
$(CC) $(CFLAGS) $(LDFLAGS) wrjpgcom.c
.c.obj:
$(CC) $(CFLAGS) -c $<
jconfig.h: jconfig.txt
echo You must prepare a system-dependent jconfig.h file.
echo Please read the installation directions in install.txt.
exit 1
clean: .SYMBOLIC
- del *.obj
- del libjpeg.lib
- del cjpeg.exe
- del djpeg.exe
- del jpegtran.exe
- del rdjpgcom.exe
- del wrjpgcom.exe
- del testout*.*
test: cjpeg.exe djpeg.exe jpegtran.exe .SYMBOLIC
- del testout*.*
djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
cjpeg -dct int -outfile testout.jpg testimg.ppm
djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
jpegtran -outfile testoutt.jpg testprog.jpg
!ifeq SYSTEM DOS
fc /b testimg.ppm testout.ppm
fc /b testimg.bmp testout.bmp
fc /b testimg.jpg testout.jpg
fc /b testimg.ppm testoutp.ppm
fc /b testimgp.jpg testoutp.jpg
fc /b testorig.jpg testoutt.jpg
!else
echo n > n.tmp
comp testimg.ppm testout.ppm < n.tmp
comp testimg.bmp testout.bmp < n.tmp
comp testimg.jpg testout.jpg < n.tmp
comp testimg.ppm testoutp.ppm < n.tmp
comp testimgp.jpg testoutp.jpg < n.tmp
comp testorig.jpg testoutt.jpg < n.tmp
del n.tmp
!endif
jaricom.obj: jaricom.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcapimin.obj: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcapistd.obj: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcarith.obj: jcarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jccoefct.obj: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jccolor.obj: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcdctmgr.obj: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jchuff.obj: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcinit.obj: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcmainct.obj: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcmarker.obj: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcomapi.obj: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcparam.obj: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcprepct.obj: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jcsample.obj: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jctrans.obj: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdapimin.obj: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdapistd.obj: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdarith.obj: jdarith.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdatadst.obj: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
jdatasrc.obj: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
jdcoefct.obj: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jddctmgr.obj: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdinput.obj: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdmainct.obj: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdmarker.obj: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdmerge.obj: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdpostct.obj: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdsample.obj: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jdtrans.obj: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jerror.obj: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
jfdctflt.obj: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jfdctfst.obj: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jfdctint.obj: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jidctflt.obj: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jidctfst.obj: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jidctint.obj: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
jquant1.obj: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jquant2.obj: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jutils.obj: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
jmemmgr.obj: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
jmemansi.obj: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
jmemname.obj: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
jmemnobs.obj: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
jmemdos.obj: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
jmemmac.obj: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
cjpeg.obj: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
djpeg.obj: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
jpegtran.obj: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
rdjpgcom.obj: rdjpgcom.c jinclude.h jconfig.h
wrjpgcom.obj: wrjpgcom.c jinclude.h jconfig.h
cdjpeg.obj: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdcolmap.obj: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdswitch.obj: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
transupp.obj: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
rdppm.obj: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
wrppm.obj: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdgif.obj: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
wrgif.obj: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdtarga.obj: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
wrtarga.obj: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdbmp.obj: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
wrbmp.obj: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
rdrle.obj: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
wrrle.obj: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
|
1137519-player
|
jpeg-7/makefile.wat
|
WebAssembly
|
lgpl
| 12,775
|
; Project file for Independent JPEG Group's software
;
; This project file is for Atari ST/STE/TT systems using Pure C or Turbo C.
; Thanks to Frank Moehle, B. Setzepfandt, and Guido Vollbeding.
;
; To use this file, rename it to djpeg.prj.
; If you are using Turbo C, change filenames beginning with "pc..." to "tc..."
; Read installation instructions before trying to make the program!
;
;
; * * * Output file * * *
djpeg.ttp
;
; * * * COMPILER OPTIONS * * *
.C[-P] ; absolute calls
.C[-M] ; and no string merging, folks
.C[-w-cln] ; no "constant is long" warnings
.C[-w-par] ; no "parameter xxxx unused"
.C[-w-rch] ; no "unreachable code"
.C[-wsig] ; warn if significant digits may be lost
=
; * * * * List of modules * * * *
pcstart.o
djpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h,jversion.h)
cdjpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
rdcolmap.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
wrppm.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
wrgif.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
wrtarga.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
wrbmp.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
wrrle.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
libjpeg.lib ; built by libjpeg.prj
pcfltlib.lib ; floating point library
; the float library can be omitted if you've turned off DCT_FLOAT_SUPPORTED
pcstdlib.lib ; standard library
pcextlib.lib ; extended library
|
1137519-player
|
jpeg-7/makdjpeg.st
|
Smalltalk
|
lgpl
| 1,674
|
/*
* mjpeg.h
*
* Created on: 2011/07/10
* Author: Tonsuke
*/
#ifndef MJPEG_H_
#define MJPEG_H_
#include "stm32f4xx_conf.h"
#include <stddef.h>
#include "fat.h"
#include "mpool.h"
MY_FILE fp_global;
struct {
int buf_type;
uint32_t frame_size;
}jpeg_read;
#define CMARK 0xA9
static uint8_t atomHasChild[] = {0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0 ,0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
#define ATOM_ITEMS (sizeof(atomHasChild) / sizeof(atomHasChild[0]))
static const uint8_t atomTypeString[ATOM_ITEMS][5] =
{
"ftyp", // -
"wide", // -
"mdat", // -
"moov", // +
"mvhd", // -
"trak", // +
"tkhd", // -
"tapt", // +
"clef", // -
"prof", // -
"enof", // -
"edts", // +
"elst", // -
"mdia", // +
"mdhd", // -
"hdlr", // -
"minf", // +
"vmhd", // -
"smhd", // -
"dinf", // +
"dref", // -
"stbl", // +
"stsd", // -
"stts", // -
"stsc", // -
"stsz", // -
"stco", // -
"udta", // +
"free", // -
"skip", // -
"meta", // +
"load", // -
"iods", // -
"ilst", // +
"keys", // -
"data", // -
"trkn", // +
"disk", // +
"cpil", // +
"pgap", // +
"tmpo", // +
"gnre", // +
"covr", // -
{CMARK, 'n', 'a', 'm', '\0'}, // -
{CMARK, 'A', 'R', 'T', '\0'}, // -
{CMARK, 'a', 'l', 'b', '\0'}, // -
{CMARK, 'g', 'e', 'n', '\0'}, // -
{CMARK, 'd', 'a', 'y', '\0'}, // -
{CMARK, 't', 'o', 'o', '\0'}, // -
{CMARK, 'w', 'r', 't', '\0'}, // -
"----", // -
};
enum AtomEnum {
FTYP, // -
WIDE, // -
MDAT, // -
MOOV, // +
MVHD, // -
TRAK, // +
TKHD, // -
TAPT, // +
CLEF, // -
PROF, // -
ENOF, // -
EDTS, // +
ELST, // -
MDIA, // +
MDHD, // -
HDLR, // -
MINF, // +
VMHD, // -
SMHD, // -
DINF, // +
DREF, // -
STBL, // +
STSD, // -
STTS, // -
STSC, // -
STSZ, // -
STCO, // -
UDTA, // +
FREE, // -
SKIP, // -
META, // +
LOAD, // -
IODS, // -
ILST, // +
KEYS, // -
DATA, // -
TRKN, // +
DISK, // +
CPIL, // +
PGAP, // +
TMPO, // +
GNRE, // +
COVR, // -
CNAM, // -
CART, // -
CALB, // -
CGEN, // -
CDAY, // -
CTOO, // -
CWRT, // -
NONE, // -
};
volatile struct {
int8_t id, \
done, \
resynch, \
draw_icon;
uint32_t paused_chunk, \
resynch_entry;
} mjpeg_touch;
struct {
uint32_t *firstChunk, *prevChunk, *prevSamples, *samples, *totalSamples, *videoStcoCount;
MY_FILE *fp_video_stsc, *fp_video_stsz, *fp_video_stco, *fp_frame;
} pv_src;
struct {
uint32_t *firstChunk, *prevChunk, *prevSamples, *samples, *soundStcoCount;
MY_FILE *fp_sound_stsc, *fp_sound_stsz, *fp_sound_stco;
} ps_src;
struct{
uint32_t numEntry;
MY_FILE fp;
} sound_stts;
struct{
uint32_t numEntry;
MY_FILE fp;
} sound_stsc;
struct{
uint32_t sampleSize,
numEntry;
MY_FILE fp;
} sound_stsz;
struct{
uint32_t numEntry;
MY_FILE fp;
} sound_stco;
struct{
uint32_t numEntry;
MY_FILE fp;
} video_stts;
struct{
uint32_t numEntry;
MY_FILE fp;
} video_stsc;
struct{
uint32_t sampleSize,
numEntry;
MY_FILE fp;
} video_stsz;
struct{
uint32_t numEntry;
MY_FILE fp;
} video_stco;
typedef struct samples_struct{
uint32_t numEntry;
MY_FILE *fp;
} samples_struct;
typedef struct sound_flag{
uint32_t process, complete;
} sound_flag;
typedef struct video_flag{
uint32_t process, complete;
} video_flag;
typedef struct sound_format{
char audioFmtString[4];
uint8_t reserved[10];
uint16_t version,
revision,
vendor,
numChannel,
sampleSize,
complesionID,
packetSize,
sampleRate,
reserved1;
} sound_format;
typedef struct esds_format{
char esdsString[4];
// uint8_t reserved[22];
uint32_t maxBitrate, avgBitrate;
} esds_format;
typedef struct media_sound{
sound_flag flag;
sound_format format;
uint32_t timeScale,
duration;
} media_sound;
typedef struct media_video{
video_flag flag;
uint32_t timeScale,
duration;
int16_t width, height, frameRate, startPosX, startPosY;
char videoFmtString[5], videoCmpString[15], playJpeg;
} media_video;
volatile struct{
media_sound sound;
media_video video;
} media;
typedef struct {
int output_scanline, frame_size, rasters, buf_size;
uint16_t *p_raster;
} raw_video_typedef;
/* --- TIM1 SR Register ---*/
/* Alias word address of TIM1 SR UIF bit */
#define TIM1_SR_OFFSET (TIM1_BASE + 0x10)
#define TIM1_SR_UIF_BitNumber 0x00
#define TIM1_SR_UIF_BB (*(uint32_t *)(PERIPH_BB_BASE + (TIM1_SR_OFFSET * 32) + (TIM1_SR_UIF_BitNumber * 4)))
/* --- TIM3 CR1 Register ---*/
/* Alias word address of TIM3 CR1 CEN bit */
#define TIM3_CR1_OFFSET (TIM3_BASE + 0x00)
#define TIM3_CR1_CEN_BitNumber 0x00
#define TIM3_CR1_CEN_BB (*(uint32_t *)(PERIPH_BB_BASE + (TIM3_CR1_OFFSET * 32) + (TIM3_CR1_CEN_BitNumber * 4)))
/* --- TIM3 DIER Register ---*/
/* Alias word address of TIM3 DIER UIE bit */
#define TIM3_DIER_OFFSET (TIM3_BASE + 0x0C)
#define TIM3_DIER_UIE_BitNumber 0x00
#define TIM3_DIER_UIE_BB (*(uint32_t *)(PERIPH_BB_BASE + (TIM3_DIER_OFFSET * 32) + (TIM3_DIER_UIE_BitNumber * 4)))
/* --- TIM3 SR Register ---*/
/* Alias word address of TIM3 SR UIF bit */
#define TIM3_SR_OFFSET (TIM3_BASE + 0x10)
#define TIM3_SR_UIF_BitNumber 0x00
#define TIM3_SR_UIF_BB (*(uint32_t *)(PERIPH_BB_BASE + (TIM3_SR_OFFSET * 32) + (TIM3_SR_UIF_BitNumber * 4)))
extern uint32_t b2l(void* val, size_t t);
//inline uint32_t getAtomSize(void* atom);
extern int PlayMotionJpeg(int id);
/*
typedef struct
{
uint8_t mem[50000];
}ExtJpgMem_TypeDef;
#define JPG ((ExtJpgMem_TypeDef*)(0x600030C0))
*/
#endif /* MJPEG_H_ */
|
1137519-player
|
mjpeg.h
|
C
|
lgpl
| 5,585
|
/*
* djpeg.h
*
* Created on: 2012/12/25
* Author: masayuki
*/
#ifndef DJPEG_H_
#define DJPEG_H_
#define DJPEG_PLAY (1 << 2)
#define DJPEG_ARROW_LEFT (1 << 1)
#define DJPEG_ARROW_RIGHT (1 << 0)
extern int dojpeg(int id, uint8_t djpeg_arrows, uint8_t arrow_clicked);
#endif /* DJPEG_H_ */
|
1137519-player
|
dojpeg.h
|
C
|
lgpl
| 312
|
/*
* usart.h
*
* Created on: 2011/02/22
* Author: masayuki
*/
#ifndef USART_H_
#define USART_H_
#include "stm32f4xx_conf.h"
#define CURSOR_LEFT 0x01
#define CURSOR_RIGHT 0x06
#define CURSOR_UP 0x10
#define CURSOR_DOWN 0x0e
#define CURSOR_ENTER 0x0D
#define USART_IRQ_ENABLE USART_ITConfig(USART3, USART_IT_RXNE, ENABLE)
#define USART_IRQ_DISABLE USART_ITConfig(USART3, USART_IT_RXNE, DISABLE)
volatile struct {
int (*printf)(const char *, ...);
} debug;
extern void USARTInit(void);
extern void USARTPutData(uint16_t x);
extern void USARTPutChar(void *c);
extern void USARTPutString(const char *str);
extern void USARTPutNChar(void *str, uint32_t n);
int USARTPrintf(const char *fmt, ...);
#endif /* USART_H_ */
|
1137519-player
|
usart.h
|
C
|
lgpl
| 739
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: trigtabs_fltgen.c,v 1.2 2006/12/05 03:36:53 ehyche Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com), Ken Cooke (kenc@real.com)
* June 2005
*
* trigtabs_fltgen.c - low-ROM alternative to trigtabs.c
* generates large trig tables at runtime using floating-point
* math library
* MUST VERIFY that runtime-generated tables are bit-exact matches
* with ROM tables in trigtabs.c
**************************************************************************************/
#ifdef HELIX_CONFIG_AAC_GENERATE_TRIGTABS_FLOAT
#include <math.h>
#include "coder.h"
/* read-only tables */
const int cos4sin4tabOffset[NUM_IMDCT_SIZES] = {0, 128};
const int sinWindowOffset[NUM_IMDCT_SIZES] = {0, 128};
const int kbdWindowOffset[NUM_IMDCT_SIZES] = {0, 128};
const int bitrevtabOffset[NUM_IMDCT_SIZES] = {0, 17};
const unsigned char bitrevtab[17 + 129] = {
/* nfft = 64 */
0x01, 0x08, 0x02, 0x04, 0x03, 0x0c, 0x05, 0x0a, 0x07, 0x0e, 0x0b, 0x0d, 0x00, 0x06, 0x09, 0x0f,
0x00,
/* nfft = 512 */
0x01, 0x40, 0x02, 0x20, 0x03, 0x60, 0x04, 0x10, 0x05, 0x50, 0x06, 0x30, 0x07, 0x70, 0x09, 0x48,
0x0a, 0x28, 0x0b, 0x68, 0x0c, 0x18, 0x0d, 0x58, 0x0e, 0x38, 0x0f, 0x78, 0x11, 0x44, 0x12, 0x24,
0x13, 0x64, 0x15, 0x54, 0x16, 0x34, 0x17, 0x74, 0x19, 0x4c, 0x1a, 0x2c, 0x1b, 0x6c, 0x1d, 0x5c,
0x1e, 0x3c, 0x1f, 0x7c, 0x21, 0x42, 0x23, 0x62, 0x25, 0x52, 0x26, 0x32, 0x27, 0x72, 0x29, 0x4a,
0x2b, 0x6a, 0x2d, 0x5a, 0x2e, 0x3a, 0x2f, 0x7a, 0x31, 0x46, 0x33, 0x66, 0x35, 0x56, 0x37, 0x76,
0x39, 0x4e, 0x3b, 0x6e, 0x3d, 0x5e, 0x3f, 0x7e, 0x43, 0x61, 0x45, 0x51, 0x47, 0x71, 0x4b, 0x69,
0x4d, 0x59, 0x4f, 0x79, 0x53, 0x65, 0x57, 0x75, 0x5b, 0x6d, 0x5f, 0x7d, 0x67, 0x73, 0x6f, 0x7b,
0x00, 0x08, 0x14, 0x1c, 0x22, 0x2a, 0x36, 0x3e, 0x41, 0x49, 0x55, 0x5d, 0x63, 0x6b, 0x77, 0x7f,
0x00,
};
/* tables generated at runtime */
int cos4sin4tab[128 + 1024];
int cos1sin1tab[514];
int sinWindow[128 + 1024];
int kbdWindow[128 + 1024];
int twidTabEven[4*6 + 16*6 + 64*6];
int twidTabOdd[8*6 + 32*6 + 128*6];
#define M_PI 3.14159265358979323846
#define M2_30 1073741824.0
#define M2_31 2147483648.0
#define MAX_DBL 2147483647.0
#define MIN_DBL -2147483648.0
static int NormAndRound(double x, double q, double n)
{
if(x >= 0.0)
x = (x*q*n + 0.5);
else
x = (x*q*n - 0.5);
/* clip */
if (x > MAX_DBL)
x = MAX_DBL;
if (x < MIN_DBL)
x = MIN_DBL;
return (int)x;
}
static void Init_cos4sin4tab(int *tPtr, int nmdct)
{
int i;
double angle1, angle2, invM, x1, x2, x3, x4;
invM = -1.0 / (double)nmdct;
for (i = 0; i < nmdct/4; i++) {
angle1 = (i + 0.25) * M_PI / nmdct;
angle2 = (nmdct/2 - 1 - i + 0.25) * M_PI / nmdct;
x1 = invM * (cos(angle1) + sin(angle1));
x2 = invM * sin(angle1);
x3 = invM * (cos(angle2) + sin(angle2));
x4 = invM * sin(angle2);
tPtr[0] = NormAndRound(x1, M2_30, nmdct);
tPtr[1] = NormAndRound(x2, M2_30, nmdct);
tPtr[2] = NormAndRound(x3, M2_30, nmdct);
tPtr[3] = NormAndRound(x4, M2_30, nmdct);
tPtr += 4;
}
}
static void Init_cos1sin1tab(int *tPtr)
{
int i;
double angle, x1, x2;
for (i = 0; i <= (512/2); i++) {
angle = i * M_PI / 1024;
x1 = (cos(angle) + sin(angle));
x2 = sin(angle);
tPtr[0] = NormAndRound(x1, M2_30, 1);
tPtr[1] = NormAndRound(x2, M2_30, 1);
tPtr += 2;
}
}
static void Init_sinWindow(int *tPtr, int nmdct)
{
int i;
double angle1, angle2, x1, x2;
for (i = 0; i < nmdct/2; i++) {
angle1 = (i + 0.5) * M_PI / (2.0 * nmdct);
angle2 = (nmdct - 1 - i + 0.5) * M_PI / (2.0 * nmdct);
x1 = sin(angle1);
x2 = sin(angle2);
tPtr[0] = NormAndRound(x1, M2_31, 1);
tPtr[1] = NormAndRound(x2, M2_31, 1);
tPtr += 2;
}
}
#define KBD_THRESH 1e-12
static double CalcI0(double x)
{
int k;
double i0, iTmp, iLast, x2, xPow, kFact;
x2 = x / 2.0;
i0 = 0.0;
k = 0;
kFact = 1;
xPow = 1;
do {
iLast = i0;
iTmp = xPow / kFact;
i0 += (iTmp*iTmp);
k++;
kFact *= k;
xPow *= x2;
} while (fabs(i0 - iLast) > KBD_THRESH);
return i0;
}
static double CalcW(double nRef, double n, double a)
{
double i0Base, i0Curr, nTemp;
i0Base = CalcI0(M_PI * a);
nTemp = (n - nRef/4) / (nRef/4);
i0Curr = CalcI0( M_PI * a * sqrt(1.0 - nTemp*nTemp) );
return i0Curr / i0Base;
}
static void Init_kbdWindow(int *tPtr, int nmdct)
{
int n, nRef;
double a, wBase, wCurr, x1;
nRef = nmdct * 2;
/* kbd window */
if (nmdct == 128)
a = 6.0;
else
a = 4.0;
wBase = 0;
for (n = 0; n <= nRef/2; n++)
wBase += CalcW(nRef, n, a);
/* left */
wCurr = 0;
for (n = 0; n < nmdct/2; n++) {
wCurr += CalcW(nRef, n, a);
x1 = sqrt(wCurr / wBase);
tPtr[0] = NormAndRound(x1, M2_31, 1);
tPtr += 2;
}
tPtr--;
/* right */
for (n = nmdct/2; n < nmdct; n++) {
wCurr += CalcW(nRef, n, a);
x1 = sqrt(wCurr / wBase);
tPtr[0] = NormAndRound(x1, M2_31, 1);
tPtr -= 2;
}
/* symmetry:
* kbd_right(n) = kbd_ldef(N_REF - 1 - n), n = [N_REF/2, N_REF - 1]
*
* wCurr = 0;
* for (n = N_REF-1; n >= N_REF/2; n--) {
* wCurr += CalcW(N_REF-n-1, a);
* kbdWindowRef[n] = sqrt(wCurr / wBase);
* }
*
*/
return;
}
static void Init_twidTabs(int *tPtrEven, int *tPtrOdd, int nfft)
{
int j, k;
double wr1, wi1, wr2, wi2, wr3, wi3;
for (k = 4; k <= nfft/4; k <<= 1) {
for (j = 0; j < k; j++) {
wr1 = cos(1.0 * M_PI * j / (2*k));
wi1 = sin(1.0 * M_PI * j / (2*k));
wr1 = (wr1 + wi1);
wi1 = -wi1;
wr2 = cos(2.0 * M_PI * j / (2*k));
wi2 = sin(2.0 * M_PI * j / (2*k));
wr2 = (wr2 + wi2);
wi2 = -wi2;
wr3 = cos(3.0 * M_PI * j / (2*k));
wi3 = sin(3.0 * M_PI * j / (2*k));
wr3 = (wr3 + wi3);
wi3 = -wi3;
if (k & 0xaaaaaaaa) {
tPtrOdd[0] = NormAndRound(wr2, M2_30, 1);
tPtrOdd[1] = NormAndRound(wi2, M2_30, 1);
tPtrOdd[2] = NormAndRound(wr1, M2_30, 1);
tPtrOdd[3] = NormAndRound(wi1, M2_30, 1);
tPtrOdd[4] = NormAndRound(wr3, M2_30, 1);
tPtrOdd[5] = NormAndRound(wi3, M2_30, 1);
tPtrOdd += 6;
} else {
tPtrEven[0] = NormAndRound(wr2, M2_30, 1);
tPtrEven[1] = NormAndRound(wi2, M2_30, 1);
tPtrEven[2] = NormAndRound(wr1, M2_30, 1);
tPtrEven[3] = NormAndRound(wi1, M2_30, 1);
tPtrEven[4] = NormAndRound(wr3, M2_30, 1);
tPtrEven[5] = NormAndRound(wi3, M2_30, 1);
tPtrEven += 6;
}
}
}
}
/**************************************************************************************
* Function: AACInitTrigtabsFloat
*
* Description: generate AAC decoder tables using floating-point math library
*
* Inputs: none
*
* Outputs: initialized tables
*
* Return: 0 on success
*
* Notes: this function should ONLY be called when double-precision
* floating-point math is supported
* the generated tables must be bit-exact matches with read-only
* tables stored in trigtabs.c
* this initializes global tables in RAM, and is NOT thread-safe,
* so the caller must ensure that this function is not called
* from multiple threads
* this should be called exactly once, before the entrypoint function
* for the application or DLL is called
**************************************************************************************/
int AACInitTrigtabsFloat(void)
{
/* cos4sin4tab */
Init_cos4sin4tab(cos4sin4tab + cos4sin4tabOffset[0], 128);
Init_cos4sin4tab(cos4sin4tab + cos4sin4tabOffset[1], 1024);
/* cos1sin1tab */
Init_cos1sin1tab(cos1sin1tab);
/* sinWindow */
Init_sinWindow(sinWindow + sinWindowOffset[0], 128);
Init_sinWindow(sinWindow + sinWindowOffset[1], 1024);
/* kbdWindow */
Init_kbdWindow(kbdWindow + kbdWindowOffset[0], 128);
Init_kbdWindow(kbdWindow + kbdWindowOffset[1], 1024);
/* twidTabEven, twidTabOdd */
Init_twidTabs(twidTabEven, twidTabOdd, 512);
return 0;
}
/**************************************************************************************
* Function: AACFreeTrigtabsFloat
*
* Description: free any memory allocated by AACInitTrigtabsFloat()
*
* Inputs: none
*
* Outputs: none
*
* Return: none
**************************************************************************************/
void AACFreeTrigtabsFloat(void)
{
return;
}
#endif /* HELIX_CONFIG_AAC_GENERATE_TRIGTABS_FLOAT */
|
1137519-player
|
aac/trigtabs_fltgen.c
|
C
|
lgpl
| 10,511
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbrhuff.c,v 1.1 2005/02/26 01:47:35 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbrhuff.c - functions for unpacking Huffman-coded envelope and noise data
**************************************************************************************/
#include "sbr.h"
#include "assembly.h"
/**************************************************************************************
* Function: DecodeHuffmanScalar
*
* Description: decode one Huffman symbol from bitstream
*
* Inputs: pointers to Huffman table and info struct
* left-aligned bit buffer with >= huffTabInfo->maxBits bits
*
* Outputs: decoded symbol in *val
*
* Return: number of bits in symbol
*
* Notes: assumes canonical Huffman codes:
* first CW always 0, we have "count" CW's of length "nBits" bits
* starting CW for codes of length nBits+1 =
* (startCW[nBits] + count[nBits]) << 1
* if there are no codes at nBits, then we just keep << 1 each time
* (since count[nBits] = 0)
**************************************************************************************/
static int DecodeHuffmanScalar(const signed short *huffTab, const HuffInfo *huffTabInfo, unsigned int bitBuf, signed int *val)
{
unsigned int count, start, shift, t;
const unsigned char *countPtr;
const signed short *map;
map = huffTab + huffTabInfo->offset;
countPtr = huffTabInfo->count;
start = 0;
count = 0;
shift = 32;
do {
start += count;
start <<= 1;
map += count;
count = *countPtr++;
shift--;
t = (bitBuf >> shift) - start;
} while (t >= count);
*val = (signed int)map[t];
return (countPtr - huffTabInfo->count);
}
/**************************************************************************************
* Function: DecodeOneSymbol
*
* Description: dequantize one Huffman symbol from bitstream,
* using table huffTabSBR[huffTabIndex]
*
* Inputs: BitStreamInfo struct pointing to start of next Huffman codeword
* index of Huffman table
*
* Outputs: bitstream advanced by number of bits in codeword
*
* Return: one decoded symbol
**************************************************************************************/
static int DecodeOneSymbol(BitStreamInfo *bsi, int huffTabIndex)
{
int nBits, val;
unsigned int bitBuf;
const HuffInfo *hi;
hi = &(huffTabSBRInfo[huffTabIndex]);
bitBuf = GetBitsNoAdvance(bsi, hi->maxBits) << (32 - hi->maxBits);
nBits = DecodeHuffmanScalar(huffTabSBR, hi, bitBuf, &val);
AdvanceBitstream(bsi, nBits);
return val;
}
/* [1.0, sqrt(2)], format = Q29 (one guard bit for decoupling) */
static const int envDQTab[2] = {0x20000000, 0x2d413ccc};
/**************************************************************************************
* Function: DequantizeEnvelope
*
* Description: dequantize envelope scalefactors
*
* Inputs: number of scalefactors to process
* amplitude resolution flag for this frame (0 or 1)
* quantized envelope scalefactors
*
* Outputs: dequantized envelope scalefactors
*
* Return: extra int bits in output (6 + expMax)
* in other words, output format = Q(FBITS_OUT_DQ_ENV - (6 + expMax))
*
* Notes: dequantized scalefactors have at least 2 GB
**************************************************************************************/
static int DequantizeEnvelope(int nBands, int ampRes, signed char *envQuant, int *envDequant)
{
int exp, expMax, i, scalei;
if (nBands <= 0)
return 0;
/* scan for largest dequant value (do separately from envelope decoding to keep code cleaner) */
expMax = 0;
for (i = 0; i < nBands; i++) {
if (envQuant[i] > expMax)
expMax = envQuant[i];
}
/* dequantized envelope gains
* envDequant = 64*2^(envQuant / alpha) = 2^(6 + envQuant / alpha)
* if ampRes == 0, alpha = 2 and range of envQuant = [0, 127]
* if ampRes == 1, alpha = 1 and range of envQuant = [0, 63]
* also if coupling is on, envDequant is scaled by something in range [0, 2]
* so range of envDequant = [2^6, 2^69] (no coupling), [2^6, 2^70] (with coupling)
*
* typical range (from observation) of envQuant/alpha = [0, 27] --> largest envQuant ~= 2^33
* output: Q(29 - (6 + expMax))
*
* reference: 14496-3:2001(E)/4.6.18.3.5 and 14496-4:200X/FPDAM8/5.6.5.1.2.1.5
*/
if (ampRes) {
do {
exp = *envQuant++;
scalei = MIN(expMax - exp, 31);
*envDequant++ = envDQTab[0] >> scalei;
} while (--nBands);
return (6 + expMax);
} else {
expMax >>= 1;
do {
exp = *envQuant++;
scalei = MIN(expMax - (exp >> 1), 31);
*envDequant++ = envDQTab[exp & 0x01] >> scalei;
} while (--nBands);
return (6 + expMax);
}
}
/**************************************************************************************
* Function: DequantizeNoise
*
* Description: dequantize noise scalefactors
*
* Inputs: number of scalefactors to process
* quantized noise scalefactors
*
* Outputs: dequantized noise scalefactors, format = Q(FBITS_OUT_DQ_NOISE)
*
* Return: none
*
* Notes: dequantized scalefactors have at least 2 GB
**************************************************************************************/
static void DequantizeNoise(int nBands, signed char *noiseQuant, int *noiseDequant)
{
int exp, scalei;
if (nBands <= 0)
return;
/* dequantize noise floor gains (4.6.18.3.5):
* noiseDequant = 2^(NOISE_FLOOR_OFFSET - noiseQuant)
*
* range of noiseQuant = [0, 30] (see 4.6.18.3.6), NOISE_FLOOR_OFFSET = 6
* so range of noiseDequant = [2^-24, 2^6]
*/
do {
exp = *noiseQuant++;
scalei = NOISE_FLOOR_OFFSET - exp + FBITS_OUT_DQ_NOISE; /* 6 + 24 - exp, exp = [0,30] */
if (scalei < 0)
*noiseDequant++ = 0;
else if (scalei < 30)
*noiseDequant++ = 1 << scalei;
else
*noiseDequant++ = 0x3fffffff; /* leave 2 GB */
} while (--nBands);
}
/**************************************************************************************
* Function: DecodeSBREnvelope
*
* Description: decode delta Huffman coded envelope scalefactors from bitstream
*
* Inputs: BitStreamInfo struct pointing to start of env data
* initialized PSInfoSBR struct
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* initialized SBRChan struct for this channel
* index of current channel (0 for SCE, 0 or 1 for CPE)
*
* Outputs: dequantized env scalefactors for left channel (before decoupling)
* dequantized env scalefactors for right channel (if coupling off)
* or raw decoded env scalefactors for right channel (if coupling on)
*
* Return: none
**************************************************************************************/
void DecodeSBREnvelope(BitStreamInfo *bsi, PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch)
{
int huffIndexTime, huffIndexFreq, env, envStartBits, band, nBands, sf, lastEnv;
int freqRes, freqResPrev, dShift, i;
if (psi->couplingFlag && ch) {
dShift = 1;
if (sbrGrid->ampResFrame) {
huffIndexTime = HuffTabSBR_tEnv30b;
huffIndexFreq = HuffTabSBR_fEnv30b;
envStartBits = 5;
} else {
huffIndexTime = HuffTabSBR_tEnv15b;
huffIndexFreq = HuffTabSBR_fEnv15b;
envStartBits = 6;
}
} else {
dShift = 0;
if (sbrGrid->ampResFrame) {
huffIndexTime = HuffTabSBR_tEnv30;
huffIndexFreq = HuffTabSBR_fEnv30;
envStartBits = 6;
} else {
huffIndexTime = HuffTabSBR_tEnv15;
huffIndexFreq = HuffTabSBR_fEnv15;
envStartBits = 7;
}
}
/* range of envDataQuant[] = [0, 127] (see comments in DequantizeEnvelope() for reference) */
for (env = 0; env < sbrGrid->numEnv; env++) {
nBands = (sbrGrid->freqRes[env] ? sbrFreq->nHigh : sbrFreq->nLow);
freqRes = (sbrGrid->freqRes[env]);
freqResPrev = (env == 0 ? sbrGrid->freqResPrev : sbrGrid->freqRes[env-1]);
lastEnv = (env == 0 ? sbrGrid->numEnvPrev-1 : env-1);
if (lastEnv < 0)
lastEnv = 0; /* first frame */
ASSERT(nBands <= MAX_QMF_BANDS);
if (sbrChan->deltaFlagEnv[env] == 0) {
/* delta coding in freq */
sf = GetBits(bsi, envStartBits) << dShift;
sbrChan->envDataQuant[env][0] = sf;
for (band = 1; band < nBands; band++) {
sf = DecodeOneSymbol(bsi, huffIndexFreq) << dShift;
sbrChan->envDataQuant[env][band] = sf + sbrChan->envDataQuant[env][band-1];
}
} else if (freqRes == freqResPrev) {
/* delta coding in time - same freq resolution for both frames */
for (band = 0; band < nBands; band++) {
sf = DecodeOneSymbol(bsi, huffIndexTime) << dShift;
sbrChan->envDataQuant[env][band] = sf + sbrChan->envDataQuant[lastEnv][band];
}
} else if (freqRes == 0 && freqResPrev == 1) {
/* delta coding in time - low freq resolution for new frame, high freq resolution for old frame */
for (band = 0; band < nBands; band++) {
sf = DecodeOneSymbol(bsi, huffIndexTime) << dShift;
sbrChan->envDataQuant[env][band] = sf;
for (i = 0; i < sbrFreq->nHigh; i++) {
if (sbrFreq->freqHigh[i] == sbrFreq->freqLow[band]) {
sbrChan->envDataQuant[env][band] += sbrChan->envDataQuant[lastEnv][i];
break;
}
}
}
} else if (freqRes == 1 && freqResPrev == 0) {
/* delta coding in time - high freq resolution for new frame, low freq resolution for old frame */
for (band = 0; band < nBands; band++) {
sf = DecodeOneSymbol(bsi, huffIndexTime) << dShift;
sbrChan->envDataQuant[env][band] = sf;
for (i = 0; i < sbrFreq->nLow; i++) {
if (sbrFreq->freqLow[i] <= sbrFreq->freqHigh[band] && sbrFreq->freqHigh[band] < sbrFreq->freqLow[i+1] ) {
sbrChan->envDataQuant[env][band] += sbrChan->envDataQuant[lastEnv][i];
break;
}
}
}
}
/* skip coupling channel */
if (ch != 1 || psi->couplingFlag != 1)
psi->envDataDequantScale[ch][env] = DequantizeEnvelope(nBands, sbrGrid->ampResFrame, sbrChan->envDataQuant[env], psi->envDataDequant[ch][env]);
}
sbrGrid->numEnvPrev = sbrGrid->numEnv;
sbrGrid->freqResPrev = sbrGrid->freqRes[sbrGrid->numEnv-1];
}
/**************************************************************************************
* Function: DecodeSBRNoise
*
* Description: decode delta Huffman coded noise scalefactors from bitstream
*
* Inputs: BitStreamInfo struct pointing to start of noise data
* initialized PSInfoSBR struct
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* initialized SBRChan struct for this channel
* index of current channel (0 for SCE, 0 or 1 for CPE)
*
* Outputs: dequantized noise scalefactors for left channel (before decoupling)
* dequantized noise scalefactors for right channel (if coupling off)
* or raw decoded noise scalefactors for right channel (if coupling on)
*
* Return: none
**************************************************************************************/
void DecodeSBRNoise(BitStreamInfo *bsi, PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch)
{
int huffIndexTime, huffIndexFreq, noiseFloor, band, dShift, sf, lastNoiseFloor;
if (psi->couplingFlag && ch) {
dShift = 1;
huffIndexTime = HuffTabSBR_tNoise30b;
huffIndexFreq = HuffTabSBR_fNoise30b;
} else {
dShift = 0;
huffIndexTime = HuffTabSBR_tNoise30;
huffIndexFreq = HuffTabSBR_fNoise30;
}
for (noiseFloor = 0; noiseFloor < sbrGrid->numNoiseFloors; noiseFloor++) {
lastNoiseFloor = (noiseFloor == 0 ? sbrGrid->numNoiseFloorsPrev-1 : noiseFloor-1);
if (lastNoiseFloor < 0)
lastNoiseFloor = 0; /* first frame */
ASSERT(sbrFreq->numNoiseFloorBands <= MAX_QMF_BANDS);
if (sbrChan->deltaFlagNoise[noiseFloor] == 0) {
/* delta coding in freq */
sbrChan->noiseDataQuant[noiseFloor][0] = GetBits(bsi, 5) << dShift;
for (band = 1; band < sbrFreq->numNoiseFloorBands; band++) {
sf = DecodeOneSymbol(bsi, huffIndexFreq) << dShift;
sbrChan->noiseDataQuant[noiseFloor][band] = sf + sbrChan->noiseDataQuant[noiseFloor][band-1];
}
} else {
/* delta coding in time */
for (band = 0; band < sbrFreq->numNoiseFloorBands; band++) {
sf = DecodeOneSymbol(bsi, huffIndexTime) << dShift;
sbrChan->noiseDataQuant[noiseFloor][band] = sf + sbrChan->noiseDataQuant[lastNoiseFloor][band];
}
}
/* skip coupling channel */
if (ch != 1 || psi->couplingFlag != 1)
DequantizeNoise(sbrFreq->numNoiseFloorBands, sbrChan->noiseDataQuant[noiseFloor], psi->noiseDataDequant[ch][noiseFloor]);
}
sbrGrid->numNoiseFloorsPrev = sbrGrid->numNoiseFloors;
}
/* dqTabCouple[i] = 2 / (1 + 2^(12 - i)), format = Q30 */
static const int dqTabCouple[25] = {
0x0007ff80, 0x000ffe00, 0x001ff802, 0x003fe010, 0x007f8080, 0x00fe03f8, 0x01f81f82, 0x03e0f83e,
0x07878788, 0x0e38e38e, 0x1999999a, 0x2aaaaaab, 0x40000000, 0x55555555, 0x66666666, 0x71c71c72,
0x78787878, 0x7c1f07c2, 0x7e07e07e, 0x7f01fc08, 0x7f807f80, 0x7fc01ff0, 0x7fe007fe, 0x7ff00200,
0x7ff80080,
};
/**************************************************************************************
* Function: UncoupleSBREnvelope
*
* Description: scale dequantized envelope scalefactors according to channel
* coupling rules
*
* Inputs: initialized PSInfoSBR struct including
* dequantized envelope data for left channel
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* initialized SBRChan struct for right channel including
* quantized envelope scalefactors
*
* Outputs: dequantized envelope data for left channel (after decoupling)
* dequantized envelope data for right channel (after decoupling)
*
* Return: none
**************************************************************************************/
void UncoupleSBREnvelope(PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChanR)
{
int env, band, nBands, scalei, E_1;
scalei = (sbrGrid->ampResFrame ? 0 : 1);
for (env = 0; env < sbrGrid->numEnv; env++) {
nBands = (sbrGrid->freqRes[env] ? sbrFreq->nHigh : sbrFreq->nLow);
psi->envDataDequantScale[1][env] = psi->envDataDequantScale[0][env]; /* same scalefactor for L and R */
for (band = 0; band < nBands; band++) {
/* clip E_1 to [0, 24] (scalefactors approach 0 or 2) */
E_1 = sbrChanR->envDataQuant[env][band] >> scalei;
if (E_1 < 0) E_1 = 0;
if (E_1 > 24) E_1 = 24;
/* envDataDequant[0] has 1 GB, so << by 2 is okay */
psi->envDataDequant[1][env][band] = MULSHIFT32(psi->envDataDequant[0][env][band], dqTabCouple[24 - E_1]) << 2;
psi->envDataDequant[0][env][band] = MULSHIFT32(psi->envDataDequant[0][env][band], dqTabCouple[E_1]) << 2;
}
}
}
/**************************************************************************************
* Function: UncoupleSBRNoise
*
* Description: scale dequantized noise floor scalefactors according to channel
* coupling rules
*
* Inputs: initialized PSInfoSBR struct including
* dequantized noise data for left channel
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* initialized SBRChan struct for this channel including
* quantized noise scalefactors
*
* Outputs: dequantized noise data for left channel (after decoupling)
* dequantized noise data for right channel (after decoupling)
*
* Return: none
**************************************************************************************/
void UncoupleSBRNoise(PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChanR)
{
int noiseFloor, band, Q_1;
for (noiseFloor = 0; noiseFloor < sbrGrid->numNoiseFloors; noiseFloor++) {
for (band = 0; band < sbrFreq->numNoiseFloorBands; band++) {
/* Q_1 should be in range [0, 24] according to 4.6.18.3.6, but check to make sure */
Q_1 = sbrChanR->noiseDataQuant[noiseFloor][band];
if (Q_1 < 0) Q_1 = 0;
if (Q_1 > 24) Q_1 = 24;
/* noiseDataDequant[0] has 1 GB, so << by 2 is okay */
psi->noiseDataDequant[1][noiseFloor][band] = MULSHIFT32(psi->noiseDataDequant[0][noiseFloor][band], dqTabCouple[24 - Q_1]) << 2;
psi->noiseDataDequant[0][noiseFloor][band] = MULSHIFT32(psi->noiseDataDequant[0][noiseFloor][band], dqTabCouple[Q_1]) << 2;
}
}
}
|
1137519-player
|
aac/sbrhuff.c
|
C
|
lgpl
| 18,463
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: hufftabs.c,v 1.1 2005/02/26 01:47:34 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* hufftabs.c - Huffman symbol tables
**************************************************************************************/
#include "coder.h"
const HuffInfo huffTabSpecInfo[11] = {
/* table 0 not used */
{11, { 1, 0, 0, 0, 8, 0, 24, 0, 24, 8, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0},
{ 9, { 0, 0, 1, 1, 7, 24, 15, 19, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 81},
{16, { 1, 0, 0, 4, 2, 6, 3, 5, 15, 15, 8, 9, 3, 3, 5, 2, 0, 0, 0, 0}, 162},
{12, { 0, 0, 0, 10, 6, 0, 9, 21, 8, 14, 11, 2, 0, 0, 0, 0, 0, 0, 0, 0}, 243},
{13, { 1, 0, 0, 4, 4, 0, 4, 12, 12, 12, 18, 10, 4, 0, 0, 0, 0, 0, 0, 0}, 324},
{11, { 0, 0, 0, 9, 0, 16, 13, 8, 23, 8, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 405},
{12, { 1, 0, 2, 1, 0, 4, 5, 10, 14, 15, 8, 4, 0, 0, 0, 0, 0, 0, 0, 0}, 486},
{10, { 0, 0, 1, 5, 7, 10, 14, 15, 8, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 550},
{15, { 1, 0, 2, 1, 0, 4, 3, 8, 11, 20, 31, 38, 32, 14, 4, 0, 0, 0, 0, 0}, 614},
{12, { 0, 0, 0, 3, 8, 14, 17, 25, 31, 41, 22, 8, 0, 0, 0, 0, 0, 0, 0, 0}, 783},
{12, { 0, 0, 0, 2, 6, 7, 16, 59, 55, 95, 43, 6, 0, 0, 0, 0, 0, 0, 0, 0}, 952},
};
const signed short huffTabSpec[1241] = {
/* spectrum table 1 [81] (signed) */
0x0000, 0x0200, 0x0e00, 0x0007, 0x0040, 0x0001, 0x0038, 0x0008, 0x01c0, 0x03c0, 0x0e40, 0x0039, 0x0078, 0x01c8, 0x000f, 0x0240,
0x003f, 0x0fc0, 0x01f8, 0x0238, 0x0047, 0x0e08, 0x0009, 0x0208, 0x01c1, 0x0048, 0x0041, 0x0e38, 0x0201, 0x0e07, 0x0207, 0x0e01,
0x01c7, 0x0278, 0x0e78, 0x03c8, 0x004f, 0x0079, 0x01c9, 0x01cf, 0x03f8, 0x0239, 0x007f, 0x0e48, 0x0e0f, 0x0fc8, 0x01f9, 0x03c1,
0x03c7, 0x0e47, 0x0ff8, 0x01ff, 0x0049, 0x020f, 0x0241, 0x0e41, 0x0248, 0x0fc1, 0x0e3f, 0x0247, 0x023f, 0x0e39, 0x0fc7, 0x0e09,
0x0209, 0x03cf, 0x0e79, 0x0e4f, 0x03f9, 0x0249, 0x0fc9, 0x027f, 0x0fcf, 0x0fff, 0x0279, 0x03c9, 0x0e49, 0x0e7f, 0x0ff9, 0x03ff,
0x024f,
/* spectrum table 2 [81] (signed) */
0x0000, 0x0200, 0x0e00, 0x0001, 0x0038, 0x0007, 0x01c0, 0x0008, 0x0040, 0x01c8, 0x0e40, 0x0078, 0x000f, 0x0047, 0x0039, 0x0e07,
0x03c0, 0x0238, 0x0fc0, 0x003f, 0x0208, 0x0201, 0x01c1, 0x0e08, 0x0041, 0x01f8, 0x0e01, 0x01c7, 0x0e38, 0x0240, 0x0048, 0x0009,
0x0207, 0x0079, 0x0239, 0x0e78, 0x01cf, 0x03c8, 0x0247, 0x0209, 0x0e48, 0x01f9, 0x0248, 0x0e0f, 0x0ff8, 0x0e39, 0x03f8, 0x0278,
0x03c1, 0x0e47, 0x0fc8, 0x0e09, 0x0fc1, 0x0fc7, 0x01ff, 0x020f, 0x023f, 0x007f, 0x0049, 0x0e41, 0x0e3f, 0x004f, 0x03c7, 0x01c9,
0x0241, 0x03cf, 0x0e79, 0x03f9, 0x0fff, 0x0e4f, 0x0e49, 0x0249, 0x0fcf, 0x03c9, 0x0e7f, 0x0fc9, 0x027f, 0x03ff, 0x0ff9, 0x0279,
0x024f,
/* spectrum table 3 [81] (unsigned) */
0x0000, 0x1200, 0x1001, 0x1040, 0x1008, 0x2240, 0x2009, 0x2048, 0x2041, 0x2208, 0x3049, 0x2201, 0x3248, 0x4249, 0x3209, 0x3241,
0x1400, 0x1002, 0x200a, 0x2440, 0x3288, 0x2011, 0x3051, 0x2280, 0x304a, 0x3448, 0x1010, 0x2088, 0x2050, 0x1080, 0x2042, 0x2408,
0x4289, 0x3089, 0x3250, 0x4251, 0x3281, 0x2210, 0x3211, 0x2081, 0x4449, 0x424a, 0x3441, 0x320a, 0x2012, 0x3052, 0x3488, 0x3290,
0x2202, 0x2401, 0x3091, 0x2480, 0x4291, 0x3242, 0x3409, 0x4252, 0x4489, 0x2090, 0x308a, 0x3212, 0x3481, 0x3450, 0x3490, 0x3092,
0x4491, 0x4451, 0x428a, 0x4292, 0x2082, 0x2410, 0x3282, 0x3411, 0x444a, 0x3442, 0x4492, 0x448a, 0x4452, 0x340a, 0x2402, 0x3482,
0x3412,
/* spectrum table 4 [81] (unsigned) */
0x4249, 0x3049, 0x3241, 0x3248, 0x3209, 0x1200, 0x2240, 0x0000, 0x2009, 0x2208, 0x2201, 0x2048, 0x1001, 0x2041, 0x1008, 0x1040,
0x4449, 0x4251, 0x4289, 0x424a, 0x3448, 0x3441, 0x3288, 0x3409, 0x3051, 0x304a, 0x3250, 0x3089, 0x320a, 0x3281, 0x3242, 0x3211,
0x2440, 0x2408, 0x2280, 0x2401, 0x2042, 0x2088, 0x200a, 0x2050, 0x2081, 0x2202, 0x2011, 0x2210, 0x1400, 0x1002, 0x1080, 0x1010,
0x4291, 0x4489, 0x4451, 0x4252, 0x428a, 0x444a, 0x3290, 0x3488, 0x3450, 0x3091, 0x3052, 0x3481, 0x308a, 0x3411, 0x3212, 0x4491,
0x3282, 0x340a, 0x3442, 0x4292, 0x4452, 0x448a, 0x2090, 0x2480, 0x2012, 0x2410, 0x2082, 0x2402, 0x4492, 0x3092, 0x3490, 0x3482,
0x3412,
/* spectrum table 5 [81] (signed) */
0x0000, 0x03e0, 0x0020, 0x0001, 0x001f, 0x003f, 0x03e1, 0x03ff, 0x0021, 0x03c0, 0x0002, 0x0040, 0x001e, 0x03df, 0x0041, 0x03fe,
0x0022, 0x03c1, 0x005f, 0x03e2, 0x003e, 0x03a0, 0x0060, 0x001d, 0x0003, 0x03bf, 0x0023, 0x0061, 0x03fd, 0x03a1, 0x007f, 0x003d,
0x03e3, 0x03c2, 0x0042, 0x03de, 0x005e, 0x03be, 0x007e, 0x03c3, 0x005d, 0x0062, 0x0043, 0x03a2, 0x03dd, 0x001c, 0x0380, 0x0081,
0x0080, 0x039f, 0x0004, 0x009f, 0x03fc, 0x0024, 0x03e4, 0x0381, 0x003c, 0x007d, 0x03bd, 0x03a3, 0x03c4, 0x039e, 0x0082, 0x005c,
0x0044, 0x0063, 0x0382, 0x03dc, 0x009e, 0x007c, 0x039d, 0x0383, 0x0064, 0x03a4, 0x0083, 0x009d, 0x03bc, 0x009c, 0x0384, 0x0084,
0x039c,
/* spectrum table 6 [81] (signed) */
0x0000, 0x0020, 0x001f, 0x0001, 0x03e0, 0x0021, 0x03e1, 0x003f, 0x03ff, 0x005f, 0x0041, 0x03c1, 0x03df, 0x03c0, 0x03e2, 0x0040,
0x003e, 0x0022, 0x001e, 0x03fe, 0x0002, 0x005e, 0x03c2, 0x03de, 0x0042, 0x03a1, 0x0061, 0x007f, 0x03e3, 0x03bf, 0x0023, 0x003d,
0x03fd, 0x0060, 0x03a0, 0x001d, 0x0003, 0x0062, 0x03be, 0x03c3, 0x0043, 0x007e, 0x005d, 0x03dd, 0x03a2, 0x0063, 0x007d, 0x03bd,
0x03a3, 0x003c, 0x03fc, 0x0081, 0x0381, 0x039f, 0x0024, 0x009f, 0x03e4, 0x001c, 0x0382, 0x039e, 0x0044, 0x03dc, 0x0380, 0x0082,
0x009e, 0x03c4, 0x0080, 0x005c, 0x0004, 0x03bc, 0x03a4, 0x007c, 0x009d, 0x0064, 0x0083, 0x0383, 0x039d, 0x0084, 0x0384, 0x039c,
0x009c,
/* spectrum table 7 [64] (unsigned) */
0x0000, 0x0420, 0x0401, 0x0821, 0x0841, 0x0822, 0x0440, 0x0402, 0x0861, 0x0823, 0x0842, 0x0460, 0x0403, 0x0843, 0x0862, 0x0824,
0x0881, 0x0825, 0x08a1, 0x0863, 0x0844, 0x0404, 0x0480, 0x0882, 0x0845, 0x08a2, 0x0405, 0x08c1, 0x04a0, 0x0826, 0x0883, 0x0865,
0x0864, 0x08a3, 0x0846, 0x08c2, 0x0827, 0x0866, 0x0406, 0x04c0, 0x0884, 0x08e1, 0x0885, 0x08e2, 0x08a4, 0x08c3, 0x0847, 0x08e3,
0x08c4, 0x08a5, 0x0886, 0x0867, 0x04e0, 0x0407, 0x08c5, 0x08a6, 0x08e4, 0x0887, 0x08a7, 0x08e5, 0x08e6, 0x08c6, 0x08c7, 0x08e7,
/* spectrum table 8 [64] (unsigned) */
0x0821, 0x0841, 0x0420, 0x0822, 0x0401, 0x0842, 0x0000, 0x0440, 0x0402, 0x0861, 0x0823, 0x0862, 0x0843, 0x0863, 0x0881, 0x0824,
0x0882, 0x0844, 0x0460, 0x0403, 0x0883, 0x0864, 0x08a2, 0x08a1, 0x0845, 0x0825, 0x08a3, 0x0865, 0x0884, 0x08a4, 0x0404, 0x0885,
0x0480, 0x0846, 0x08c2, 0x08c1, 0x0826, 0x0866, 0x08c3, 0x08a5, 0x04a0, 0x08c4, 0x0405, 0x0886, 0x08e1, 0x08e2, 0x0847, 0x08c5,
0x08e3, 0x0827, 0x08a6, 0x0867, 0x08c6, 0x08e4, 0x04c0, 0x0887, 0x0406, 0x08e5, 0x08e6, 0x08c7, 0x08a7, 0x04e0, 0x0407, 0x08e7,
/* spectrum table 9 [169] (unsigned) */
0x0000, 0x0420, 0x0401, 0x0821, 0x0841, 0x0822, 0x0440, 0x0402, 0x0861, 0x0842, 0x0823, 0x0460, 0x0403, 0x0843, 0x0862, 0x0824,
0x0881, 0x0844, 0x0825, 0x0882, 0x0863, 0x0404, 0x0480, 0x08a1, 0x0845, 0x0826, 0x0864, 0x08a2, 0x08c1, 0x0883, 0x0405, 0x0846,
0x04a0, 0x0827, 0x0865, 0x0828, 0x0901, 0x0884, 0x08a3, 0x08c2, 0x08e1, 0x0406, 0x0902, 0x0848, 0x0866, 0x0847, 0x0885, 0x0921,
0x0829, 0x08e2, 0x04c0, 0x08a4, 0x08c3, 0x0903, 0x0407, 0x0922, 0x0868, 0x0886, 0x0867, 0x0408, 0x0941, 0x08c4, 0x0849, 0x08a5,
0x0500, 0x04e0, 0x08e3, 0x0942, 0x0923, 0x0904, 0x082a, 0x08e4, 0x08c5, 0x08a6, 0x0888, 0x0887, 0x0869, 0x0961, 0x08a8, 0x0520,
0x0905, 0x0943, 0x084a, 0x0409, 0x0962, 0x0924, 0x08c6, 0x0981, 0x0889, 0x0906, 0x082b, 0x0925, 0x0944, 0x08a7, 0x08e5, 0x084b,
0x082c, 0x0982, 0x0963, 0x086a, 0x08a9, 0x08c7, 0x0907, 0x0964, 0x040a, 0x08e6, 0x0983, 0x0540, 0x0945, 0x088a, 0x08c8, 0x084c,
0x0926, 0x0927, 0x088b, 0x0560, 0x08c9, 0x086b, 0x08aa, 0x0908, 0x08e8, 0x0985, 0x086c, 0x0965, 0x08e7, 0x0984, 0x0966, 0x0946,
0x088c, 0x08e9, 0x08ab, 0x040b, 0x0986, 0x08ca, 0x0580, 0x0947, 0x08ac, 0x08ea, 0x0928, 0x040c, 0x0967, 0x0909, 0x0929, 0x0948,
0x08eb, 0x0987, 0x08cb, 0x090b, 0x0968, 0x08ec, 0x08cc, 0x090a, 0x0949, 0x090c, 0x092a, 0x092b, 0x092c, 0x094b, 0x0989, 0x094a,
0x0969, 0x0988, 0x096a, 0x098a, 0x098b, 0x094c, 0x096b, 0x096c, 0x098c,
/* spectrum table 10 [169] (unsigned) */
0x0821, 0x0822, 0x0841, 0x0842, 0x0420, 0x0401, 0x0823, 0x0862, 0x0861, 0x0843, 0x0863, 0x0440, 0x0402, 0x0844, 0x0882, 0x0824,
0x0881, 0x0000, 0x0883, 0x0864, 0x0460, 0x0403, 0x0884, 0x0845, 0x08a2, 0x0825, 0x08a1, 0x08a3, 0x0865, 0x08a4, 0x0885, 0x08c2,
0x0846, 0x08c3, 0x0480, 0x08c1, 0x0404, 0x0826, 0x0866, 0x08a5, 0x08c4, 0x0886, 0x08c5, 0x08e2, 0x0867, 0x0847, 0x08a6, 0x0902,
0x08e3, 0x04a0, 0x08e1, 0x0405, 0x0901, 0x0827, 0x0903, 0x08e4, 0x0887, 0x0848, 0x08c6, 0x08e5, 0x0828, 0x0868, 0x0904, 0x0888,
0x08a7, 0x0905, 0x08a8, 0x08e6, 0x08c7, 0x0922, 0x04c0, 0x08c8, 0x0923, 0x0869, 0x0921, 0x0849, 0x0406, 0x0906, 0x0924, 0x0889,
0x0942, 0x0829, 0x08e7, 0x0907, 0x0925, 0x08e8, 0x0943, 0x08a9, 0x0944, 0x084a, 0x0941, 0x086a, 0x0926, 0x08c9, 0x0500, 0x088a,
0x04e0, 0x0962, 0x08e9, 0x0963, 0x0946, 0x082a, 0x0961, 0x0927, 0x0407, 0x0908, 0x0945, 0x086b, 0x08aa, 0x0909, 0x0965, 0x0408,
0x0964, 0x084b, 0x08ea, 0x08ca, 0x0947, 0x088b, 0x082b, 0x0982, 0x0928, 0x0983, 0x0966, 0x08ab, 0x0984, 0x0967, 0x0985, 0x086c,
0x08cb, 0x0520, 0x0948, 0x0540, 0x0981, 0x0409, 0x088c, 0x0929, 0x0986, 0x084c, 0x090a, 0x092a, 0x082c, 0x0968, 0x0987, 0x08eb,
0x08ac, 0x08cc, 0x0949, 0x090b, 0x0988, 0x040a, 0x08ec, 0x0560, 0x094a, 0x0969, 0x096a, 0x040b, 0x096b, 0x092b, 0x094b, 0x0580,
0x090c, 0x0989, 0x094c, 0x092c, 0x096c, 0x098b, 0x040c, 0x098a, 0x098c,
/* spectrum table 11 [289] (unsigned) */
0x0000, 0x2041, 0x2410, 0x1040, 0x1001, 0x2081, 0x2042, 0x2082, 0x2043, 0x20c1, 0x20c2, 0x1080, 0x2083, 0x1002, 0x20c3, 0x2101,
0x2044, 0x2102, 0x2084, 0x2103, 0x20c4, 0x10c0, 0x1003, 0x2141, 0x2142, 0x2085, 0x2104, 0x2045, 0x2143, 0x20c5, 0x2144, 0x2105,
0x2182, 0x2086, 0x2181, 0x2183, 0x20c6, 0x2046, 0x2110, 0x20d0, 0x2405, 0x2403, 0x2404, 0x2184, 0x2406, 0x1100, 0x2106, 0x1004,
0x2090, 0x2145, 0x2150, 0x2407, 0x2402, 0x2408, 0x2087, 0x21c2, 0x20c7, 0x2185, 0x2146, 0x2190, 0x240a, 0x21c3, 0x21c1, 0x2409,
0x21d0, 0x2050, 0x2047, 0x2107, 0x240b, 0x21c4, 0x240c, 0x2210, 0x2401, 0x2186, 0x2250, 0x2088, 0x2147, 0x2290, 0x240d, 0x2203,
0x2202, 0x20c8, 0x1140, 0x240e, 0x22d0, 0x21c5, 0x2108, 0x2187, 0x21c6, 0x1005, 0x2204, 0x240f, 0x2310, 0x2048, 0x2201, 0x2390,
0x2148, 0x2350, 0x20c9, 0x2205, 0x21c7, 0x2089, 0x2206, 0x2242, 0x2243, 0x23d0, 0x2109, 0x2188, 0x1180, 0x2244, 0x2149, 0x2207,
0x21c8, 0x2049, 0x2283, 0x1006, 0x2282, 0x2241, 0x2245, 0x210a, 0x208a, 0x2246, 0x20ca, 0x2189, 0x2284, 0x2208, 0x2285, 0x2247,
0x22c3, 0x204a, 0x11c0, 0x2286, 0x21c9, 0x20cb, 0x214a, 0x2281, 0x210b, 0x22c2, 0x2342, 0x218a, 0x2343, 0x208b, 0x1400, 0x214b,
0x22c5, 0x22c4, 0x2248, 0x21ca, 0x2209, 0x1010, 0x210d, 0x1007, 0x20cd, 0x22c6, 0x2341, 0x2344, 0x2303, 0x208d, 0x2345, 0x220a,
0x218b, 0x2288, 0x2287, 0x2382, 0x2304, 0x204b, 0x210c, 0x22c1, 0x20cc, 0x204d, 0x2302, 0x21cb, 0x20ce, 0x214c, 0x214d, 0x2384,
0x210e, 0x22c7, 0x2383, 0x2305, 0x2346, 0x2306, 0x1200, 0x22c8, 0x208c, 0x2249, 0x2385, 0x218d, 0x228a, 0x23c2, 0x220b, 0x224a,
0x2386, 0x2289, 0x214e, 0x22c9, 0x2381, 0x208e, 0x218c, 0x204c, 0x2348, 0x1008, 0x2347, 0x21cc, 0x2307, 0x21cd, 0x23c3, 0x2301,
0x218e, 0x208f, 0x23c5, 0x23c4, 0x204e, 0x224b, 0x210f, 0x2387, 0x220d, 0x2349, 0x220c, 0x214f, 0x20cf, 0x228b, 0x22ca, 0x2308,
0x23c6, 0x23c7, 0x220e, 0x23c1, 0x21ce, 0x1240, 0x1009, 0x224d, 0x224c, 0x2309, 0x2388, 0x228d, 0x2389, 0x230a, 0x218f, 0x21cf,
0x224e, 0x23c8, 0x22cb, 0x22ce, 0x204f, 0x228c, 0x228e, 0x234b, 0x234a, 0x22cd, 0x22cc, 0x220f, 0x238b, 0x234c, 0x230d, 0x23c9,
0x238a, 0x1280, 0x230b, 0x224f, 0x100a, 0x230c, 0x12c0, 0x230e, 0x228f, 0x234d, 0x100d, 0x238c, 0x23ca, 0x23cb, 0x22cf, 0x238d,
0x1340, 0x100b, 0x234e, 0x23cc, 0x23cd, 0x230f, 0x1380, 0x238e, 0x234f, 0x1300, 0x238f, 0x100e, 0x100c, 0x23ce, 0x13c0, 0x100f,
0x23cf,
};
const HuffInfo huffTabScaleFactInfo =
{19, { 1, 0, 1, 3, 2, 4, 3, 5, 4, 6, 6, 6, 5, 8, 4, 7, 3, 7, 46, 0}, 0};
/* note - includes offset of -60 (4.6.2.3 in spec) */
const signed short huffTabScaleFact[121] = {
/* scale factor table [121] */
0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, 6, -6, 7, -7, 8,
-8, 9, -9, 10, -10, -11, 11, 12, -12, 13, -13, 14, -14, 16, 15, 17,
18, -15, -17, -16, 19, -18, -19, 20, -20, 21, -21, 22, -22, 23, -23, -25,
25, -27, -24, -26, 24, -28, 27, 29, -30, -29, 26, -31, -34, -33, -32, -36,
28, -35, -38, -37, 30, -39, -41, -57, -59, -58, -60, 38, 39, 40, 41, 42,
57, 37, 31, 32, 33, 34, 35, 36, 44, 51, 52, 53, 54, 55, 56, 50,
45, 46, 47, 48, 49, 58, -54, -52, -51, -50, -55, 43, 60, 59, -56, -53,
-45, -44, -42, -40, -43, -49, -48, -46, -47,
};
|
1137519-player
|
aac/hufftabs.c
|
C
|
lgpl
| 14,775
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbrimdct.c,v 1.1 2005/02/26 01:47:35 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbrimdct.c - inverse MDCT without clipping or interleaving, for input to SBR
**************************************************************************************/
#include "coder.h"
#include "assembly.h"
/**************************************************************************************
* Function: DecWindowOverlapNoClip
*
* Description: apply synthesis window, do overlap-add without clipping,
* for winSequence LONG-LONG
*
* Inputs: input buffer (output of type-IV DCT)
* overlap buffer (saved from last time)
* window type (sin or KBD) for input buffer
* window type (sin or KBD) for overlap buffer
*
* Outputs: one channel, one frame of 32-bit PCM, non-interleaved
*
* Return: none
*
* Notes: use this function when the decoded PCM is going to the SBR decoder
**************************************************************************************/
void DecWindowOverlapNoClip(int *buf0, int *over0, int *out0, int winTypeCurr, int winTypePrev)
{
int in, w0, w1, f0, f1;
int *buf1, *over1, *out1;
const int *wndPrev, *wndCurr;
buf0 += (1024 >> 1);
buf1 = buf0 - 1;
out1 = out0 + 1024 - 1;
over1 = over0 + 1024 - 1;
wndPrev = (winTypePrev == 1 ? kbdWindow + kbdWindowOffset[1] : sinWindow + sinWindowOffset[1]);
if (winTypeCurr == winTypePrev) {
/* cut window loads in half since current and overlap sections use same symmetric window */
do {
w0 = *wndPrev++;
w1 = *wndPrev++;
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*out0++ = in - f0;
in = *over1;
*out1-- = in + f1;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
} else {
/* different windows for current and overlap parts - should still fit in registers on ARM w/o stack spill */
wndCurr = (winTypeCurr == 1 ? kbdWindow + kbdWindowOffset[1] : sinWindow + sinWindowOffset[1]);
do {
w0 = *wndPrev++;
w1 = *wndPrev++;
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*out0++ = in - f0;
in = *over1;
*out1-- = in + f1;
w0 = *wndCurr++;
w1 = *wndCurr++;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
}
}
/**************************************************************************************
* Function: DecWindowOverlapLongStart
*
* Description: apply synthesis window, do overlap-add, without clipping
* for winSequence LONG-START
*
* Inputs: input buffer (output of type-IV DCT)
* overlap buffer (saved from last time)
* window type (sin or KBD) for input buffer
* window type (sin or KBD) for overlap buffer
*
* Outputs: one channel, one frame of 32-bit PCM, non-interleaved
*
* Return: none
*
* Notes: use this function when the decoded PCM is going to the SBR decoder
**************************************************************************************/
void DecWindowOverlapLongStartNoClip(int *buf0, int *over0, int *out0, int winTypeCurr, int winTypePrev)
{
int i, in, w0, w1, f0, f1;
int *buf1, *over1, *out1;
const int *wndPrev, *wndCurr;
buf0 += (1024 >> 1);
buf1 = buf0 - 1;
out1 = out0 + 1024 - 1;
over1 = over0 + 1024 - 1;
wndPrev = (winTypePrev == 1 ? kbdWindow + kbdWindowOffset[1] : sinWindow + sinWindowOffset[1]);
i = 448; /* 2 outputs, 2 overlaps per loop */
do {
w0 = *wndPrev++;
w1 = *wndPrev++;
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*out0++ = in - f0;
in = *over1;
*out1-- = in + f1;
in = *buf1--;
*over1-- = 0; /* Wn = 0 for n = (2047, 2046, ... 1600) */
*over0++ = in >> 1; /* Wn = 1 for n = (1024, 1025, ... 1471) */
} while (--i);
wndCurr = (winTypeCurr == 1 ? kbdWindow + kbdWindowOffset[0] : sinWindow + sinWindowOffset[0]);
/* do 64 more loops - 2 outputs, 2 overlaps per loop */
do {
w0 = *wndPrev++;
w1 = *wndPrev++;
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*out0++ = in - f0;
in = *over1;
*out1-- = in + f1;
w0 = *wndCurr++; /* W[0], W[1], ... --> W[255], W[254], ... */
w1 = *wndCurr++; /* W[127], W[126], ... --> W[128], W[129], ... */
in = *buf1--;
*over1-- = MULSHIFT32(w0, in); /* Wn = short window for n = (1599, 1598, ... , 1536) */
*over0++ = MULSHIFT32(w1, in); /* Wn = short window for n = (1472, 1473, ... , 1535) */
} while (over0 < over1);
}
/**************************************************************************************
* Function: DecWindowOverlapLongStop
*
* Description: apply synthesis window, do overlap-add, without clipping
* for winSequence LONG-STOP
*
* Inputs: input buffer (output of type-IV DCT)
* overlap buffer (saved from last time)
* window type (sin or KBD) for input buffer
* window type (sin or KBD) for overlap buffer
*
* Outputs: one channel, one frame of 32-bit PCM, non-interleaved
*
* Return: none
*
* Notes: use this function when the decoded PCM is going to the SBR decoder
**************************************************************************************/
void DecWindowOverlapLongStopNoClip(int *buf0, int *over0, int *out0, int winTypeCurr, int winTypePrev)
{
int i, in, w0, w1, f0, f1;
int *buf1, *over1, *out1;
const int *wndPrev, *wndCurr;
buf0 += (1024 >> 1);
buf1 = buf0 - 1;
out1 = out0 + 1024 - 1;
over1 = over0 + 1024 - 1;
wndPrev = (winTypePrev == 1 ? kbdWindow + kbdWindowOffset[0] : sinWindow + sinWindowOffset[0]);
wndCurr = (winTypeCurr == 1 ? kbdWindow + kbdWindowOffset[1] : sinWindow + sinWindowOffset[1]);
i = 448; /* 2 outputs, 2 overlaps per loop */
do {
/* Wn = 0 for n = (0, 1, ... 447) */
/* Wn = 1 for n = (576, 577, ... 1023) */
in = *buf0++;
f1 = in >> 1; /* scale since skipping multiply by Q31 */
in = *over0;
*out0++ = in;
in = *over1;
*out1-- = in + f1;
w0 = *wndCurr++;
w1 = *wndCurr++;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (--i);
/* do 64 more loops - 2 outputs, 2 overlaps per loop */
do {
w0 = *wndPrev++; /* W[0], W[1], ...W[63] */
w1 = *wndPrev++; /* W[127], W[126], ... W[64] */
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*out0++ = in - f0;
in = *over1;
*out1-- = in + f1;
w0 = *wndCurr++;
w1 = *wndCurr++;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
}
/**************************************************************************************
* Function: DecWindowOverlapShort
*
* Description: apply synthesis window, do overlap-add, without clipping
* for winSequence EIGHT-SHORT (does all 8 short blocks)
*
* Inputs: input buffer (output of type-IV DCT)
* overlap buffer (saved from last time)
* window type (sin or KBD) for input buffer
* window type (sin or KBD) for overlap buffer
*
* Outputs: one channel, one frame of 32-bit PCM, non-interleaved
*
* Return: none
*
* Notes: use this function when the decoded PCM is going to the SBR decoder
**************************************************************************************/
void DecWindowOverlapShortNoClip(int *buf0, int *over0, int *out0, int winTypeCurr, int winTypePrev)
{
int i, in, w0, w1, f0, f1;
int *buf1, *over1, *out1;
const int *wndPrev, *wndCurr;
wndPrev = (winTypePrev == 1 ? kbdWindow + kbdWindowOffset[0] : sinWindow + sinWindowOffset[0]);
wndCurr = (winTypeCurr == 1 ? kbdWindow + kbdWindowOffset[0] : sinWindow + sinWindowOffset[0]);
/* pcm[0-447] = 0 + overlap[0-447] */
i = 448;
do {
f0 = *over0++;
f1 = *over0++;
*out0++ = f0;
*out0++ = f1;
i -= 2;
} while (i);
/* pcm[448-575] = Wp[0-127] * block0[0-127] + overlap[448-575] */
out1 = out0 + (128 - 1);
over1 = over0 + 128 - 1;
buf0 += 64;
buf1 = buf0 - 1;
do {
w0 = *wndPrev++; /* W[0], W[1], ...W[63] */
w1 = *wndPrev++; /* W[127], W[126], ... W[64] */
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*out0++ = in - f0;
in = *over1;
*out1-- = in + f1;
w0 = *wndCurr++;
w1 = *wndCurr++;
in = *buf1--;
/* save over0/over1 for next short block, in the slots just vacated */
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
/* pcm[576-703] = Wc[128-255] * block0[128-255] + Wc[0-127] * block1[0-127] + overlap[576-703]
* pcm[704-831] = Wc[128-255] * block1[128-255] + Wc[0-127] * block2[0-127] + overlap[704-831]
* pcm[832-959] = Wc[128-255] * block2[128-255] + Wc[0-127] * block3[0-127] + overlap[832-959]
*/
for (i = 0; i < 3; i++) {
out0 += 64;
out1 = out0 + 128 - 1;
over0 += 64;
over1 = over0 + 128 - 1;
buf0 += 64;
buf1 = buf0 - 1;
wndCurr -= 128;
do {
w0 = *wndCurr++; /* W[0], W[1], ...W[63] */
w1 = *wndCurr++; /* W[127], W[126], ... W[64] */
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *(over0 - 128); /* from last short block */
in += *(over0 + 0); /* from last full frame */
*out0++ = in - f0;
in = *(over1 - 128); /* from last short block */
in += *(over1 + 0); /* from last full frame */
*out1-- = in + f1;
/* save over0/over1 for next short block, in the slots just vacated */
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
}
/* pcm[960-1023] = Wc[128-191] * block3[128-191] + Wc[0-63] * block4[0-63] + overlap[960-1023]
* over[0-63] = Wc[192-255] * block3[192-255] + Wc[64-127] * block4[64-127]
*/
out0 += 64;
over0 -= 832; /* points at overlap[64] */
over1 = over0 + 128 - 1; /* points at overlap[191] */
buf0 += 64;
buf1 = buf0 - 1;
wndCurr -= 128;
do {
w0 = *wndCurr++; /* W[0], W[1], ...W[63] */
w1 = *wndCurr++; /* W[127], W[126], ... W[64] */
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *(over0 + 768); /* from last short block */
in += *(over0 + 896); /* from last full frame */
*out0++ = in - f0;
in = *(over1 + 768); /* from last short block */
*(over1 - 128) = in + f1;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in); /* save in overlap[128-191] */
*over0++ = MULSHIFT32(w1, in); /* save in overlap[64-127] */
} while (over0 < over1);
/* over0 now points at overlap[128] */
/* over[64-191] = Wc[128-255] * block4[128-255] + Wc[0-127] * block5[0-127]
* over[192-319] = Wc[128-255] * block5[128-255] + Wc[0-127] * block6[0-127]
* over[320-447] = Wc[128-255] * block6[128-255] + Wc[0-127] * block7[0-127]
* over[448-576] = Wc[128-255] * block7[128-255]
*/
for (i = 0; i < 3; i++) {
over0 += 64;
over1 = over0 + 128 - 1;
buf0 += 64;
buf1 = buf0 - 1;
wndCurr -= 128;
do {
w0 = *wndCurr++; /* W[0], W[1], ...W[63] */
w1 = *wndCurr++; /* W[127], W[126], ... W[64] */
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
/* from last short block */
*(over0 - 128) -= f0;
*(over1 - 128)+= f1;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
}
/* over[576-1024] = 0 */
i = 448;
over0 += 64;
do {
*over0++ = 0;
*over0++ = 0;
*over0++ = 0;
*over0++ = 0;
i -= 4;
} while (i);
}
|
1137519-player
|
aac/sbrimdct.c
|
C
|
lgpl
| 13,539
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbrtabs.c,v 1.1 2005/02/26 01:47:35 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbrtabs.c - platform-independent tables for SBR (global, read-only)
**************************************************************************************/
#include "sbr.h"
/* k0Tab[sampRateIdx][k] = k0 = startMin + offset(bs_start_freq) for given sample rate (4.6.18.3.2.1)
* downsampled (single-rate) SBR not currently supported
*/
const unsigned char k0Tab[NUM_SAMPLE_RATES_SBR][16] = {
{ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 23, 27, 31 }, /* 96 kHz */
{ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 23, 27, 31 }, /* 88 kHz */
{ 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 21, 23, 26, 30 }, /* 64 kHz */
{ 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 27, 31 }, /* 48 kHz */
{ 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 23, 25, 28, 32 }, /* 44 kHz */
{ 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 27, 29, 32 }, /* 32 kHz */
{ 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 27, 29, 32 }, /* 24 kHz */
{ 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 30 }, /* 22 kHz */
{ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }, /* 16 kHz */
};
/* k2Tab[sampRateIdx][k] = stopVector(bs_stop_freq) for given sample rate, bs_stop_freq = [0, 13] (4.6.18.3.2.1)
* generated with Matlab script calc_stopvec.m
* downsampled (single-rate) SBR not currently supported
*/
const unsigned char k2Tab[NUM_SAMPLE_RATES_SBR][14] = {
{ 13, 15, 17, 19, 21, 24, 27, 31, 35, 39, 44, 50, 57, 64 }, /* 96 kHz */
{ 15, 17, 19, 21, 23, 26, 29, 33, 37, 41, 46, 51, 57, 64 }, /* 88 kHz */
{ 20, 22, 24, 26, 28, 31, 34, 37, 41, 45, 49, 54, 59, 64 }, /* 64 kHz */
{ 21, 23, 25, 27, 29, 32, 35, 38, 41, 45, 49, 54, 59, 64 }, /* 48 kHz */
{ 23, 25, 27, 29, 31, 34, 37, 40, 43, 47, 51, 55, 59, 64 }, /* 44 kHz */
{ 32, 34, 36, 38, 40, 42, 44, 46, 49, 52, 55, 58, 61, 64 }, /* 32 kHz */
{ 32, 34, 36, 38, 40, 42, 44, 46, 49, 52, 55, 58, 61, 64 }, /* 24 kHz */
{ 35, 36, 38, 40, 42, 44, 46, 48, 50, 52, 55, 58, 61, 64 }, /* 22 kHz */
{ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64 }, /* 16 kHz */
};
/* NINT(2.048E6 / Fs) (figure 4.47)
* downsampled (single-rate) SBR not currently supported
*/
const unsigned char goalSBTab[NUM_SAMPLE_RATES_SBR] = {
21, 23, 32, 43, 46, 64, 85, 93, 128
};
const HuffInfo huffTabSBRInfo[10] = {
{19, { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 2, 7, 4, 8, 72, 0}, 0},
{20, { 0, 2, 2, 2, 2, 2, 1, 3, 3, 2, 4, 4, 4, 3, 2, 5, 6, 13, 15, 46}, 121},
{17, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 2, 0, 0, 1, 25, 10, 0, 0, 0}, 242},
{19, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, 1, 0, 1, 1, 2, 1, 29, 2, 0}, 291},
{19, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 1, 2, 5, 1, 4, 2, 3, 34, 0}, 340},
{20, { 1, 1, 1, 1, 1, 1, 0, 2, 2, 2, 2, 2, 1, 2, 3, 4, 4, 7, 10, 16}, 403},
{14, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 13, 2, 0, 0, 0, 0, 0, 0}, 466},
{14, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 6, 8, 0, 0, 0, 0, 0, 0}, 491},
{14, { 1, 1, 1, 1, 1, 1, 0, 2, 0, 1, 1, 0, 51, 2, 0, 0, 0, 0, 0, 0}, 516},
{ 8, { 1, 1, 1, 0, 1, 1, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 579},
};
/* Huffman tables from appendix 4.A.6.1, includes offset of -LAV[i] for table i */
const signed short huffTabSBR[604] = {
/* SBR table sbr_tenv15 [121] (signed) */
0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8,
-9, 8, -10, 9, -11, 10, -12, -13, 11, -14, 12, -15, -16, 13, -19, -18,
-17, 14, -24, -20, 16, -26, -21, 15, -23, -25, -22, -60, -59, -58, -57, -56,
-55, -54, -53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40,
-39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60,
/* SBR table sbr_fenv15 [121] (signed) */
0, -1, 1, -2, -3, 2, -4, 3, -5, 4, -6, 5, -7, 6, -8, 7,
-9, 8, -10, 9, -11, 10, 11, -12, 12, -13, 13, 14, -14, -15, 15, 16,
17, -16, -17, -18, -19, 18, 19, -20, -21, 20, 21, -24, -23, -22, -26, -28,
22, 23, 25, -41, -25, 26, 27, -30, -27, 24, 28, 44, -51, -46, -44, -43,
-37, -33, -31, -29, 30, 37, 42, 47, 48, -60, -59, -58, -57, -56, -55, -54,
-53, -52, -50, -49, -48, -47, -45, -42, -40, -39, -38, -36, -35, -34, -32, 29,
31, 32, 33, 34, 35, 36, 38, 39, 40, 41, 43, 45, 46, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60,
/* SBR table sbr_tenv15b [49] (signed) */
0, 1, -1, 2, -2, 3, -3, 4, -4, -5, 5, -6, 6, 7, -7, 8,
-24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9,
-8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24,
/* SBR table sbr_fenv15b [49] (signed) */
0, -1, 1, -2, 2, 3, -3, -4, 4, -5, 5, -6, 6, -7, 7, 8,
-9, -8, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11,
-10, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24,
/* SBR table sbr_tenv30 [63] (signed) */
0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, -7, 6, -8, 7,
-9, -10, 8, 9, 10, -13, -11, -12, -14, 11, 12, -31, -30, -29, -28, -27,
-26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
/* SBR table sbr_fenv30 [63] (signed) */
0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8,
8, 9, -9, -10, 10, 11, -11, -12, 12, 13, -13, -15, 14, 15, -14, 18,
-18, -24, -19, 16, 17, -22, -21, -16, 20, 21, 22, 25, -23, -20, 24, -31,
-30, -29, -28, -27, -26, -25, -17, 19, 23, 26, 27, 28, 29, 30, 31,
/* SBR table sbr_tenv30b [25] (signed) */
0, 1, -1, -2, 2, 3, -3, -4, 4, -5, -12, -11, -10, -9, -8, -7,
-6, 5, 6, 7, 8, 9, 10, 11, 12,
/* SBR table sbr_fenv30b [25] (signed) */
0, -1, 1, -2, 2, 3, -3, -4, 4, -5, 5, 6, -12, -11, -10, -9,
-8, -7, -6, 7, 8, 9, 10, 11, 12,
/* SBR table sbr_tnoise30 [63] (signed) */
0, 1, -1, -2, 2, -3, 3, -4, 4, -5, 5, 11, -31, -30, -29, -28,
-27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12,
-11, -10, -9, -8, -7, -6, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
/* SBR table sbr_tnoise30b [25] (signed) */
0, -1, 1, -2, 2, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, 3,
4, 5, 6, 7, 8, 9, 10, 11, 12,
};
/* log2Tab[x] = floor(log2(x)), format = Q28 */
const int log2Tab[65] = {
0x00000000, 0x00000000, 0x10000000, 0x195c01a3, 0x20000000, 0x25269e12, 0x295c01a3, 0x2ceaecfe,
0x30000000, 0x32b80347, 0x35269e12, 0x3759d4f8, 0x395c01a3, 0x3b350047, 0x3ceaecfe, 0x3e829fb6,
0x40000000, 0x41663f6f, 0x42b80347, 0x43f782d7, 0x45269e12, 0x4646eea2, 0x4759d4f8, 0x48608280,
0x495c01a3, 0x4a4d3c25, 0x4b350047, 0x4c1404ea, 0x4ceaecfe, 0x4dba4a47, 0x4e829fb6, 0x4f446359,
0x50000000, 0x50b5d69b, 0x51663f6f, 0x52118b11, 0x52b80347, 0x5359ebc5, 0x53f782d7, 0x549101ea,
0x55269e12, 0x55b88873, 0x5646eea2, 0x56d1fafd, 0x5759d4f8, 0x57dea15a, 0x58608280, 0x58df988f,
0x595c01a3, 0x59d5d9fd, 0x5a4d3c25, 0x5ac24113, 0x5b350047, 0x5ba58feb, 0x5c1404ea, 0x5c80730b,
0x5ceaecfe, 0x5d53847a, 0x5dba4a47, 0x5e1f4e51, 0x5e829fb6, 0x5ee44cd5, 0x5f446359, 0x5fa2f045,
0x60000000
};
/* coefficient table 4.A.87, format = Q31
* reordered as:
* cTab[0], cTab[64], cTab[128], cTab[192], cTab[256],
* cTab[2], cTab[66], cTab[130], cTab[194], cTab[258],
* ...
* cTab[64], cTab[128], cTab[192], cTab[256], cTab[320]
*
* NOTE: cTab[1, 2, ... , 318, 319] = cTab[639, 638, ... 322, 321]
* except cTab[384] = -cTab[256], cTab[512] = -cTab[128]
*/
const int cTabA[165] = {
0x00000000, 0x0055dba1, 0x01b2e41d, 0x09015651, 0x2e3a7532, 0xffed978a, 0x006090c4, 0x01fd3ba0, 0x08a24899, 0x311af3a4,
0xfff0065d, 0x006b47fa, 0x024bf7a1, 0x082f552e, 0x33ff670e, 0xffef7b8b, 0x0075fded, 0x029e35b4, 0x07a8127d, 0x36e69691,
0xffee1650, 0x00807994, 0x02f3e48d, 0x070bbf58, 0x39ce0477, 0xffecc31b, 0x008a7dd7, 0x034d01f0, 0x06593912, 0x3cb41219,
0xffeb50b2, 0x009424c6, 0x03a966bb, 0x0590a67d, 0x3f962fb8, 0xffe9ca76, 0x009d10bf, 0x04083fec, 0x04b0adcb, 0x4272a385,
0xffe88ba8, 0x00a520bb, 0x04694101, 0x03b8f8dc, 0x4547daea, 0xffe79e16, 0x00abe79e, 0x04cc2fcf, 0x02a99097, 0x4812f848,
0xffe6d466, 0x00b1978d, 0x05303f87, 0x01816e06, 0x4ad237a2, 0xffe65416, 0x00b5c867, 0x05950122, 0x0040c496, 0x4d83976c,
0xffe66dd0, 0x00b8394b, 0x05f9c051, 0xfee723c6, 0x5024d70e, 0xffe69423, 0x00b8c6b0, 0x065dd56a, 0xfd7475d8, 0x52b449de,
0xffe75361, 0x00b73ab0, 0x06c0f0c0, 0xfbe8f5bd, 0x552f8ff7, 0xffe85b4b, 0x00b36acd, 0x0721bf22, 0xfa44a069, 0x579505f5,
0xffea353a, 0x00acbd2f, 0x077fedb3, 0xf887507c, 0x59e2f69e, 0xffec8409, 0x00a3508f, 0x07da2b7f, 0xf6b1f3c3, 0x5c16d0ae,
0xffef2395, 0x0096dcc2, 0x08303897, 0xf4c473c6, 0x5e2f6367, 0xfff294c3, 0x00872c63, 0x0880ffdd, 0xf2bf6ea4, 0x602b0c7f,
0xfff681d6, 0x007400b8, 0x08cb4e23, 0xf0a3959f, 0x6207f220, 0xfffb42b0, 0x005d36df, 0x090ec1fc, 0xee71b2fe, 0x63c45243,
0x00007134, 0x00426f36, 0x0949eaac, 0xec2a3f5f, 0x655f63f2, 0x0006b1cf, 0x0023b989, 0x097c1ee8, 0xe9cea84a, 0x66d76725,
0x000d31b5, 0x0000e790, 0x09a3e163, 0xe75f8bb8, 0x682b39a4, 0x001471f8, 0xffda17f2, 0x09c0e59f, 0xe4de0cb0, 0x6959709d,
0x001c3549, 0xffaea5d6, 0x09d19ca9, 0xe24b8f66, 0x6a619c5e, 0x0024dd50, 0xff7ee3f1, 0x09d5560b, 0xdfa93ab5, 0x6b42a864,
0x002d8e42, 0xff4aabc8, 0x09caeb0f, 0xdcf898fb, 0x6bfbdd98, 0x003745f9, 0xff120d70, 0x09b18a1d, 0xda3b176a, 0x6c8c4c7a,
0x004103f4, 0xfed4bec3, 0x09881dc5, 0xd7722f04, 0x6cf4073e, 0x004b6c46, 0xfe933dc0, 0x094d7ec2, 0xd49fd55f, 0x6d32730f,
0x0055dba1, 0x01b2e41d, 0x09015651, 0x2e3a7532, 0x6d474e1d,
};
/* coefficient table 4.A.87, format = Q31
* reordered as cTab[0], cTab[64], cTab[128], ... cTab[576], cTab[1], cTab[65], cTab[129], ... cTab[639]
* keeping full table (not using symmetry) to allow sequential access in synth filter inner loop
* format = Q31
*/
const int cTabS[640] = {
0x00000000, 0x0055dba1, 0x01b2e41d, 0x09015651, 0x2e3a7532, 0x6d474e1d, 0xd1c58ace, 0x09015651, 0xfe4d1be3, 0x0055dba1,
0xffede50e, 0x005b5371, 0x01d78bfc, 0x08d3e41b, 0x2faa221c, 0x6d41d963, 0xd3337b3d, 0x09299ead, 0xfe70b8d1, 0x0050b177,
0xffed978a, 0x006090c4, 0x01fd3ba0, 0x08a24899, 0x311af3a4, 0x6d32730f, 0xd49fd55f, 0x094d7ec2, 0xfe933dc0, 0x004b6c46,
0xffefc9b9, 0x0065fde5, 0x02244a24, 0x086b1eeb, 0x328cc6f0, 0x6d18520e, 0xd60a46e5, 0x096d0e21, 0xfeb48d0d, 0x00465348,
0xfff0065d, 0x006b47fa, 0x024bf7a1, 0x082f552e, 0x33ff670e, 0x6cf4073e, 0xd7722f04, 0x09881dc5, 0xfed4bec3, 0x004103f4,
0xffeff6ca, 0x0070c8a5, 0x0274ba43, 0x07ee507c, 0x3572ec70, 0x6cc59bab, 0xd8d7f21f, 0x099ec3dc, 0xfef3f6ab, 0x003c1fa4,
0xffef7b8b, 0x0075fded, 0x029e35b4, 0x07a8127d, 0x36e69691, 0x6c8c4c7a, 0xda3b176a, 0x09b18a1d, 0xff120d70, 0x003745f9,
0xffeedfa4, 0x007b3875, 0x02c89901, 0x075ca90c, 0x385a49c4, 0x6c492217, 0xdb9b5b12, 0x09c018ce, 0xff2ef725, 0x00329ab6,
0xffee1650, 0x00807994, 0x02f3e48d, 0x070bbf58, 0x39ce0477, 0x6bfbdd98, 0xdcf898fb, 0x09caeb0f, 0xff4aabc8, 0x002d8e42,
0xffed651d, 0x0085c217, 0x03201116, 0x06b559c3, 0x3b415115, 0x6ba4629f, 0xde529086, 0x09d1fa23, 0xff6542d1, 0x00293718,
0xffecc31b, 0x008a7dd7, 0x034d01f0, 0x06593912, 0x3cb41219, 0x6b42a864, 0xdfa93ab5, 0x09d5560b, 0xff7ee3f1, 0x0024dd50,
0xffebe77b, 0x008f4bfc, 0x037ad438, 0x05f7fb90, 0x3e25b17e, 0x6ad73e8d, 0xe0fc421e, 0x09d52709, 0xff975c01, 0x002064f8,
0xffeb50b2, 0x009424c6, 0x03a966bb, 0x0590a67d, 0x3f962fb8, 0x6a619c5e, 0xe24b8f66, 0x09d19ca9, 0xffaea5d6, 0x001c3549,
0xffea9192, 0x0098b855, 0x03d8afe6, 0x05237f9d, 0x41058bc6, 0x69e29784, 0xe396a45d, 0x09cab9f2, 0xffc4e365, 0x0018703f,
0xffe9ca76, 0x009d10bf, 0x04083fec, 0x04b0adcb, 0x4272a385, 0x6959709d, 0xe4de0cb0, 0x09c0e59f, 0xffda17f2, 0x001471f8,
0xffe940f4, 0x00a1039c, 0x043889c6, 0x0437fb0a, 0x43de620a, 0x68c7269b, 0xe620c476, 0x09b3d77f, 0xffee183b, 0x0010bc63,
0xffe88ba8, 0x00a520bb, 0x04694101, 0x03b8f8dc, 0x4547daea, 0x682b39a4, 0xe75f8bb8, 0x09a3e163, 0x0000e790, 0x000d31b5,
0xffe83a07, 0x00a8739d, 0x049aa82f, 0x03343533, 0x46aea856, 0x6785c24d, 0xe89971b7, 0x099140a7, 0x00131c75, 0x0009aa3f,
0xffe79e16, 0x00abe79e, 0x04cc2fcf, 0x02a99097, 0x4812f848, 0x66d76725, 0xe9cea84a, 0x097c1ee8, 0x0023b989, 0x0006b1cf,
0xffe7746e, 0x00af374c, 0x04fe20be, 0x02186a91, 0x4973fef1, 0x661fd6b8, 0xeafee7f1, 0x0963ed46, 0x0033b927, 0x00039609,
0xffe6d466, 0x00b1978d, 0x05303f87, 0x01816e06, 0x4ad237a2, 0x655f63f2, 0xec2a3f5f, 0x0949eaac, 0x00426f36, 0x00007134,
0xffe6afee, 0x00b3d15c, 0x05626209, 0x00e42fa2, 0x4c2ca3df, 0x64964063, 0xed50a31d, 0x092d7970, 0x00504f41, 0xfffdfa25,
0xffe65416, 0x00b5c867, 0x05950122, 0x0040c496, 0x4d83976c, 0x63c45243, 0xee71b2fe, 0x090ec1fc, 0x005d36df, 0xfffb42b0,
0xffe681c6, 0x00b74c37, 0x05c76fed, 0xff96db90, 0x4ed62be3, 0x62ea6474, 0xef8d4d7b, 0x08edfeaa, 0x006928a0, 0xfff91fca,
0xffe66dd0, 0x00b8394b, 0x05f9c051, 0xfee723c6, 0x5024d70e, 0x6207f220, 0xf0a3959f, 0x08cb4e23, 0x007400b8, 0xfff681d6,
0xffe66fac, 0x00b8fe0d, 0x062bf5ec, 0xfe310657, 0x516eefb9, 0x611d58a3, 0xf1b461ab, 0x08a75da4, 0x007e0393, 0xfff48700,
0xffe69423, 0x00b8c6b0, 0x065dd56a, 0xfd7475d8, 0x52b449de, 0x602b0c7f, 0xf2bf6ea4, 0x0880ffdd, 0x00872c63, 0xfff294c3,
0xffe6fed4, 0x00b85f70, 0x068f8b44, 0xfcb1d740, 0x53f495aa, 0x5f30ff5f, 0xf3c4e887, 0x08594887, 0x008f87aa, 0xfff0e7ef,
0xffe75361, 0x00b73ab0, 0x06c0f0c0, 0xfbe8f5bd, 0x552f8ff7, 0x5e2f6367, 0xf4c473c6, 0x08303897, 0x0096dcc2, 0xffef2395,
0xffe80414, 0x00b58c8c, 0x06f1825d, 0xfb19b7bd, 0x56654bdd, 0x5d26be9b, 0xf5be0fa9, 0x08061671, 0x009da526, 0xffedc418,
0xffe85b4b, 0x00b36acd, 0x0721bf22, 0xfa44a069, 0x579505f5, 0x5c16d0ae, 0xf6b1f3c3, 0x07da2b7f, 0x00a3508f, 0xffec8409,
0xffe954d0, 0x00b06b68, 0x075112a2, 0xf96916f5, 0x58befacd, 0x5b001db8, 0xf79fa13a, 0x07ad8c26, 0x00a85e94, 0xffeb3849,
0xffea353a, 0x00acbd2f, 0x077fedb3, 0xf887507c, 0x59e2f69e, 0x59e2f69e, 0xf887507c, 0x077fedb3, 0x00acbd2f, 0xffea353a,
0xffeb3849, 0x00a85e94, 0x07ad8c26, 0xf79fa13a, 0x5b001db8, 0x58befacd, 0xf96916f5, 0x075112a2, 0x00b06b68, 0xffe954d0,
0xffec8409, 0x00a3508f, 0x07da2b7f, 0xf6b1f3c3, 0x5c16d0ae, 0x579505f5, 0xfa44a069, 0x0721bf22, 0x00b36acd, 0xffe85b4b,
0xffedc418, 0x009da526, 0x08061671, 0xf5be0fa9, 0x5d26be9b, 0x56654bdd, 0xfb19b7bd, 0x06f1825d, 0x00b58c8c, 0xffe80414,
0xffef2395, 0x0096dcc2, 0x08303897, 0xf4c473c6, 0x5e2f6367, 0x552f8ff7, 0xfbe8f5bd, 0x06c0f0c0, 0x00b73ab0, 0xffe75361,
0xfff0e7ef, 0x008f87aa, 0x08594887, 0xf3c4e887, 0x5f30ff5f, 0x53f495aa, 0xfcb1d740, 0x068f8b44, 0x00b85f70, 0xffe6fed4,
0xfff294c3, 0x00872c63, 0x0880ffdd, 0xf2bf6ea4, 0x602b0c7f, 0x52b449de, 0xfd7475d8, 0x065dd56a, 0x00b8c6b0, 0xffe69423,
0xfff48700, 0x007e0393, 0x08a75da4, 0xf1b461ab, 0x611d58a3, 0x516eefb9, 0xfe310657, 0x062bf5ec, 0x00b8fe0d, 0xffe66fac,
0xfff681d6, 0x007400b8, 0x08cb4e23, 0xf0a3959f, 0x6207f220, 0x5024d70e, 0xfee723c6, 0x05f9c051, 0x00b8394b, 0xffe66dd0,
0xfff91fca, 0x006928a0, 0x08edfeaa, 0xef8d4d7b, 0x62ea6474, 0x4ed62be3, 0xff96db90, 0x05c76fed, 0x00b74c37, 0xffe681c6,
0xfffb42b0, 0x005d36df, 0x090ec1fc, 0xee71b2fe, 0x63c45243, 0x4d83976c, 0x0040c496, 0x05950122, 0x00b5c867, 0xffe65416,
0xfffdfa25, 0x00504f41, 0x092d7970, 0xed50a31d, 0x64964063, 0x4c2ca3df, 0x00e42fa2, 0x05626209, 0x00b3d15c, 0xffe6afee,
0x00007134, 0x00426f36, 0x0949eaac, 0xec2a3f5f, 0x655f63f2, 0x4ad237a2, 0x01816e06, 0x05303f87, 0x00b1978d, 0xffe6d466,
0x00039609, 0x0033b927, 0x0963ed46, 0xeafee7f1, 0x661fd6b8, 0x4973fef1, 0x02186a91, 0x04fe20be, 0x00af374c, 0xffe7746e,
0x0006b1cf, 0x0023b989, 0x097c1ee8, 0xe9cea84a, 0x66d76725, 0x4812f848, 0x02a99097, 0x04cc2fcf, 0x00abe79e, 0xffe79e16,
0x0009aa3f, 0x00131c75, 0x099140a7, 0xe89971b7, 0x6785c24d, 0x46aea856, 0x03343533, 0x049aa82f, 0x00a8739d, 0xffe83a07,
0x000d31b5, 0x0000e790, 0x09a3e163, 0xe75f8bb8, 0x682b39a4, 0x4547daea, 0x03b8f8dc, 0x04694101, 0x00a520bb, 0xffe88ba8,
0x0010bc63, 0xffee183b, 0x09b3d77f, 0xe620c476, 0x68c7269b, 0x43de620a, 0x0437fb0a, 0x043889c6, 0x00a1039c, 0xffe940f4,
0x001471f8, 0xffda17f2, 0x09c0e59f, 0xe4de0cb0, 0x6959709d, 0x4272a385, 0x04b0adcb, 0x04083fec, 0x009d10bf, 0xffe9ca76,
0x0018703f, 0xffc4e365, 0x09cab9f2, 0xe396a45d, 0x69e29784, 0x41058bc6, 0x05237f9d, 0x03d8afe6, 0x0098b855, 0xffea9192,
0x001c3549, 0xffaea5d6, 0x09d19ca9, 0xe24b8f66, 0x6a619c5e, 0x3f962fb8, 0x0590a67d, 0x03a966bb, 0x009424c6, 0xffeb50b2,
0x002064f8, 0xff975c01, 0x09d52709, 0xe0fc421e, 0x6ad73e8d, 0x3e25b17e, 0x05f7fb90, 0x037ad438, 0x008f4bfc, 0xffebe77b,
0x0024dd50, 0xff7ee3f1, 0x09d5560b, 0xdfa93ab5, 0x6b42a864, 0x3cb41219, 0x06593912, 0x034d01f0, 0x008a7dd7, 0xffecc31b,
0x00293718, 0xff6542d1, 0x09d1fa23, 0xde529086, 0x6ba4629f, 0x3b415115, 0x06b559c3, 0x03201116, 0x0085c217, 0xffed651d,
0x002d8e42, 0xff4aabc8, 0x09caeb0f, 0xdcf898fb, 0x6bfbdd98, 0x39ce0477, 0x070bbf58, 0x02f3e48d, 0x00807994, 0xffee1650,
0x00329ab6, 0xff2ef725, 0x09c018ce, 0xdb9b5b12, 0x6c492217, 0x385a49c4, 0x075ca90c, 0x02c89901, 0x007b3875, 0xffeedfa4,
0x003745f9, 0xff120d70, 0x09b18a1d, 0xda3b176a, 0x6c8c4c7a, 0x36e69691, 0x07a8127d, 0x029e35b4, 0x0075fded, 0xffef7b8b,
0x003c1fa4, 0xfef3f6ab, 0x099ec3dc, 0xd8d7f21f, 0x6cc59bab, 0x3572ec70, 0x07ee507c, 0x0274ba43, 0x0070c8a5, 0xffeff6ca,
0x004103f4, 0xfed4bec3, 0x09881dc5, 0xd7722f04, 0x6cf4073e, 0x33ff670e, 0x082f552e, 0x024bf7a1, 0x006b47fa, 0xfff0065d,
0x00465348, 0xfeb48d0d, 0x096d0e21, 0xd60a46e5, 0x6d18520e, 0x328cc6f0, 0x086b1eeb, 0x02244a24, 0x0065fde5, 0xffefc9b9,
0x004b6c46, 0xfe933dc0, 0x094d7ec2, 0xd49fd55f, 0x6d32730f, 0x311af3a4, 0x08a24899, 0x01fd3ba0, 0x006090c4, 0xffed978a,
0x0050b177, 0xfe70b8d1, 0x09299ead, 0xd3337b3d, 0x6d41d963, 0x2faa221c, 0x08d3e41b, 0x01d78bfc, 0x005b5371, 0xffede50f,
};
/* noise table 4.A.88, format = Q31 */
const int noiseTab[512*2] = {
0x8010fd38, 0xb3dc7948, 0x7c4e2301, 0xa9904192, 0x121622a7, 0x86489625, 0xc3d53d25, 0xd0343fa9,
0x674d6f70, 0x25f4e9fd, 0xce1a8c8b, 0x72a726c5, 0xfea6efc6, 0xaa4adb1a, 0x8b2dd628, 0xf14029e4,
0x46321c1a, 0x604889a0, 0x33363b63, 0x815ed069, 0x802b4315, 0x8f2bf7f3, 0x85b86073, 0x745cfb46,
0xc57886b3, 0xb76731f0, 0xa2a66772, 0x828ca631, 0x60cc145e, 0x1ad1010f, 0x090c83d4, 0x9bd7ba87,
0x5f5aeea2, 0x8b4dbd99, 0x848e7b1e, 0x86bb9fa2, 0x26f18ae5, 0xc0b81194, 0x553407bf, 0x52c17953,
0x755f468d, 0x166b04f8, 0xa5687981, 0x4343248b, 0xa6558d5e, 0xc5f6fab7, 0x80a4fb8c, 0x8cb53cb7,
0x7da68a54, 0x9cd8df8a, 0xba05376c, 0xfcb58ee2, 0xfdd657a4, 0x005e35ca, 0x91c75c55, 0x367651e6,
0x816abf85, 0x8f831c4f, 0x423f9c9c, 0x55aa919e, 0x80779834, 0xb59f4244, 0x800a095c, 0x7de9e0cc,
0x46bda5cb, 0x4c184464, 0x2c438f71, 0x797216b5, 0x5035cee6, 0xa0c3a26e, 0x9d3f95fa, 0xd4a100c0,
0x8ac30dac, 0x04b87397, 0x9e5ac516, 0x8b0b442e, 0x66210ad6, 0x88ba7598, 0x45b9bd33, 0xf0be5087,
0x9261b85e, 0x364f6a31, 0x891c4b50, 0x23ad08ce, 0xf10366a6, 0x80414276, 0x1b562e06, 0x8be21591,
0x9e798195, 0x7fb4045c, 0x7d9506cf, 0x854e691f, 0x9207f092, 0x7a94c9d5, 0x88911536, 0x3f45cc61,
0x27059279, 0xa5b57109, 0x6d2bb67b, 0x3bdc5379, 0x74e662d8, 0x80348f8c, 0xf875e638, 0x5a8caea1,
0x2459ae75, 0x2c54b939, 0x79ee3203, 0xb9bc8683, 0x9b6f630c, 0x9f45b351, 0x8563b2b9, 0xe5dbba41,
0x697c7d0d, 0x7bb7c90e, 0xac900866, 0x8e6b5177, 0x8822dd37, 0x7fd5a91e, 0x7506da05, 0x82302aca,
0xa5e4be04, 0x4b4288eb, 0x00b8bc9f, 0x4f1033e4, 0x7200d612, 0x43900c8c, 0xa815b900, 0x676ed1d4,
0x5c5f23b2, 0xa758ee11, 0xaf73abfa, 0x11714ec0, 0x265239e0, 0xc50de679, 0x8a84e341, 0xa1438354,
0x7f1a341f, 0x343ec96b, 0x696e71b0, 0xa13bde39, 0x81e75094, 0x80091111, 0x853a73bf, 0x80f9c1ee,
0xe4980086, 0x886a8e28, 0xa7e89426, 0xdd93edd7, 0x7592100d, 0x0bfa8123, 0x850a26d4, 0x2e34f395,
0x421b6c00, 0xa4a462e4, 0x4e3f5090, 0x3c189f4c, 0x3c971a56, 0xdd0376d2, 0x747a5367, 0x7bcbc9d7,
0x3966be6a, 0x7efda616, 0x55445e15, 0x7ba2ab3f, 0x5fe684f2, 0x8cf42af9, 0x808c61c3, 0x4390c27b,
0x7cac62ff, 0xea6cab22, 0x5d0902ad, 0xc27b7208, 0x7a27389d, 0x5820a357, 0xa29bbe59, 0x9df0f1fd,
0x92bd67e5, 0x7195b587, 0x97cac65b, 0x8339807e, 0x8f72d832, 0x5fad8685, 0xa462d9d3, 0x81d46214,
0x6ae93e1d, 0x6b23a5b9, 0xc2732874, 0x81795268, 0x7c568cb6, 0x668513ea, 0x428d024e, 0x66b78b3a,
0xfee9ef03, 0x9ddcbb82, 0xa605f07e, 0x46dc55e0, 0x85415054, 0xc89ec271, 0x7c42edfb, 0x0befe59b,
0x89b8f607, 0x6d732a1a, 0xa7081ebd, 0x7e403258, 0x21feeb7b, 0x5dd7a1e7, 0x23e3a31a, 0x129bc896,
0xa11a6b54, 0x7f1e031c, 0xfdc1a4d1, 0x96402e53, 0xb9700f1a, 0x8168ecd6, 0x7d63d3cc, 0x87a70d65,
0x81075a7a, 0x55c8caa7, 0xa95d00b5, 0x102b1652, 0x0bb30215, 0xe5b63237, 0xa446ca44, 0x82d4c333,
0x67b2e094, 0x44c3d661, 0x33fd6036, 0xde1ea2a1, 0xa95e8e47, 0x78f66eb9, 0x6f2aef1e, 0xe8887247,
0x80a3b70e, 0xfca0d9d3, 0x6bf0fd20, 0x0d5226de, 0xf4341c87, 0x5902df05, 0x7ff1a38d, 0xf02e5a5b,
0x99f129af, 0x8ac63d01, 0x7b53f599, 0x7bb32532, 0x99ac59b0, 0x5255a80f, 0xf1320a41, 0x2497aa5c,
0xcce60bd8, 0x787c634b, 0x7ed58c5b, 0x8a28eb3a, 0x24a5e647, 0x8b79a2c1, 0x955f5ce5, 0xa9d12bc4,
0x7a1e20c6, 0x3eeda7ac, 0xf7be823a, 0x042924ce, 0x808b3f03, 0x364248da, 0xac2895e5, 0x69a8b5fa,
0x97fe8b63, 0xbdeac9aa, 0x8073e0ad, 0x6c25dba7, 0x005e51d2, 0x52e74389, 0x59d3988c, 0xe5d1f39c,
0x7b57dc91, 0x341adbe7, 0xa7d42b8d, 0x74e9f335, 0xd35bf7d8, 0x5b7c0a4b, 0x75bc0874, 0x552129bf,
0x8144b70d, 0x6de93bbb, 0x5825f14b, 0x473ec5ca, 0x80a8f37c, 0xe6552d69, 0x7898360b, 0x806379b0,
0xa9b59339, 0x3f6bf60c, 0xc367d731, 0x920ade99, 0x125592f7, 0x877e5ed1, 0xda895d95, 0x075f2ece,
0x380e5f5e, 0x9b006b62, 0xd17a6dd2, 0x530a0e13, 0xf4cc9a14, 0x7d0a0ed4, 0x847c6e3f, 0xbaee4975,
0x47131163, 0x64fb2cac, 0x5e2100a6, 0x7b756a42, 0xd87609f4, 0x98bfe48c, 0x0493745e, 0x836c5784,
0x7e5ccb40, 0x3df6b476, 0x97700d28, 0x8bbd93fd, 0x56de9cdb, 0x680b4e65, 0xebc3d90e, 0x6d286793,
0x6753712e, 0xe05c98a7, 0x3d2b6b85, 0xc4b18ddb, 0x7b59b869, 0x31435688, 0x811888e9, 0xe011ee7a,
0x6a5844f9, 0x86ae35ea, 0xb4cbc10b, 0x01a6f5d6, 0x7a49ed64, 0x927caa49, 0x847ddaed, 0xae0d9bb6,
0x836bdb04, 0x0fd810a6, 0x74fe126b, 0x4a346b5f, 0x80184d36, 0x5afd153c, 0x90cc8102, 0xe606d0e6,
0xde69aa58, 0xa89f1222, 0xe06df715, 0x8fd16144, 0x0317c3e8, 0x22ce92fc, 0x690c3eca, 0x93166f02,
0x71573414, 0x8d43cffb, 0xe8bd0bb6, 0xde86770f, 0x0bf99a41, 0x4633a661, 0xba064108, 0x7adafae3,
0x2f6cde5d, 0xb350a52c, 0xa5ebfb0b, 0x74c57b46, 0xd3b603b5, 0x80b70892, 0xa7f7fa53, 0xd94b566c,
0xdda3fd86, 0x6a635793, 0x3ed005ca, 0xc5f087d8, 0x31e3a746, 0x7a4278f9, 0x82def1f9, 0x06caa2b2,
0xe9d2c349, 0x8940e7f7, 0x7feef8dd, 0x4a9b01f0, 0xacde69f8, 0x57ddc280, 0xf09e4ba4, 0xb6d9f729,
0xb48c18f2, 0xd3654aa9, 0xca7a03c8, 0x14d57545, 0x7fda87a5, 0x0e411366, 0xb77d0df0, 0x8c2aa467,
0x787f2590, 0x2d292db1, 0x9f12682c, 0x44ac364d, 0x1a4b31a6, 0x871f7ded, 0x7ff99167, 0x6630a1d5,
0x25385eb9, 0x2d4dd549, 0xaf8a7004, 0x319ebe0f, 0x379ab730, 0x81dc56a4, 0x822d8523, 0x1ae8554c,
0x18fa0786, 0x875f7de4, 0x85ca350f, 0x7de818dc, 0x7786a38f, 0xa5456355, 0x92e60f88, 0xf5526122,
0x916039bc, 0xc561e2de, 0x31c42042, 0x7c82e290, 0x75d158b2, 0xb015bda1, 0x7220c750, 0x46565441,
0xd0da1fdd, 0x7b777481, 0x782e73c6, 0x8cd72b7b, 0x7f1006aa, 0xfb30e51e, 0x87994818, 0x34e7c7db,
0x7faae06b, 0xea74fbc0, 0xd20c7af4, 0xc44f396b, 0x06b4234e, 0xdf2e2a93, 0x2efb07c8, 0xce861911,
0x7550ea05, 0xd8d90bbb, 0x58522eec, 0x746b3520, 0xce844ce9, 0x7f5cacc3, 0xda8f17e0, 0x2fedf9cb,
0xb2f77ec4, 0x6f13f4c0, 0x834de085, 0x7b7ace4b, 0x713b16ac, 0x499c5ab0, 0x06a7961d, 0x1b39a48a,
0xbb853e6e, 0x7c781cc1, 0xc0baebf5, 0x7dace394, 0x815ceebc, 0xcc7b27d4, 0x8274b181, 0xa2be40a2,
0xdd01d5dc, 0x7fefeb14, 0x0813ec78, 0xba3077cc, 0xe5cf1e1c, 0xedcfacae, 0x54c43a9b, 0x5cd62a42,
0x93806b55, 0x03095c5b, 0x8e076ae3, 0x71bfcd2a, 0x7ac1989b, 0x623bc71a, 0x5e15d4d2, 0xfb341dd1,
0xd75dfbca, 0xd0da32be, 0xd4569063, 0x337869da, 0x3d30606a, 0xcd89cca2, 0x7dd2ae36, 0x028c03cd,
0xd85e052c, 0xe8dc9ec5, 0x7ffd9241, 0xde5bf4c6, 0x88c4b235, 0x8228be2e, 0x7fe6ec64, 0x996abe6a,
0xdeb0666d, 0x9eb86611, 0xd249b922, 0x18b3e26b, 0x80211168, 0x5f8bb99c, 0x6ecb0dd2, 0x4728ff8d,
0x2ac325b8, 0x6e5169d2, 0x7ebbd68d, 0x05e41d17, 0xaaa19f28, 0x8ab238a6, 0x51f105be, 0x140809cc,
0x7f7345d9, 0x3aae5a9d, 0xaecec6e4, 0x1afb3473, 0xf6229ed1, 0x8d55f467, 0x7e32003a, 0x70f30c14,
0x6686f33f, 0xd0d45ed8, 0x644fab57, 0x3a3fbbd3, 0x0b255fc4, 0x679a1701, 0x90e17b6e, 0x325d537b,
0xcd7b9b87, 0xaa7be2a2, 0x7d47c966, 0xa33dbce5, 0x8659c3bb, 0x72a41367, 0x15c446e0, 0x45fe8b0a,
0x9d8ddf26, 0x84d47643, 0x7fabe0da, 0x36a70122, 0x7a28ebfe, 0x7c29b8b8, 0x7f760406, 0xbabe4672,
0x23ea216e, 0x92bcc50a, 0x6d20dba2, 0xad5a7c7e, 0xbf3897f5, 0xabb793e1, 0x8391fc7e, 0xe270291c,
0x7a248d58, 0x80f8fd15, 0x83ef19f3, 0x5e6ece7d, 0x278430c1, 0x35239f4d, 0xe09c073b, 0x50e78cb5,
0xd4b811bd, 0xce834ee0, 0xf88aaa34, 0xf71da5a9, 0xe2b0a1d5, 0x7c3aef31, 0xe84eabca, 0x3ce25964,
0xf29336d3, 0x8fa78b2c, 0xa3fc3415, 0x63e1313d, 0x7fbc74e0, 0x7340bc93, 0x49ae583b, 0x8b79de4b,
0x25011ce9, 0x7b462279, 0x36007db0, 0x3da1599c, 0x77780772, 0xc845c9bb, 0x83ba68be, 0x6ee507d1,
0x2f0159b8, 0x5392c4ed, 0x98336ff6, 0x0b3c7f11, 0xde697aac, 0x893fc8d0, 0x6b83f8f3, 0x47799a0d,
0x801d9dfc, 0x8516a83e, 0x5f8d22ec, 0x0f8ba384, 0xa049dc4b, 0xdd920b05, 0x7a99bc9f, 0x9ad19344,
0x7a345dba, 0xf501a13f, 0x3e58bf19, 0x7fffaf9a, 0x3b4e1511, 0x0e08b991, 0x9e157620, 0x7230a326,
0x4977f9ff, 0x2d2bbae1, 0x607aa7fc, 0x7bc85d5f, 0xb441bbbe, 0x8d8fa5f2, 0x601cce26, 0xda1884f2,
0x81c82d64, 0x200b709c, 0xcbd36abe, 0x8cbdddd3, 0x55ab61d3, 0x7e3ee993, 0x833f18aa, 0xffc1aaea,
0x7362e16a, 0x7fb85db2, 0x904ee04c, 0x7f04dca6, 0x8ad7a046, 0xebe7d8f7, 0xfbc4c687, 0xd0609458,
0x093ed977, 0x8e546085, 0x7f5b8236, 0x7c47e118, 0xa01f2641, 0x7ffb3e48, 0x05de7cda, 0x7fc281b9,
0x8e0278fc, 0xd74e6d07, 0x94c24450, 0x7cf9e641, 0x2ad27871, 0x919fa815, 0x805fd205, 0x7758397f,
0xe2c7e02c, 0x1828e194, 0x5613d6fe, 0xfb55359f, 0xf9699516, 0x8978ee26, 0x7feebad9, 0x77d71d82,
0x55b28b60, 0x7e997600, 0x80821a6b, 0xc6d78af1, 0x691822ab, 0x7f6982a0, 0x7ef56f99, 0x5c307f40,
0xac6f8b76, 0x42cc8ba4, 0x782c61d9, 0xa0224dd0, 0x7bd234d1, 0x74576e3b, 0xe38cfe9a, 0x491e66ef,
0xc78291c5, 0x895bb87f, 0x924f7889, 0x71b89394, 0x757b779d, 0xc4a9c604, 0x5cdf7829, 0x8020e9df,
0x805e8245, 0x4a82c398, 0x6360bd62, 0x78bb60fc, 0x09e0d014, 0x4b0ea180, 0xb841978b, 0x69a0e864,
0x7df35977, 0x3284b0dd, 0x3cdc2efd, 0x57d31f5e, 0x541069cc, 0x1776e92e, 0x04309ea3, 0xa015eb2d,
0xce7bfabc, 0x41b638f8, 0x8365932e, 0x846ab44c, 0xbbcc80cb, 0x8afa6cac, 0x7fc422ea, 0x4e403fc0,
0xbfac9aee, 0x8e4c6709, 0x028e01fb, 0x6d160a9b, 0x7fe93004, 0x790f9cdc, 0x6a1f37a0, 0xf7e7ef30,
0xb4ea0f04, 0x7bf4c8e6, 0xe981701f, 0xc258a9d3, 0x6acbbfba, 0xef5479c7, 0x079c8bd8, 0x1a410f56,
0x6853b799, 0x86cd4f01, 0xc66e23b6, 0x34585565, 0x8d1fe00d, 0x7fcdba1a, 0x32c9717b, 0xa02f9f48,
0xf64940db, 0x5ed7d8f1, 0x61b823b2, 0x356f8918, 0xa0a7151e, 0x793fc969, 0x530beaeb, 0x34e93270,
0x4fc4ddb5, 0x88d58b6c, 0x36094774, 0xf620ac80, 0x03763a72, 0xf910c9a6, 0x6666fb2d, 0x752c8be8,
0x9a6dfdd8, 0xd1a7117d, 0x51c1b1d4, 0x0a67773d, 0x43b32a79, 0x4cdcd085, 0x5f067d30, 0x05bfe92a,
0x7ed7d203, 0xe71a3c85, 0x99127ce2, 0x8eb3cac4, 0xad4bbcea, 0x5c6a0fd0, 0x0eec04af, 0x94e95cd4,
0x8654f921, 0x83eabb5d, 0xb058d7ca, 0x69f12d3c, 0x03d881b2, 0x80558ef7, 0x82938cb3, 0x2ec0e1d6,
0x80044422, 0xd1e47051, 0x720fc6ff, 0x82b20316, 0x0d527b02, 0x63049a15, 0x7ad5b9ad, 0xd2a4641d,
0x41144f86, 0x7b04917a, 0x15c4a2c0, 0x9da07916, 0x211df54a, 0x7fdd09af, 0xfe924f3f, 0x7e132cfe,
0x9a1d18d6, 0x7c56508b, 0x80f0f0af, 0x8095ced6, 0x8037d0d7, 0x026719d1, 0xa55fec43, 0x2b1c7cb7,
0xa5cd5ac1, 0x77639fad, 0x7fcd8b62, 0x81a18c27, 0xaee4912e, 0xeae9eebe, 0xeb3081de, 0x8532aada,
0xc822362e, 0x86a649a9, 0x8031a71d, 0x7b319dc6, 0xea8022e6, 0x814bc5a9, 0x8f62f7a1, 0xa430ea17,
0x388deafb, 0x883b5185, 0x776fe13c, 0x801c683f, 0x87c11b98, 0xb7cbc644, 0x8e9ad3e8, 0x3cf5a10c,
0x7ff6a634, 0x949ef096, 0x9f84aa7c, 0x010af13f, 0x782d1de8, 0xf18e492a, 0x6cf63b01, 0x4301cd81,
0x32d15c9e, 0x68ad8cef, 0xd09bd2d6, 0x908c5c15, 0xd1e36260, 0x2c5bfdd0, 0x88765a99, 0x93deba1e,
0xac6ae342, 0xe865b84c, 0x0f4f2847, 0x7fdf0499, 0x78b1c9b3, 0x6a73261e, 0x601a96f6, 0xd2847933,
0x489aa888, 0xe12e8093, 0x3bfa5a5f, 0xd96ba5f7, 0x7c8f4c8d, 0x80940c6f, 0xcef9dd1a, 0x7e1a055f,
0x3483558b, 0x02b59cc4, 0x0c56333e, 0x05a5b813, 0x92d66287, 0x7516b679, 0x71bfe03f, 0x8056bf68,
0xc24d0724, 0x8416bcf3, 0x234afbdb, 0x4b0d6f9c, 0xaba97333, 0x4b4f42b6, 0x7e8343ab, 0x7ffe2603,
0xe590f73c, 0x45e10c76, 0xb07a6a78, 0xb35609d3, 0x1a027dfd, 0x90cb6e20, 0x82d3fe38, 0x7b409257,
0x0e395afa, 0x1b802093, 0xcb0c6c59, 0x241e17e7, 0x1ee3ea0a, 0x41a82302, 0xab04350a, 0xf570beb7,
0xbb444b9b, 0x83021459, 0x838d65dc, 0x1c439c84, 0x6fdcc454, 0xef9ef325, 0x18626c1c, 0x020d251f,
0xc4aae786, 0x8614cb48, 0xf6f53ca6, 0x8710dbab, 0x89abec0d, 0xf29d41c1, 0x94b50336, 0xfdd49178,
0x604658d1, 0x800e85be, 0xca1bb079, 0x7fa48eeb, 0xa3b7fafe, 0xd330436b, 0x64eb604c, 0x43a658ae,
0x7caa1337, 0xddd445e6, 0x7efbf955, 0xb706ec71, 0x624a6b53, 0x9e0e231f, 0x97097248, 0xa1e1a17a,
0x68dd2e44, 0x7f9d2e14, 0xddcc7074, 0x58324197, 0xc88fc426, 0x6d3640ae, 0x7ef83600, 0x759a0270,
0x98b6d854, 0xd63c9b84, 0x372474a2, 0xe3f18cfd, 0x56ab0bdb, 0x85c9be7e, 0x47dfcfeb, 0xa5830d41,
0x0ddd6283, 0xf4f480ad, 0x74c60e38, 0xab8943c3, 0xc1508fe7, 0x480cdc39, 0x8e097362, 0xa44793be,
0x538b7e18, 0x545f5b41, 0x56529175, 0x9771a97e, 0xc2da7421, 0xea8265f2, 0x805d1163, 0x883c5d28,
0x8ba94c48, 0x4f676e65, 0xf78735b3, 0xe1853671, 0x7f454f53, 0x18147f85, 0x7d09e15d, 0xdb4f3494,
0x795c8973, 0x83310632, 0x85d8061c, 0x9a1a0ebf, 0xc125583c, 0x2a1b1a95, 0x7fd9103f, 0x71e98c72,
0x40932ed7, 0x91ed227a, 0x3c5e560e, 0xe816dee9, 0xb0891b80, 0x600038ba, 0xc7d9a80d, 0x7fff5e09,
0x7e3f4351, 0xbb6b4424, 0xb14448d4, 0x8d6bb7e1, 0xfb153626, 0xa68ad537, 0xd9782006, 0xf62f6991,
0x359ba8c1, 0x02ccff0b, 0x91bf2256, 0x7ea71c4d, 0x560ce5df, 0xeeba289b, 0xa574c4e7, 0x9e04f6ee,
0x7860a5ec, 0x0b8db4a2, 0x968ba3d7, 0x0b6c77df, 0xd6f3157d, 0x402eff1a, 0x49b820b3, 0x8152aebb,
0xd180b0b6, 0x098604d4, 0x7ff92224, 0xede9c996, 0x89c58061, 0x829624c4, 0xc6e71ea7, 0xba94d915,
0x389c3cf6, 0x5b4c5a06, 0x04b335e6, 0x516a8aab, 0x42c8d7d9, 0x92b12af6, 0x86c8549f, 0xfda98acf,
0x819673b6, 0x69545dac, 0x6feaa230, 0x726e6d3f, 0x886ebdfe, 0x34f5730a, 0x7af63ba2, 0x77307bbf,
0x7cd80630, 0x6e45efe0, 0x7f8ad7eb, 0x59d7df99, 0x86c70946, 0xda233629, 0x753f6cbf, 0x825eeb40,
};
|
1137519-player
|
aac/sbrtabs.c
|
C
|
lgpl
| 33,542
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbrmath.c,v 1.1 2005/02/26 01:47:35 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbrmath.c - fixed-point math functions for SBR
**************************************************************************************/
#include "sbr.h"
#include "assembly.h"
#define Q28_2 0x20000000 /* Q28: 2.0 */
#define Q28_15 0x30000000 /* Q28: 1.5 */
#define NUM_ITER_IRN 5
/**************************************************************************************
* Function: InvRNormalized
*
* Description: use Newton's method to solve for x = 1/r
*
* Inputs: r = Q31, range = [0.5, 1) (normalize your inputs to this range)
*
* Outputs: none
*
* Return: x = Q29, range ~= [1.0, 2.0]
*
* Notes: guaranteed to converge and not overflow for any r in [0.5, 1)
*
* xn+1 = xn - f(xn)/f'(xn)
* f(x) = 1/r - x = 0 (find root)
* = 1/x - r
* f'(x) = -1/x^2
*
* so xn+1 = xn - (1/xn - r) / (-1/xn^2)
* = xn * (2 - r*xn)
*
* NUM_ITER_IRN = 2, maxDiff = 6.2500e-02 (precision of about 4 bits)
* NUM_ITER_IRN = 3, maxDiff = 3.9063e-03 (precision of about 8 bits)
* NUM_ITER_IRN = 4, maxDiff = 1.5288e-05 (precision of about 16 bits)
* NUM_ITER_IRN = 5, maxDiff = 3.0034e-08 (precision of about 24 bits)
**************************************************************************************/
int InvRNormalized(int r)
{
int i, xn, t;
/* r = [0.5, 1.0)
* 1/r = (1.0, 2.0]
* so use 1.5 as initial guess
*/
xn = Q28_15;
/* xn = xn*(2.0 - r*xn) */
for (i = NUM_ITER_IRN; i != 0; i--) {
t = MULSHIFT32(r, xn); /* Q31*Q29 = Q28 */
t = Q28_2 - t; /* Q28 */
xn = MULSHIFT32(xn, t) << 4; /* Q29*Q28 << 4 = Q29 */
}
return xn;
}
#define NUM_TERMS_RPI 5
#define LOG2_EXP_INV 0x58b90bfc /* 1/log2(e), Q31 */
/* invTab[x] = 1/(x+1), format = Q30 */
static const int invTab[NUM_TERMS_RPI] = {0x40000000, 0x20000000, 0x15555555, 0x10000000, 0x0ccccccd};
/**************************************************************************************
* Function: RatioPowInv
*
* Description: use Taylor (MacLaurin) series expansion to calculate (a/b) ^ (1/c)
*
* Inputs: a = [1, 64], b = [1, 64], c = [1, 64], a >= b
*
* Outputs: none
*
* Return: y = Q24, range ~= [0.015625, 64]
**************************************************************************************/
int RatioPowInv(int a, int b, int c)
{
int lna, lnb, i, p, t, y;
if (a < 1 || b < 1 || c < 1 || a > 64 || b > 64 || c > 64 || a < b)
return 0;
lna = MULSHIFT32(log2Tab[a], LOG2_EXP_INV) << 1; /* ln(a), Q28 */
lnb = MULSHIFT32(log2Tab[b], LOG2_EXP_INV) << 1; /* ln(b), Q28 */
p = (lna - lnb) / c; /* Q28 */
/* sum in Q24 */
y = (1 << 24);
t = p >> 4; /* t = p^1 * 1/1! (Q24)*/
y += t;
for (i = 2; i <= NUM_TERMS_RPI; i++) {
t = MULSHIFT32(invTab[i-1], t) << 2;
t = MULSHIFT32(p, t) << 4; /* t = p^i * 1/i! (Q24) */
y += t;
}
return y;
}
/**************************************************************************************
* Function: SqrtFix
*
* Description: use binary search to calculate sqrt(q)
*
* Inputs: q = Q30
* number of fraction bits in input
*
* Outputs: number of fraction bits in output
*
* Return: lo = Q(fBitsOut)
*
* Notes: absolute precision varies depending on fBitsIn
* normalizes input to range [0x200000000, 0x7fffffff] and takes
* floor(sqrt(input)), and sets fBitsOut appropriately
**************************************************************************************/
int SqrtFix(int q, int fBitsIn, int *fBitsOut)
{
int z, lo, hi, mid;
if (q <= 0) {
*fBitsOut = fBitsIn;
return 0;
}
/* force even fBitsIn */
z = fBitsIn & 0x01;
q >>= z;
fBitsIn -= z;
/* for max precision, normalize to [0x20000000, 0x7fffffff] */
z = (CLZ(q) - 1);
z >>= 1;
q <<= (2*z);
/* choose initial bounds */
lo = 1;
if (q >= 0x10000000)
lo = 16384; /* (int)sqrt(0x10000000) */
hi = 46340; /* (int)sqrt(0x7fffffff) */
/* do binary search with 32x32->32 multiply test */
do {
mid = (lo + hi) >> 1;
if (mid*mid > q)
hi = mid - 1;
else
lo = mid + 1;
} while (hi >= lo);
lo--;
*fBitsOut = ((fBitsIn + 2*z) >> 1);
return lo;
}
|
1137519-player
|
aac/sbrmath.c
|
C
|
lgpl
| 6,206
|
@ ***** BEGIN LICENSE BLOCK *****
@ Source last modified: $Id: sbrqmfsk.s,v 1.1 2005/04/08 21:59:46 jrecker Exp $
@
@ Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
@
@ The contents of this file, and the files included with this file,
@ are subject to the current version of the RealNetworks Public
@ Source License (the "RPSL") available at
@ http://www.helixcommunity.org/content/rpsl unless you have licensed
@ the file under the current version of the RealNetworks Community
@ Source License (the "RCSL") available at
@ http://www.helixcommunity.org/content/rcsl, in which case the RCSL
@ will apply. You may also obtain the license terms directly from
@ RealNetworks. You may not use this file except in compliance with
@ the RPSL or, if you have a valid RCSL with RealNetworks applicable
@ to this file, the RCSL. Please see the applicable RPSL or RCSL for
@ the rights, obligations and limitations governing use of the
@ contents of the file.
@
@ This file is part of the Helix DNA Technology. RealNetworks is the
@ developer and/or licensor of the Original Code and owns the
@ copyrights in the portions it created.
@
@ This file, and the files included with this file, is distributed
@ and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
@ KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
@ ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
@ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
@ ENJOYMENT OR NON-INFRINGEMENT.
@
@ Technology Compatibility Kit Test Suite(s) Location:
@ http://www.helixcommunity.org/content/tck
@
@ Contributor(s):
@
@ ***** END LICENSE BLOCK *****
.text
.code 32
.align
@ void QMFSynthesisConv(int *cPtr, int *delay, int dIdx, short *outbuf, int nChans);
@ see comments in sbrqmf.c
.global raac_QMFSynthesisConv
raac_QMFSynthesisConv:
stmfd sp!, {r4-r11, r14}
ldr r9, [r13, #4*9] @ we saved 9 registers on stack
mov r5, r2, lsl #7 @ dOff0 = 128*dIdx
subs r6, r5, #1 @ dOff1 = dOff0 - 1
addlt r6, r6, #1280 @ if (dOff1 < 0) then dOff1 += 1280
mov r4, #64
SRC_Loop_Start:
ldr r10, [r0], #4
ldr r12, [r0], #4
ldr r11, [r1, r5, lsl #2]
ldr r14, [r1, r6, lsl #2]
smull r7, r8, r10, r11
subs r5, r5, #256
addlt r5, r5, #1280
smlal r7, r8, r12, r14
subs r6, r6, #256
addlt r6, r6, #1280
ldr r10, [r0], #4
ldr r12, [r0], #4
ldr r11, [r1, r5, lsl #2]
ldr r14, [r1, r6, lsl #2]
smlal r7, r8, r10, r11
subs r5, r5, #256
addlt r5, r5, #1280
smlal r7, r8, r12, r14
subs r6, r6, #256
addlt r6, r6, #1280
ldr r10, [r0], #4
ldr r12, [r0], #4
ldr r11, [r1, r5, lsl #2]
ldr r14, [r1, r6, lsl #2]
smlal r7, r8, r10, r11
subs r5, r5, #256
addlt r5, r5, #1280
smlal r7, r8, r12, r14
subs r6, r6, #256
addlt r6, r6, #1280
ldr r10, [r0], #4
ldr r12, [r0], #4
ldr r11, [r1, r5, lsl #2]
ldr r14, [r1, r6, lsl #2]
smlal r7, r8, r10, r11
subs r5, r5, #256
addlt r5, r5, #1280
smlal r7, r8, r12, r14
subs r6, r6, #256
addlt r6, r6, #1280
ldr r10, [r0], #4
ldr r12, [r0], #4
ldr r11, [r1, r5, lsl #2]
ldr r14, [r1, r6, lsl #2]
smlal r7, r8, r10, r11
subs r5, r5, #256
addlt r5, r5, #1280
smlal r7, r8, r12, r14
subs r6, r6, #256
addlt r6, r6, #1280
add r5, r5, #1
sub r6, r6, #1
add r8, r8, #0x04
mov r8, r8, asr #3 @ FBITS_OUT_QMFS
mov r7, r8, asr #31
cmp r7, r8, asr #15
eorne r8, r7, #0x7f00 @ takes 2 instructions for immediate value of 0x7fffffff
eorne r8, r8, #0x00ff
strh r8, [r3, #0]
add r3, r3, r9, lsl #1
subs r4, r4, #1
bne SRC_Loop_Start
ldmfd sp!, {r4-r11, pc}
.end
|
1137519-player
|
aac/armgcc_nosyms/sbrqmfsk.s
|
Unix Assembly
|
lgpl
| 4,390
|
@ ***** BEGIN LICENSE BLOCK *****
@ Source last modified: $Id: sbrcov.s,v 1.1 2005/04/08 21:59:46 jrecker Exp $
@
@ Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
@
@ The contents of this file, and the files included with this file,
@ are subject to the current version of the RealNetworks Public
@ Source License (the "RPSL") available at
@ http://www.helixcommunity.org/content/rpsl unless you have licensed
@ the file under the current version of the RealNetworks Community
@ Source License (the "RCSL") available at
@ http://www.helixcommunity.org/content/rcsl, in which case the RCSL
@ will apply. You may also obtain the license terms directly from
@ RealNetworks. You may not use this file except in compliance with
@ the RPSL or, if you have a valid RCSL with RealNetworks applicable
@ to this file, the RCSL. Please see the applicable RPSL or RCSL for
@ the rights, obligations and limitations governing use of the
@ contents of the file.
@
@ This file is part of the Helix DNA Technology. RealNetworks is the
@ developer and/or licensor of the Original Code and owns the
@ copyrights in the portions it created.
@
@ This file, and the files included with this file, is distributed
@ and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
@ KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
@ ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
@ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
@ ENJOYMENT OR NON-INFRINGEMENT.
@
@ Technology Compatibility Kit Test Suite(s) Location:
@ http://www.helixcommunity.org/content/tck
@
@ Contributor(s):
@
@ ***** END LICENSE BLOCK *****
.text
.code 32
.align
@ void CVKernel1(int *XBuf, int *accBuf)
@ see comments in sbrhfgen.c
.global raac_CVKernel1
raac_CVKernel1:
stmfd sp!, {r4-r11, r14}
ldr r3, [r0], #4*(1)
ldr r4, [r0], #4*(2*64-1)
ldr r5, [r0], #4*(1)
ldr r6, [r0], #4*(2*64-1)
rsb r14, r4, #0
smull r7, r8, r5, r3
smlal r7, r8, r6, r4
smull r9, r10, r3, r6
smlal r9, r10, r14, r5
smull r11, r12, r3, r3
smlal r11, r12, r4, r4
add r2, r1, #(4*6)
stmia r2, {r7-r12}
mov r7, #0
mov r8, #0
mov r9, #0
mov r10, #0
mov r11, #0
mov r12, #0
mov r2, #(16*2 + 6)
CV1_Loop_Start:
mov r3, r5
ldr r5, [r0], #4*(1)
mov r4, r6
ldr r6, [r0], #4*(2*64-1)
rsb r14, r4, #0
smlal r7, r8, r5, r3
smlal r7, r8, r6, r4
smlal r9, r10, r3, r6
smlal r9, r10, r14, r5
smlal r11, r12, r3, r3
smlal r11, r12, r4, r4
subs r2, r2, #1
bne CV1_Loop_Start
stmia r1, {r7-r12}
ldr r0, [r1, #4*(6)]
ldr r2, [r1, #4*(7)]
rsb r3, r3, #0
adds r7, r0, r7
adc r8, r2, r8
smlal r7, r8, r5, r3
smlal r7, r8, r6, r14
ldr r0, [r1, #4*(8)]
ldr r2, [r1, #4*(9)]
adds r9, r0, r9
adc r10, r2, r10
smlal r9, r10, r3, r6
smlal r9, r10, r4, r5
ldr r0, [r1, #4*(10)]
ldr r2, [r1, #4*(11)]
adds r11, r0, r11
adc r12, r2, r12
rsb r0, r3, #0
smlal r11, r12, r3, r0
rsb r2, r4, #0
smlal r11, r12, r4, r2
add r1, r1, #(4*6)
stmia r1, {r7-r12}
ldmfd sp!, {r4-r11, pc}
@ void CVKernel2(int *XBuf, int *accBuf)
@ see comments in sbrhfgen.c
.global raac_CVKernel2
raac_CVKernel2:
stmfd sp!, {r4-r11, r14}
mov r7, #0
mov r8, #0
mov r9, #0
mov r10, #0
ldr r3, [r0], #4*(1)
ldr r4, [r0], #4*(2*64-1)
ldr r5, [r0], #4*(1)
ldr r6, [r0], #4*(2*64-1)
mov r2, #(16*2 + 6)
CV2_Loop_Start:
ldr r11, [r0], #4*(1)
ldr r12, [r0], #4*(2*64-1)
rsb r14, r4, #0
smlal r7, r8, r11, r3
smlal r7, r8, r12, r4
smlal r9, r10, r3, r12
smlal r9, r10, r14, r11
mov r3, r5
mov r4, r6
mov r5, r11
mov r6, r12
subs r2, r2, #1
bne CV2_Loop_Start
stmia r1, {r7-r10}
ldmfd sp!, {r4-r11, pc}
.end
|
1137519-player
|
aac/armgcc_nosyms/sbrcov.s
|
Unix Assembly
|
lgpl
| 4,678
|
@ ***** BEGIN LICENSE BLOCK *****
@ Source last modified: $Id: sbrqmfak.s,v 1.1 2005/04/08 21:59:46 jrecker Exp $
@
@ Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
@
@ The contents of this file, and the files included with this file,
@ are subject to the current version of the RealNetworks Public
@ Source License (the "RPSL") available at
@ http://www.helixcommunity.org/content/rpsl unless you have licensed
@ the file under the current version of the RealNetworks Community
@ Source License (the "RCSL") available at
@ http://www.helixcommunity.org/content/rcsl, in which case the RCSL
@ will apply. You may also obtain the license terms directly from
@ RealNetworks. You may not use this file except in compliance with
@ the RPSL or, if you have a valid RCSL with RealNetworks applicable
@ to this file, the RCSL. Please see the applicable RPSL or RCSL for
@ the rights, obligations and limitations governing use of the
@ contents of the file.
@
@ This file is part of the Helix DNA Technology. RealNetworks is the
@ developer and/or licensor of the Original Code and owns the
@ copyrights in the portions it created.
@
@ This file, and the files included with this file, is distributed
@ and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
@ KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
@ ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
@ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
@ ENJOYMENT OR NON-INFRINGEMENT.
@
@ Technology Compatibility Kit Test Suite(s) Location:
@ http://www.helixcommunity.org/content/tck
@
@ Contributor(s):
@
@ ***** END LICENSE BLOCK *****
.text
.code 32
.align
@void QMFAnalysisConv(int *cTab, int *delay, int dIdx, int *uBuf)
@ see comments in sbrqmf.c
.global raac_QMFAnalysisConv
raac_QMFAnalysisConv:
stmfd sp!, {r4-r11, r14}
mov r6, r2, lsl #5 @ dOff0 = 32*dIdx
add r6, r6, #31 @ dOff0 = 32*dIdx + 31
add r4, r0, #4*(164) @ cPtr1 = cPtr0 + 164
@ special first pass (flip sign for cTab[384], cTab[512])
ldr r11, [r0], #4
ldr r14, [r0], #4
ldr r12, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
ldr r2, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
smull r7, r8, r11, r12
smull r9, r10, r14, r2
ldr r11, [r0], #4
ldr r14, [r0], #4
ldr r12, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
ldr r2, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
smlal r7, r8, r11, r12
smlal r9, r10, r14, r2
ldr r11, [r0], #4
ldr r14, [r4], #-4
ldr r12, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
ldr r2, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
smlal r7, r8, r11, r12
smlal r9, r10, r14, r2
ldr r11, [r4], #-4
ldr r14, [r4], #-4
ldr r12, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
ldr r2, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
rsb r11, r11, #0
smlal r7, r8, r11, r12
smlal r9, r10, r14, r2
ldr r11, [r4], #-4
ldr r14, [r4], #-4
ldr r12, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
ldr r2, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
rsb r11, r11, #0
smlal r7, r8, r11, r12
smlal r9, r10, r14, r2
str r10, [r3, #4*32]
str r8, [r3], #4
sub r6, r6, #1
mov r5, #31
SRC_Loop_Start:
ldr r11, [r0], #4
ldr r14, [r0], #4
ldr r12, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
ldr r2, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
smull r7, r8, r11, r12
smull r9, r10, r14, r2
ldr r11, [r0], #4
ldr r14, [r0], #4
ldr r12, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
ldr r2, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
smlal r7, r8, r11, r12
smlal r9, r10, r14, r2
ldr r11, [r0], #4
ldr r14, [r4], #-4
ldr r12, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
ldr r2, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
smlal r7, r8, r11, r12
smlal r9, r10, r14, r2
ldr r11, [r4], #-4
ldr r14, [r4], #-4
ldr r12, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
ldr r2, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
smlal r7, r8, r11, r12
smlal r9, r10, r14, r2
ldr r11, [r4], #-4
ldr r14, [r4], #-4
ldr r12, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
ldr r2, [r1, r6, lsl #2]
subs r6, r6, #32
addlt r6, r6, #320
smlal r7, r8, r11, r12
smlal r9, r10, r14, r2
str r10, [r3, #4*32]
str r8, [r3], #4
sub r6, r6, #1
subs r5, r5, #1
bne SRC_Loop_Start
ldmfd sp!, {r4-r11, pc}
.end
|
1137519-player
|
aac/armgcc_nosyms/sbrqmfak.s
|
Unix Assembly
|
lgpl
| 5,774
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: filefmt.c,v 1.1 2005/02/26 01:47:34 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* filefmt.c - ADIF and ADTS header decoding, raw block handling
**************************************************************************************/
#include "coder.h"
/**************************************************************************************
* Function: UnpackADTSHeader
*
* Description: parse the ADTS frame header and initialize decoder state
*
* Inputs: valid AACDecInfo struct
* double pointer to buffer with complete ADTS frame header (byte aligned)
* header size = 7 bytes, plus 2 if CRC
*
* Outputs: filled in ADTS struct
* updated buffer pointer
* updated bit offset
* updated number of available bits
*
* Return: 0 if successful, error code (< 0) if error
*
* TODO: test CRC
* verify that fixed fields don't change between frames
**************************************************************************************/
int UnpackADTSHeader(AACDecInfo *aacDecInfo, unsigned char **buf, int *bitOffset, int *bitsAvail)
{
int bitsUsed;
PSInfoBase *psi;
BitStreamInfo bsi;
ADTSHeader *fhADTS;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
fhADTS = &(psi->fhADTS);
/* init bitstream reader */
SetBitstreamPointer(&bsi, (*bitsAvail + 7) >> 3, *buf);
GetBits(&bsi, *bitOffset);
/* verify that first 12 bits of header are syncword */
if (GetBits(&bsi, 12) != 0x0fff)
return ERR_AAC_INVALID_ADTS_HEADER;
/* fixed fields - should not change from frame to frame */
fhADTS->id = GetBits(&bsi, 1);
fhADTS->layer = GetBits(&bsi, 2);
fhADTS->protectBit = GetBits(&bsi, 1);
fhADTS->profile = GetBits(&bsi, 2);
fhADTS->sampRateIdx = GetBits(&bsi, 4);
fhADTS->privateBit = GetBits(&bsi, 1);
fhADTS->channelConfig = GetBits(&bsi, 3);
fhADTS->origCopy = GetBits(&bsi, 1);
fhADTS->home = GetBits(&bsi, 1);
/* variable fields - can change from frame to frame */
fhADTS->copyBit = GetBits(&bsi, 1);
fhADTS->copyStart = GetBits(&bsi, 1);
fhADTS->frameLength = GetBits(&bsi, 13);
fhADTS->bufferFull = GetBits(&bsi, 11);
fhADTS->numRawDataBlocks = GetBits(&bsi, 2) + 1;
/* note - MPEG4 spec, correction 1 changes how CRC is handled when protectBit == 0 and numRawDataBlocks > 1 */
if (fhADTS->protectBit == 0)
fhADTS->crcCheckWord = GetBits(&bsi, 16);
/* byte align */
ByteAlignBitstream(&bsi); /* should always be aligned anyway */
/* check validity of header */
if (fhADTS->layer != 0 || fhADTS->profile != AAC_PROFILE_LC ||
fhADTS->sampRateIdx >= NUM_SAMPLE_RATES || fhADTS->channelConfig >= NUM_DEF_CHAN_MAPS)
return ERR_AAC_INVALID_ADTS_HEADER;
#ifndef AAC_ENABLE_MPEG4
if (fhADTS->id != 1)
return ERR_AAC_MPEG4_UNSUPPORTED;
#endif
/* update codec info */
psi->sampRateIdx = fhADTS->sampRateIdx;
if (!psi->useImpChanMap)
psi->nChans = channelMapTab[fhADTS->channelConfig];
/* syntactic element fields will be read from bitstream for each element */
aacDecInfo->prevBlockID = AAC_ID_INVALID;
aacDecInfo->currBlockID = AAC_ID_INVALID;
aacDecInfo->currInstTag = -1;
/* fill in user-accessible data (TODO - calc bitrate, handle tricky channel config cases) */
aacDecInfo->bitRate = 0;
aacDecInfo->nChans = psi->nChans;
aacDecInfo->sampRate = sampRateTab[psi->sampRateIdx];
aacDecInfo->profile = fhADTS->profile;
aacDecInfo->sbrEnabled = 0;
aacDecInfo->adtsBlocksLeft = fhADTS->numRawDataBlocks;
/* update bitstream reader */
bitsUsed = CalcBitsUsed(&bsi, *buf, *bitOffset);
*buf += (bitsUsed + *bitOffset) >> 3;
*bitOffset = (bitsUsed + *bitOffset) & 0x07;
*bitsAvail -= bitsUsed ;
if (*bitsAvail < 0)
return ERR_AAC_INDATA_UNDERFLOW;
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: GetADTSChannelMapping
*
* Description: determine the number of channels from implicit mapping rules
*
* Inputs: valid AACDecInfo struct
* pointer to start of raw_data_block
* bit offset
* bits available
*
* Outputs: updated number of channels
*
* Return: 0 if successful, error code (< 0) if error
*
* Notes: calculates total number of channels using rules in 14496-3, 4.5.1.2.1
* does not attempt to deduce speaker geometry
**************************************************************************************/
int GetADTSChannelMapping(AACDecInfo *aacDecInfo, unsigned char *buf, int bitOffset, int bitsAvail)
{
int ch, nChans, elementChans, err;
PSInfoBase *psi;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
nChans = 0;
do {
/* parse next syntactic element */
err = DecodeNextElement(aacDecInfo, &buf, &bitOffset, &bitsAvail);
if (err)
return err;
elementChans = elementNumChans[aacDecInfo->currBlockID];
nChans += elementChans;
for (ch = 0; ch < elementChans; ch++) {
err = DecodeNoiselessData(aacDecInfo, &buf, &bitOffset, &bitsAvail, ch);
if (err)
return err;
}
} while (aacDecInfo->currBlockID != AAC_ID_END);
if (nChans <= 0)
return ERR_AAC_CHANNEL_MAP;
/* update number of channels in codec state and user-accessible info structs */
psi->nChans = nChans;
aacDecInfo->nChans = psi->nChans;
psi->useImpChanMap = 1;
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: GetNumChannelsADIF
*
* Description: get number of channels from program config elements in an ADIF file
*
* Inputs: array of filled-in program config element structures
* number of PCE's
*
* Outputs: none
*
* Return: total number of channels in file
* -1 if error (invalid number of PCE's or unsupported mode)
**************************************************************************************/
static int GetNumChannelsADIF(ProgConfigElement *fhPCE, int nPCE)
{
int i, j, nChans;
if (nPCE < 1 || nPCE > MAX_NUM_PCE_ADIF)
return -1;
nChans = 0;
for (i = 0; i < nPCE; i++) {
/* for now: only support LC, no channel coupling */
if (fhPCE[i].profile != AAC_PROFILE_LC || fhPCE[i].numCCE > 0)
return -1;
/* add up number of channels in all channel elements (assume all single-channel) */
nChans += fhPCE[i].numFCE;
nChans += fhPCE[i].numSCE;
nChans += fhPCE[i].numBCE;
nChans += fhPCE[i].numLCE;
/* add one more for every element which is a channel pair */
for (j = 0; j < fhPCE[i].numFCE; j++) {
if (CHAN_ELEM_IS_CPE(fhPCE[i].fce[j]))
nChans++;
}
for (j = 0; j < fhPCE[i].numSCE; j++) {
if (CHAN_ELEM_IS_CPE(fhPCE[i].sce[j]))
nChans++;
}
for (j = 0; j < fhPCE[i].numBCE; j++) {
if (CHAN_ELEM_IS_CPE(fhPCE[i].bce[j]))
nChans++;
}
}
return nChans;
}
/**************************************************************************************
* Function: GetSampleRateIdxADIF
*
* Description: get sampling rate index from program config elements in an ADIF file
*
* Inputs: array of filled-in program config element structures
* number of PCE's
*
* Outputs: none
*
* Return: sample rate of file
* -1 if error (invalid number of PCE's or sample rate mismatch)
**************************************************************************************/
static int GetSampleRateIdxADIF(ProgConfigElement *fhPCE, int nPCE)
{
int i, idx;
if (nPCE < 1 || nPCE > MAX_NUM_PCE_ADIF)
return -1;
/* make sure all PCE's have the same sample rate */
idx = fhPCE[0].sampRateIdx;
for (i = 1; i < nPCE; i++) {
if (fhPCE[i].sampRateIdx != idx)
return -1;
}
return idx;
}
/**************************************************************************************
* Function: UnpackADIFHeader
*
* Description: parse the ADIF file header and initialize decoder state
*
* Inputs: valid AACDecInfo struct
* double pointer to buffer with complete ADIF header
* (starting at 'A' in 'ADIF' tag)
* pointer to bit offset
* pointer to number of valid bits remaining in inbuf
*
* Outputs: filled-in ADIF struct
* updated buffer pointer
* updated bit offset
* updated number of available bits
*
* Return: 0 if successful, error code (< 0) if error
**************************************************************************************/
int UnpackADIFHeader(AACDecInfo *aacDecInfo, unsigned char **buf, int *bitOffset, int *bitsAvail)
{
int i, bitsUsed;
PSInfoBase *psi;
BitStreamInfo bsi;
ADIFHeader *fhADIF;
ProgConfigElement *pce;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
/* init bitstream reader */
SetBitstreamPointer(&bsi, (*bitsAvail + 7) >> 3, *buf);
GetBits(&bsi, *bitOffset);
/* unpack ADIF file header */
fhADIF = &(psi->fhADIF);
pce = psi->pce;
/* verify that first 32 bits of header are "ADIF" */
if (GetBits(&bsi, 8) != 'A' || GetBits(&bsi, 8) != 'D' || GetBits(&bsi, 8) != 'I' || GetBits(&bsi, 8) != 'F')
return ERR_AAC_INVALID_ADIF_HEADER;
/* read ADIF header fields */
fhADIF->copyBit = GetBits(&bsi, 1);
if (fhADIF->copyBit) {
for (i = 0; i < ADIF_COPYID_SIZE; i++)
fhADIF->copyID[i] = GetBits(&bsi, 8);
}
fhADIF->origCopy = GetBits(&bsi, 1);
fhADIF->home = GetBits(&bsi, 1);
fhADIF->bsType = GetBits(&bsi, 1);
fhADIF->bitRate = GetBits(&bsi, 23);
fhADIF->numPCE = GetBits(&bsi, 4) + 1; /* add 1 (so range = [1, 16]) */
if (fhADIF->bsType == 0)
fhADIF->bufferFull = GetBits(&bsi, 20);
/* parse all program config elements */
for (i = 0; i < fhADIF->numPCE; i++)
DecodeProgramConfigElement(pce + i, &bsi);
/* byte align */
ByteAlignBitstream(&bsi);
/* update codec info */
psi->nChans = GetNumChannelsADIF(pce, fhADIF->numPCE);
psi->sampRateIdx = GetSampleRateIdxADIF(pce, fhADIF->numPCE);
/* check validity of header */
if (psi->nChans < 0 || psi->sampRateIdx < 0 || psi->sampRateIdx >= NUM_SAMPLE_RATES)
return ERR_AAC_INVALID_ADIF_HEADER;
/* syntactic element fields will be read from bitstream for each element */
aacDecInfo->prevBlockID = AAC_ID_INVALID;
aacDecInfo->currBlockID = AAC_ID_INVALID;
aacDecInfo->currInstTag = -1;
/* fill in user-accessible data */
aacDecInfo->bitRate = 0;
aacDecInfo->nChans = psi->nChans;
aacDecInfo->sampRate = sampRateTab[psi->sampRateIdx];
aacDecInfo->profile = pce[0].profile;
aacDecInfo->sbrEnabled = 0;
/* update bitstream reader */
bitsUsed = CalcBitsUsed(&bsi, *buf, *bitOffset);
*buf += (bitsUsed + *bitOffset) >> 3;
*bitOffset = (bitsUsed + *bitOffset) & 0x07;
*bitsAvail -= bitsUsed ;
if (*bitsAvail < 0)
return ERR_AAC_INDATA_UNDERFLOW;
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: SetRawBlockParams
*
* Description: set internal state variables for decoding a stream of raw data blocks
*
* Inputs: valid AACDecInfo struct
* flag indicating source of parameters (from previous headers or passed
* explicitly by caller)
* number of channels
* sample rate
* profile ID
*
* Outputs: updated state variables in aacDecInfo
*
* Return: 0 if successful, error code (< 0) if error
*
* Notes: if copyLast == 1, then psi->nChans, psi->sampRateIdx, and
* aacDecInfo->profile are not changed (it's assumed that we already
* set them, such as by a previous call to UnpackADTSHeader())
* if copyLast == 0, then the parameters we passed in are used instead
**************************************************************************************/
int SetRawBlockParams(AACDecInfo *aacDecInfo, int copyLast, int nChans, int sampRate, int profile)
{
int idx;
PSInfoBase *psi;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
if (!copyLast) {
aacDecInfo->profile = profile;
psi->nChans = nChans;
for (idx = 0; idx < NUM_SAMPLE_RATES; idx++) {
if (sampRate == sampRateTab[idx]) {
psi->sampRateIdx = idx;
break;
}
}
if (idx == NUM_SAMPLE_RATES)
return ERR_AAC_INVALID_FRAME;
}
aacDecInfo->nChans = psi->nChans;
aacDecInfo->sampRate = sampRateTab[psi->sampRateIdx];
/* check validity of header */
if (psi->sampRateIdx >= NUM_SAMPLE_RATES || psi->sampRateIdx < 0 || aacDecInfo->profile != AAC_PROFILE_LC)
return ERR_AAC_RAWBLOCK_PARAMS;
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: PrepareRawBlock
*
* Description: reset per-block state variables for raw blocks (no ADTS/ADIF headers)
*
* Inputs: valid AACDecInfo struct
*
* Outputs: updated state variables in aacDecInfo
*
* Return: 0 if successful, error code (< 0) if error
**************************************************************************************/
int PrepareRawBlock(AACDecInfo *aacDecInfo)
{
PSInfoBase *psi;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
/* syntactic element fields will be read from bitstream for each element */
aacDecInfo->prevBlockID = AAC_ID_INVALID;
aacDecInfo->currBlockID = AAC_ID_INVALID;
aacDecInfo->currInstTag = -1;
/* fill in user-accessible data */
aacDecInfo->bitRate = 0;
aacDecInfo->sbrEnabled = 0;
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: FlushCodec
*
* Description: flush internal codec state (after seeking, for example)
*
* Inputs: valid AACDecInfo struct
*
* Outputs: updated state variables in aacDecInfo
*
* Return: 0 if successful, error code (< 0) if error
*
* Notes: only need to clear data which is persistent between frames
* (such as overlap buffer)
**************************************************************************************/
int FlushCodec(AACDecInfo *aacDecInfo)
{
PSInfoBase *psi;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
ClearBuffer(psi->overlap, AAC_MAX_NCHANS * AAC_MAX_NSAMPS * sizeof(int));
ClearBuffer(psi->prevWinShape, AAC_MAX_NCHANS * sizeof(int));
return ERR_AAC_NONE;
}
|
1137519-player
|
aac/filefmt.c
|
C
|
lgpl
| 16,895
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: buffers.c,v 1.2 2008/01/15 21:20:31 ehyche Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* buffers.c - allocation and deallocation of internal AAC decoder buffers
**************************************************************************************/
#ifdef USE_DEFAULT_STDLIB
#include <stdlib.h>
#else
#include "hlxclib/stdlib.h"
#endif
#if defined(REAL_FORMAT_SDK)
#include "rm_memory_shim.h"
#define malloc hx_realformatsdk_malloc
#define free hx_realformatsdk_free
#endif /* #if defined(REAL_FORMAT_SDK) */
#include "coder.h"
/**************************************************************************************
* Function: ClearBuffer
*
* Description: fill buffer with 0's
*
* Inputs: pointer to buffer
* number of bytes to fill with 0
*
* Outputs: cleared buffer
*
* Return: none
*
* Notes: slow, platform-independent equivalent to memset(buf, 0, nBytes)
**************************************************************************************/
void ClearBuffer(void *buf, int nBytes)
{
int i;
unsigned char *cbuf = (unsigned char *)buf;
for (i = 0; i < nBytes; i++)
cbuf[i] = 0;
return;
}
/**************************************************************************************
* Function: AllocateBuffers
*
* Description: allocate all the memory needed for the AAC decoder
*
* Inputs: none
*
* Outputs: none
*
* Return: pointer to AACDecInfo structure, cleared to all 0's (except for
* pointer to platform-specific data structure)
*
* Notes: if one or more mallocs fail, function frees any buffers already
* allocated before returning
**************************************************************************************/
AACDecInfo *AllocateBuffers(void)
{
AACDecInfo *aacDecInfo;
aacDecInfo = (AACDecInfo *)malloc(sizeof(AACDecInfo));
if (!aacDecInfo)
return 0;
ClearBuffer(aacDecInfo, sizeof(AACDecInfo));
aacDecInfo->psInfoBase = malloc(sizeof(PSInfoBase));
if (!aacDecInfo->psInfoBase) {
FreeBuffers(aacDecInfo);
return 0;
}
ClearBuffer(aacDecInfo->psInfoBase, sizeof(PSInfoBase));
return aacDecInfo;
}
#ifndef SAFE_FREE
#define SAFE_FREE(x) {if (x) free(x); (x) = 0;} /* helper macro */
#endif
/**************************************************************************************
* Function: FreeBuffers
*
* Description: frees all the memory used by the AAC decoder
*
* Inputs: pointer to initialized AACDecInfo structure
*
* Outputs: none
*
* Return: none
*
* Notes: safe to call even if some buffers were not allocated (uses SAFE_FREE)
**************************************************************************************/
void FreeBuffers(AACDecInfo *aacDecInfo)
{
if (!aacDecInfo)
return;
SAFE_FREE(aacDecInfo->psInfoBase);
SAFE_FREE(aacDecInfo);
}
|
1137519-player
|
aac/buffers.c
|
C
|
lgpl
| 4,702
|
# MCU name
MCU = -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -march=armv7e-m -mtune=cortex-m4 -mfloat-abi=softfp -mlittle-endian -mthumb-interwork
# Target file name (without extension).
TARGET = libaac.a
# List C source files here. (C dependencies are automatically generated.)
SRC = aacdec.c aactabs.c bitstream.c buffers.c dct4.c decelmnt.c dequant.c fft.c \
filefmt.c huffman.c hufftabs.c imdct.c noiseless.c pns.c sbr.c sbrfft.c sbrfreq.c \
sbrhfadj.c sbrhfgen.c sbrhuff.c sbrimdct.c sbrmath.c sbrqmf.c sbrside.c sbrtabs.c \
stproc.c tns.c trigtabs_fltgen.c trigtabs.c
ASRC =
# Optimization level, can be [0, 1, 2, 3, s].
# 0 = turn off optimization. s = optimize for size.
OPT = s
# Debugging format.
# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2.
# AVR (extended) COFF requires stabs, plus an avr-objcopy run.
DEBUG =
# List any extra directories to look for include files here.
# Each directory must be seperated by a space.
EXTRAINCDIRS = /usr/local/arm/arm-none-eabi/include ./
# Compiler flag to set the C Standard level.
# c89 - "ANSI" C
# gnu89 - c89 plus GCC extensions
# c99 - ISO C99 standard (not yet fully implemented)
# gnu99 - c99 plus GCC extensions
CSTANDARD =
# Place -D or -U options here
CDEFS = -DBUILD=0x`date '+%Y%m%d'` -DUSE_STDPERIPH_DRIVER -DUSE_DEFAULT_STDLIB
# Place -I options here
CINCS =
# Compiler flags.
# -g*: generate debugging information
# -O*: optimization level
# -f...: tuning, see GCC manual and avr-libc documentation
# -Wall...: warning level
# -Wa,...: tell GCC to pass this to the assembler.
# -adhlns...: create assembler listing
CFLAGS = -g$(DEBUG)
CFLAGS += $(CDEFS) $(CINCS)
CFLAGS += -O$(OPT)
#CFLAGS += -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums
#CFLAGS += -Wall -Wstrict-prototypes
#CFLAGS += -Wa,-adhlns=$(<:.c=.lst)
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
CFLAGS += $(CSTANDARD)
# Assembler flags.
# -Wa,...: tell GCC to pass this to the assembler.
# -ahlms: create listing
# -gstabs: have the assembler create line number information; note that
# for use in COFF files, additional information about filenames
# and function names needs to be present in the assembler source
# files -- see avr-libc docs [FIXME: not yet described there]
#ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs
ASFLAGS = -Wa,-gstabs
# Define programs and commands.
SHELL = sh
CC = arm-none-eabi-gcc
LD = arm-none-eabi-ld
AS = arm-none-eabi-as
OBJCOPY = arm-none-eabi-objcopy
OBJDUMP = arm-none-eabi-objdump
AR = arm-none-eabi-ar
SIZE = arm-none-eabi-size
NM = arm-none-eabi-nm
REMOVE = rm -f
COPY = cp
YACC = bison
LEX = flex
# Define all object files.
OBJ = $(SRC:.c=.o) $(ASRC:.s=.o)
# Define all listing files.
LST = $(ASRC:.s=.lst) $(SRC:.c=.lst)
# Compiler flags to generate dependency files.
#GENDEPFLAGS = -Wp,-M,-MP,-MT,$(*F).o,-MF,.dep/$(@F).d
# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = $(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
#ALL_ASFLAGS = -mcpu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS)
ALL_ASFLAGS = $(MCU) -I. -x assembler-with-cpp $(ASFLAGS)
# Default target.
all: $(TARGET)
$(TARGET): $(OBJ)
$(AR) rcu $(TARGET) $(OBJ)
# Eye candy.
# AVR Studio 3.x does not check make's exit code but relies on
# the following magic strings to be generated by the compile job.
# Display size of file.
HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) -A $(TARGET).elf
# Display compiler version information.
gccversion :
$(CC) --version
# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@
%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 -O $(FORMAT) $< $@
# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S $< > $@
# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
$(NM) -n $< > $@
# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
@echo
@echo $(MSG_LINKING) $@
$(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS)
# Compile: create object files from C source files.
%.o : %.c
@echo
@echo $(MSG_COMPILING) $<
$(CC) -c $(ALL_CFLAGS) $< -o $@
# Compile: create assembler files from C source files.
%.s : %.c
$(CC) -S $(ALL_CFLAGS) $< -o $@
# Assemble: create object files from assembler source files.
%.o : %.s
$(CC) -c $(ALL_ASFLAGS) $< -o $@
# Target: clean project.
clean:
$(REMOVE) $(TARGET)
$(REMOVE) $(OBJ)
$(REMOVE) $(LST)
$(REMOVE) $(SRC:.c=.s)
$(REMOVE) $(SRC:.c=.d)
$(REMOVE) .dep/*
# Include the dependency files.
#-include $(shell mkdir .dep 2>/dev/null) $(wildcard .dep/*)
# Listing of phony targets.
.PHONY : all sizebefore sizeafter gccversion \
build elf hex eep lss sym coff extcoff \
clean clean_list program
|
1137519-player
|
aac/Makefile
|
Makefile
|
lgpl
| 5,127
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: coder.h,v 1.2 2005/06/27 21:06:00 gwright Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* coder.h - definitions of platform-specific data structures, functions, and tables
**************************************************************************************/
#ifndef _CODER_H
#define _CODER_H
#include "aaccommon.h"
#include "bitstream.h"
#ifndef ASSERT
#if defined(_WIN32) && defined(_M_IX86) && (defined (_DEBUG) || defined (REL_ENABLE_ASSERTS))
#define ASSERT(x) if (!(x)) __asm int 3;
#else
#define ASSERT(x) /* do nothing */
#endif
#endif
#ifndef MAX
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
#ifndef MIN
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
#define NWINDOWS_LONG 1
#define NWINDOWS_SHORT 8
#define DATA_BUF_SIZE 510 /* max count = 255 + 255 */
#define FILL_BUF_SIZE 269 /* max count = 15 + 255 - 1*/
#define ADIF_COPYID_SIZE 9
#define MAX_COMMENT_BYTES 255
#define MAX_NUM_FCE 15
#define MAX_NUM_SCE 15
#define MAX_NUM_BCE 15
#define MAX_NUM_LCE 3
#define MAX_NUM_ADE 7
#define MAX_NUM_CCE 15
#define CHAN_ELEM_IS_CPE(x) (((x) & 0x10) >> 4) /* bit 4 = SCE/CPE flag */
#define CHAN_ELEM_GET_TAG(x) (((x) & 0x0f) >> 0) /* bits 3-0 = instance tag */
#define CHAN_ELEM_SET_CPE(x) (((x) & 0x01) << 4) /* bit 4 = SCE/CPE flag */
#define CHAN_ELEM_SET_TAG(x) (((x) & 0x0f) << 0) /* bits 3-0 = instance tag */
#define MAX_HUFF_BITS 20
#define HUFFTAB_SPEC_OFFSET 1
/* do y <<= n, clipping to range [-2^30, 2^30 - 1] (i.e. output has one guard bit) */
#define CLIP_2N_SHIFT(y, n) { \
int sign = (y) >> 31; \
if (sign != (y) >> (30 - (n))) { \
(y) = sign ^ (0x3fffffff); \
} else { \
(y) = (y) << (n); \
} \
}
/* clip to [-2^n, 2^n-1], valid range of n = [1, 30] */
#define CLIP_2N(val, n) { \
if ((val) >> 31 != (val) >> (n)) \
(val) = ((val) >> 31) ^ ((1 << (n)) - 1); \
}
#define SF_DQ_OFFSET 15
#define FBITS_OUT_DQ 20
#define FBITS_OUT_DQ_OFF (FBITS_OUT_DQ - SF_DQ_OFFSET) /* number of fraction bits out of dequant, including 2^15 bias */
#define FBITS_IN_IMDCT FBITS_OUT_DQ_OFF /* number of fraction bits into IMDCT */
#define GBITS_IN_DCT4 4 /* min guard bits in for DCT4 */
#define FBITS_LOST_DCT4 1 /* number of fraction bits lost (>> out) in DCT-IV */
#define FBITS_LOST_WND 1 /* number of fraction bits lost (>> out) in synthesis window (neg = gain frac bits) */
#define FBITS_LOST_IMDCT (FBITS_LOST_DCT4 + FBITS_LOST_WND)
#define FBITS_OUT_IMDCT (FBITS_IN_IMDCT - FBITS_LOST_IMDCT)
#define NUM_IMDCT_SIZES 2
/* additional external symbols to name-mangle for static linking */
#define DecodeProgramConfigElement STATNAME(DecodeProgramConfigElement)
#define DecodeHuffmanScalar STATNAME(DecodeHuffmanScalar)
#define DecodeSpectrumLong STATNAME(DecodeSpectrumLong)
#define DecodeSpectrumShort STATNAME(DecodeSpectrumShort)
#define DecodeICSInfo STATNAME(DecodeICSInfo)
#define DCT4 STATNAME(DCT4)
#define R4FFT STATNAME(R4FFT)
#define DecWindowOverlapNoClip STATNAME(DecWindowOverlapNoClip)
#define DecWindowOverlapLongStartNoClip STATNAME(DecWindowOverlapLongStartNoClip)
#define DecWindowOverlapLongStopNoClip STATNAME(DecWindowOverlapLongStopNoClip)
#define DecWindowOverlapShortNoClip STATNAME(DecWindowOverlapShortNoClip)
#define huffTabSpecInfo STATNAME(huffTabSpecInfo)
#define huffTabSpec STATNAME(huffTabSpec)
#define huffTabScaleFactInfo STATNAME(huffTabScaleFactInfo)
#define huffTabScaleFact STATNAME(huffTabScaleFact)
#define cos4sin4tab STATNAME(cos4sin4tab)
#define cos4sin4tabOffset STATNAME(cos4sin4tabOffset)
#define cos1sin1tab STATNAME(cos1sin1tab)
#define sinWindow STATNAME(sinWindow)
#define sinWindowOffset STATNAME(sinWindowOffset)
#define kbdWindow STATNAME(kbdWindow)
#define kbdWindowOffset STATNAME(kbdWindowOffset)
#define bitrevtab STATNAME(bitrevtab)
#define bitrevtabOffset STATNAME(bitrevtabOffset)
#define uniqueIDTab STATNAME(uniqueIDTab)
#define twidTabEven STATNAME(twidTabEven)
#define twidTabOdd STATNAME(twidTabOdd)
typedef struct _HuffInfo {
int maxBits; /* number of bits in longest codeword */
unsigned char count[MAX_HUFF_BITS]; /* count[i] = number of codes with length i+1 bits */
int offset; /* offset into symbol table */
} HuffInfo;
typedef struct _PulseInfo {
unsigned char pulseDataPresent;
unsigned char numPulse;
unsigned char startSFB;
unsigned char offset[MAX_PULSES];
unsigned char amp[MAX_PULSES];
} PulseInfo;
typedef struct _TNSInfo {
unsigned char tnsDataPresent;
unsigned char numFilt[MAX_TNS_FILTERS]; /* max 1 filter each for 8 short windows, or 3 filters for 1 long window */
unsigned char coefRes[MAX_TNS_FILTERS];
unsigned char length[MAX_TNS_FILTERS];
unsigned char order[MAX_TNS_FILTERS];
unsigned char dir[MAX_TNS_FILTERS];
signed char coef[MAX_TNS_COEFS]; /* max 3 filters * 20 coefs for 1 long window, or 1 filter * 7 coefs for each of 8 short windows */
} TNSInfo;
typedef struct _GainControlInfo {
unsigned char gainControlDataPresent;
unsigned char maxBand;
unsigned char adjNum[MAX_GAIN_BANDS][MAX_GAIN_WIN];
unsigned char alevCode[MAX_GAIN_BANDS][MAX_GAIN_WIN][MAX_GAIN_ADJUST];
unsigned char alocCode[MAX_GAIN_BANDS][MAX_GAIN_WIN][MAX_GAIN_ADJUST];
} GainControlInfo;
typedef struct _ICSInfo {
unsigned char icsResBit;
unsigned char winSequence;
unsigned char winShape;
unsigned char maxSFB;
unsigned char sfGroup;
unsigned char predictorDataPresent;
unsigned char predictorReset;
unsigned char predictorResetGroupNum;
unsigned char predictionUsed[MAX_PRED_SFB];
unsigned char numWinGroup;
unsigned char winGroupLen[MAX_WIN_GROUPS];
} ICSInfo;
typedef struct _ADTSHeader {
/* fixed */
unsigned char id; /* MPEG bit - should be 1 */
unsigned char layer; /* MPEG layer - should be 0 */
unsigned char protectBit; /* 0 = CRC word follows, 1 = no CRC word */
unsigned char profile; /* 0 = main, 1 = LC, 2 = SSR, 3 = reserved */
unsigned char sampRateIdx; /* sample rate index range = [0, 11] */
unsigned char privateBit; /* ignore */
unsigned char channelConfig; /* 0 = implicit, >0 = use default table */
unsigned char origCopy; /* 0 = copy, 1 = original */
unsigned char home; /* ignore */
/* variable */
unsigned char copyBit; /* 1 bit of the 72-bit copyright ID (transmitted as 1 bit per frame) */
unsigned char copyStart; /* 1 = this bit starts the 72-bit ID, 0 = it does not */
int frameLength; /* length of frame */
int bufferFull; /* number of 32-bit words left in enc buffer, 0x7FF = VBR */
unsigned char numRawDataBlocks; /* number of raw data blocks in frame */
/* CRC */
int crcCheckWord; /* 16-bit CRC check word (present if protectBit == 0) */
} ADTSHeader;
typedef struct _ADIFHeader {
unsigned char copyBit; /* 0 = no copyright ID, 1 = 72-bit copyright ID follows immediately */
unsigned char origCopy; /* 0 = copy, 1 = original */
unsigned char home; /* ignore */
unsigned char bsType; /* bitstream type: 0 = CBR, 1 = VBR */
int bitRate; /* bitRate: CBR = bits/sec, VBR = peak bits/frame, 0 = unknown */
unsigned char numPCE; /* number of program config elements (max = 16) */
int bufferFull; /* bits left in bit reservoir */
unsigned char copyID[ADIF_COPYID_SIZE]; /* optional 72-bit copyright ID */
} ADIFHeader;
/* sizeof(ProgConfigElement) = 82 bytes (if KEEP_PCE_COMMENTS not defined) */
typedef struct _ProgConfigElement {
unsigned char elemInstTag; /* element instance tag */
unsigned char profile; /* 0 = main, 1 = LC, 2 = SSR, 3 = reserved */
unsigned char sampRateIdx; /* sample rate index range = [0, 11] */
unsigned char numFCE; /* number of front channel elements (max = 15) */
unsigned char numSCE; /* number of side channel elements (max = 15) */
unsigned char numBCE; /* number of back channel elements (max = 15) */
unsigned char numLCE; /* number of LFE channel elements (max = 3) */
unsigned char numADE; /* number of associated data elements (max = 7) */
unsigned char numCCE; /* number of valid channel coupling elements (max = 15) */
unsigned char monoMixdown; /* mono mixdown: bit 4 = present flag, bits 3-0 = element number */
unsigned char stereoMixdown; /* stereo mixdown: bit 4 = present flag, bits 3-0 = element number */
unsigned char matrixMixdown; /* matrix mixdown: bit 4 = present flag, bit 3 = unused,
bits 2-1 = index, bit 0 = pseudo-surround enable */
unsigned char fce[MAX_NUM_FCE]; /* front element channel pair: bit 4 = SCE/CPE flag, bits 3-0 = inst tag */
unsigned char sce[MAX_NUM_SCE]; /* side element channel pair: bit 4 = SCE/CPE flag, bits 3-0 = inst tag */
unsigned char bce[MAX_NUM_BCE]; /* back element channel pair: bit 4 = SCE/CPE flag, bits 3-0 = inst tag */
unsigned char lce[MAX_NUM_LCE]; /* instance tag for LFE elements */
unsigned char ade[MAX_NUM_ADE]; /* instance tag for ADE elements */
unsigned char cce[MAX_NUM_BCE]; /* channel coupling elements: bit 4 = switching flag, bits 3-0 = inst tag */
#ifdef KEEP_PCE_COMMENTS
/* make this optional - if not enabled, decoder will just skip comments */
unsigned char commentBytes;
unsigned char commentField[MAX_COMMENT_BYTES];
#endif
} ProgConfigElement;
/* state info struct for baseline (MPEG-4 LC) decoding */
typedef struct _PSInfoBase {
/* header information */
ADTSHeader fhADTS;
ADIFHeader fhADIF;
ProgConfigElement pce[MAX_NUM_PCE_ADIF];
int dataCount;
unsigned char dataBuf[DATA_BUF_SIZE];
int fillCount;
unsigned char fillBuf[FILL_BUF_SIZE];
/* state information which is the same throughout whole frame */
int nChans;
int useImpChanMap;
int sampRateIdx;
/* state information which can be overwritten by subsequent elements within frame */
ICSInfo icsInfo[MAX_NCHANS_ELEM];
int commonWin;
short scaleFactors[MAX_NCHANS_ELEM][MAX_SF_BANDS];
unsigned char sfbCodeBook[MAX_NCHANS_ELEM][MAX_SF_BANDS];
int msMaskPresent;
unsigned char msMaskBits[MAX_MS_MASK_BYTES];
int pnsUsed[MAX_NCHANS_ELEM];
int pnsLastVal;
int intensityUsed[MAX_NCHANS_ELEM];
PulseInfo pulseInfo[MAX_NCHANS_ELEM];
TNSInfo tnsInfo[MAX_NCHANS_ELEM];
int tnsLPCBuf[MAX_TNS_ORDER];
int tnsWorkBuf[MAX_TNS_ORDER];
GainControlInfo gainControlInfo[MAX_NCHANS_ELEM];
int gbCurrent[MAX_NCHANS_ELEM];
int coef[MAX_NCHANS_ELEM][AAC_MAX_NSAMPS];
#ifdef AAC_ENABLE_SBR
int sbrWorkBuf[MAX_NCHANS_ELEM][AAC_MAX_NSAMPS];
#endif
/* state information which must be saved for each element and used in next frame */
int overlap[AAC_MAX_NCHANS][AAC_MAX_NSAMPS];
int prevWinShape[AAC_MAX_NCHANS];
} PSInfoBase;
/* private implementation-specific functions */
/* decelmnt.c */
int DecodeProgramConfigElement(ProgConfigElement *pce, BitStreamInfo *bsi);
/* huffman.c */
int DecodeHuffmanScalar(const signed short *huffTab, const HuffInfo *huffTabInfo, unsigned int bitBuf, signed int *val);
void DecodeSpectrumLong(PSInfoBase *psi, BitStreamInfo *bsi, int ch);
void DecodeSpectrumShort(PSInfoBase *psi, BitStreamInfo *bsi, int ch);
/* noiseless.c */
void DecodeICSInfo(BitStreamInfo *bsi, ICSInfo *icsInfo, int sampRateIdx);
/* dct4.c */
void DCT4(int tabidx, int *coef, int gb);
/* fft.c */
void R4FFT(int tabidx, int *x);
/* sbrimdct.c */
void DecWindowOverlapNoClip(int *buf0, int *over0, int *out0, int winTypeCurr, int winTypePrev);
void DecWindowOverlapLongStartNoClip(int *buf0, int *over0, int *out0, int winTypeCurr, int winTypePrev);
void DecWindowOverlapLongStopNoClip(int *buf0, int *over0, int *out0, int winTypeCurr, int winTypePrev);
void DecWindowOverlapShortNoClip(int *buf0, int *over0, int *out0, int winTypeCurr, int winTypePrev);
/* hufftabs.c */
extern const HuffInfo huffTabSpecInfo[11];
extern const signed short huffTabSpec[1241];
extern const HuffInfo huffTabScaleFactInfo;
extern const signed short huffTabScaleFact[121];
/* trigtabs.c */
extern const int cos4sin4tabOffset[NUM_IMDCT_SIZES];
extern const int sinWindowOffset[NUM_IMDCT_SIZES];
extern const int kbdWindowOffset[NUM_IMDCT_SIZES];
extern const unsigned char bitrevtab[17 + 129];
extern const int bitrevtabOffset[NUM_IMDCT_SIZES];
#ifdef HELIX_CONFIG_AAC_GENERATE_TRIGTABS_FLOAT
/* trigtabs_fltgen.c */
extern int cos4sin4tab[128 + 1024];
extern int cos1sin1tab[514];
extern int sinWindow[128 + 1024];
extern int kbdWindow[128 + 1024];
extern int twidTabEven[4*6 + 16*6 + 64*6];
extern int twidTabOdd[8*6 + 32*6 + 128*6];
#else
/* trigtabs.c */
extern const int cos4sin4tab[128 + 1024];
extern const int cos1sin1tab[514];
extern const int sinWindow[128 + 1024];
extern const int kbdWindow[128 + 1024];
extern const int twidTabEven[4*6 + 16*6 + 64*6];
extern const int twidTabOdd[8*6 + 32*6 + 128*6];
#endif
#endif /* _CODER_H */
|
1137519-player
|
aac/coder.h
|
C
|
lgpl
| 17,569
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: noiseless.c,v 1.3 2010/11/16 01:41:51 ching_li Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* noiseless.c - decode channel info, scalefactors, quantized coefficients,
* scalefactor band codebook, and TNS coefficients from bitstream
**************************************************************************************/
#include "coder.h"
/**************************************************************************************
* Function: DecodeICSInfo
*
* Description: decode individual channel stream info
*
* Inputs: BitStreamInfo struct pointing to start of ICS info
* (14496-3, table 4.4.6)
* sample rate index
*
* Outputs: updated icsInfo struct
*
* Return: none
**************************************************************************************/
void DecodeICSInfo(BitStreamInfo *bsi, ICSInfo *icsInfo, int sampRateIdx)
{
int sfb, g, mask;
icsInfo->icsResBit = GetBits(bsi, 1);
icsInfo->winSequence = GetBits(bsi, 2);
icsInfo->winShape = GetBits(bsi, 1);
if (icsInfo->winSequence == 2) {
/* short block */
icsInfo->maxSFB = GetBits(bsi, 4);
icsInfo->sfGroup = GetBits(bsi, 7);
icsInfo->numWinGroup = 1;
icsInfo->winGroupLen[0] = 1;
mask = 0x40; /* start with bit 6 */
for (g = 0; g < 7; g++) {
if (icsInfo->sfGroup & mask) {
icsInfo->winGroupLen[icsInfo->numWinGroup - 1]++;
} else {
icsInfo->numWinGroup++;
icsInfo->winGroupLen[icsInfo->numWinGroup - 1] = 1;
}
mask >>= 1;
}
} else {
/* long block */
icsInfo->maxSFB = GetBits(bsi, 6);
icsInfo->predictorDataPresent = GetBits(bsi, 1);
if (icsInfo->predictorDataPresent) {
icsInfo->predictorReset = GetBits(bsi, 1);
if (icsInfo->predictorReset)
icsInfo->predictorResetGroupNum = GetBits(bsi, 5);
for (sfb = 0; sfb < MIN(icsInfo->maxSFB, predSFBMax[sampRateIdx]); sfb++)
icsInfo->predictionUsed[sfb] = GetBits(bsi, 1);
}
icsInfo->numWinGroup = 1;
icsInfo->winGroupLen[0] = 1;
}
}
/**************************************************************************************
* Function: DecodeSectionData
*
* Description: decode section data (scale factor band groupings and
* associated Huffman codebooks)
*
* Inputs: BitStreamInfo struct pointing to start of ICS info
* (14496-3, table 4.4.25)
* window sequence (short or long blocks)
* number of window groups (1 for long blocks, 1-8 for short blocks)
* max coded scalefactor band
*
* Outputs: index of Huffman codebook for each scalefactor band in each section
*
* Return: none
*
* Notes: sectCB, sectEnd, sfbCodeBook, ordered by window groups for short blocks
**************************************************************************************/
static int DecodeSectionData(BitStreamInfo *bsi, int winSequence, int numWinGrp, int maxSFB, unsigned char *sfbCodeBook)
{
int g, cb, sfb;
int sectLen, sectLenBits, sectLenIncr, sectEscapeVal;
sectLenBits = (winSequence == 2 ? 3 : 5);
sectEscapeVal = (1 << sectLenBits) - 1;
for (g = 0; g < numWinGrp; g++) {
sfb = 0;
while (sfb < maxSFB) {
if (0 == bsi->nBytes && bsi->cachedBits < 4)
return ERR_AAC_INDATA_UNDERFLOW;
cb = GetBits(bsi, 4); /* next section codebook */
sectLen = 0;
do {
if (0 == bsi->nBytes && bsi->cachedBits < sectLenBits)
return ERR_AAC_INDATA_UNDERFLOW;
sectLenIncr = GetBits(bsi, sectLenBits);
sectLen += sectLenIncr;
} while (sectLenIncr == sectEscapeVal);
sfb += sectLen;
while (sectLen--)
*sfbCodeBook++ = (unsigned char)cb;
}
ASSERT(sfb == maxSFB);
}
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: DecodeOneScaleFactor
*
* Description: decode one scalefactor using scalefactor Huffman codebook
*
* Inputs: BitStreamInfo struct pointing to start of next coded scalefactor
*
* Outputs: updated BitstreamInfo struct
*
* Return: one decoded scalefactor, including index_offset of -60
**************************************************************************************/
static int DecodeOneScaleFactor(BitStreamInfo *bsi)
{
int nBits, val;
unsigned int bitBuf;
/* decode next scalefactor from bitstream */
bitBuf = GetBitsNoAdvance(bsi, huffTabScaleFactInfo.maxBits) << (32 - huffTabScaleFactInfo.maxBits);
nBits = DecodeHuffmanScalar(huffTabScaleFact, &huffTabScaleFactInfo, bitBuf, &val);
AdvanceBitstream(bsi, nBits);
return val;
}
/**************************************************************************************
* Function: DecodeScaleFactors
*
* Description: decode scalefactors, PNS energy, and intensity stereo weights
*
* Inputs: BitStreamInfo struct pointing to start of ICS info
* (14496-3, table 4.4.26)
* number of window groups (1 for long blocks, 1-8 for short blocks)
* max coded scalefactor band
* global gain (starting value for differential scalefactor coding)
* index of Huffman codebook for each scalefactor band in each section
*
* Outputs: decoded scalefactor for each section
*
* Return: none
*
* Notes: sfbCodeBook, scaleFactors ordered by window groups for short blocks
* for section with codebook 13, scaleFactors buffer has decoded PNS
* energy instead of regular scalefactor
* for section with codebook 14 or 15, scaleFactors buffer has intensity
* stereo weight instead of regular scalefactor
**************************************************************************************/
static void DecodeScaleFactors(BitStreamInfo *bsi, int numWinGrp, int maxSFB, int globalGain,
unsigned char *sfbCodeBook, short *scaleFactors)
{
int g, sfbCB, nrg, npf, val, sf, is;
/* starting values for differential coding */
sf = globalGain;
is = 0;
nrg = globalGain - 90 - 256;
npf = 1;
for (g = 0; g < numWinGrp * maxSFB; g++) {
sfbCB = *sfbCodeBook++;
if (sfbCB == 14 || sfbCB == 15) {
/* intensity stereo - differential coding */
val = DecodeOneScaleFactor(bsi);
is += val;
*scaleFactors++ = (short)is;
} else if (sfbCB == 13) {
/* PNS - first energy is directly coded, rest are Huffman coded (npf = noise_pcm_flag) */
if (npf) {
val = GetBits(bsi, 9);
npf = 0;
} else {
val = DecodeOneScaleFactor(bsi);
}
nrg += val;
*scaleFactors++ = (short)nrg;
} else if (sfbCB >= 1 && sfbCB <= 11) {
/* regular (non-zero) region - differential coding */
val = DecodeOneScaleFactor(bsi);
sf += val;
*scaleFactors++ = (short)sf;
} else {
/* inactive scalefactor band if codebook 0 */
*scaleFactors++ = 0;
}
}
}
/**************************************************************************************
* Function: DecodePulseInfo
*
* Description: decode pulse information
*
* Inputs: BitStreamInfo struct pointing to start of pulse info
* (14496-3, table 4.4.7)
*
* Outputs: updated PulseInfo struct
*
* Return: none
**************************************************************************************/
static void DecodePulseInfo(BitStreamInfo *bsi, PulseInfo *pi)
{
int i;
pi->numPulse = GetBits(bsi, 2) + 1; /* add 1 here */
pi->startSFB = GetBits(bsi, 6);
for (i = 0; i < pi->numPulse; i++) {
pi->offset[i] = GetBits(bsi, 5);
pi->amp[i] = GetBits(bsi, 4);
}
}
/**************************************************************************************
* Function: DecodeTNSInfo
*
* Description: decode TNS filter information
*
* Inputs: BitStreamInfo struct pointing to start of TNS info
* (14496-3, table 4.4.27)
* window sequence (short or long blocks)
*
* Outputs: updated TNSInfo struct
* buffer of decoded (signed) TNS filter coefficients
*
* Return: none
**************************************************************************************/
static void DecodeTNSInfo(BitStreamInfo *bsi, int winSequence, TNSInfo *ti, signed char *tnsCoef)
{
int i, w, f, coefBits, compress;
signed char c, s, n;
signed char sgnMask[3] = { 0x02, 0x04, 0x08};
signed char negMask[3] = {~0x03, ~0x07, ~0x0f};
unsigned char *filtLength, *filtOrder, *filtDir;
filtLength = ti->length;
filtOrder = ti->order;
filtDir = ti->dir;
if (winSequence == 2) {
/* short blocks */
for (w = 0; w < NWINDOWS_SHORT; w++) {
ti->numFilt[w] = GetBits(bsi, 1);
if (ti->numFilt[w]) {
ti->coefRes[w] = GetBits(bsi, 1) + 3;
*filtLength = GetBits(bsi, 4);
*filtOrder = GetBits(bsi, 3);
if (*filtOrder) {
*filtDir++ = GetBits(bsi, 1);
compress = GetBits(bsi, 1);
coefBits = (int)ti->coefRes[w] - compress; /* 2, 3, or 4 */
s = sgnMask[coefBits - 2];
n = negMask[coefBits - 2];
for (i = 0; i < *filtOrder; i++) {
c = GetBits(bsi, coefBits);
if (c & s) c |= n;
*tnsCoef++ = c;
}
}
filtLength++;
filtOrder++;
}
}
} else {
/* long blocks */
ti->numFilt[0] = GetBits(bsi, 2);
if (ti->numFilt[0])
ti->coefRes[0] = GetBits(bsi, 1) + 3;
for (f = 0; f < ti->numFilt[0]; f++) {
*filtLength = GetBits(bsi, 6);
*filtOrder = GetBits(bsi, 5);
if (*filtOrder) {
*filtDir++ = GetBits(bsi, 1);
compress = GetBits(bsi, 1);
coefBits = (int)ti->coefRes[0] - compress; /* 2, 3, or 4 */
s = sgnMask[coefBits - 2];
n = negMask[coefBits - 2];
for (i = 0; i < *filtOrder; i++) {
c = GetBits(bsi, coefBits);
if (c & s) c |= n;
*tnsCoef++ = c;
}
}
filtLength++;
filtOrder++;
}
}
}
/* bitstream field lengths for gain control data:
* gainBits[winSequence][0] = maxWindow (how many gain windows there are)
* gainBits[winSequence][1] = locBitsZero (bits for alocCode if window == 0)
* gainBits[winSequence][2] = locBits (bits for alocCode if window != 0)
*/
static const unsigned char gainBits[4][3] = {
{1, 5, 5}, /* long */
{2, 4, 2}, /* start */
{8, 2, 2}, /* short */
{2, 4, 5}, /* stop */
};
/**************************************************************************************
* Function: DecodeGainControlInfo
*
* Description: decode gain control information (SSR profile only)
*
* Inputs: BitStreamInfo struct pointing to start of gain control info
* (14496-3, table 4.4.12)
* window sequence (short or long blocks)
*
* Outputs: updated GainControlInfo struct
*
* Return: none
**************************************************************************************/
static void DecodeGainControlInfo(BitStreamInfo *bsi, int winSequence, GainControlInfo *gi)
{
int bd, wd, ad;
int locBits, locBitsZero, maxWin;
gi->maxBand = GetBits(bsi, 2);
maxWin = (int)gainBits[winSequence][0];
locBitsZero = (int)gainBits[winSequence][1];
locBits = (int)gainBits[winSequence][2];
for (bd = 1; bd <= gi->maxBand; bd++) {
for (wd = 0; wd < maxWin; wd++) {
gi->adjNum[bd][wd] = GetBits(bsi, 3);
for (ad = 0; ad < gi->adjNum[bd][wd]; ad++) {
gi->alevCode[bd][wd][ad] = GetBits(bsi, 4);
gi->alocCode[bd][wd][ad] = GetBits(bsi, (wd == 0 ? locBitsZero : locBits));
}
}
}
}
/**************************************************************************************
* Function: DecodeICS
*
* Description: decode individual channel stream
*
* Inputs: platform specific info struct
* BitStreamInfo struct pointing to start of individual channel stream
* (14496-3, table 4.4.24)
* index of current channel
*
* Outputs: updated section data, scale factor data, pulse data, TNS data,
* and gain control data
*
* Return: none
**************************************************************************************/
static int DecodeICS(PSInfoBase *psi, BitStreamInfo *bsi, int ch)
{
int globalGain;
ICSInfo *icsInfo;
PulseInfo *pi;
TNSInfo *ti;
GainControlInfo *gi;
icsInfo = (ch == 1 && psi->commonWin == 1) ? &(psi->icsInfo[0]) : &(psi->icsInfo[ch]);
globalGain = GetBits(bsi, 8);
if (!psi->commonWin)
DecodeICSInfo(bsi, icsInfo, psi->sampRateIdx);
if ( DecodeSectionData(bsi, icsInfo->winSequence, icsInfo->numWinGroup, icsInfo->maxSFB, psi->sfbCodeBook[ch]) )
return ERR_AAC_INDATA_UNDERFLOW;
DecodeScaleFactors(bsi, icsInfo->numWinGroup, icsInfo->maxSFB, globalGain, psi->sfbCodeBook[ch], psi->scaleFactors[ch]);
pi = &psi->pulseInfo[ch];
pi->pulseDataPresent = GetBits(bsi, 1);
if (pi->pulseDataPresent)
DecodePulseInfo(bsi, pi);
ti = &psi->tnsInfo[ch];
ti->tnsDataPresent = GetBits(bsi, 1);
if (ti->tnsDataPresent)
DecodeTNSInfo(bsi, icsInfo->winSequence, ti, ti->coef);
gi = &psi->gainControlInfo[ch];
gi->gainControlDataPresent = GetBits(bsi, 1);
if (gi->gainControlDataPresent)
DecodeGainControlInfo(bsi, icsInfo->winSequence, gi);
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: DecodeNoiselessData
*
* Description: decode noiseless data (side info and transform coefficients)
*
* Inputs: valid AACDecInfo struct
* double pointer to buffer pointing to start of individual channel stream
* (14496-3, table 4.4.24)
* pointer to bit offset
* pointer to number of valid bits remaining in buf
* index of current channel
*
* Outputs: updated global gain, section data, scale factor data, pulse data,
* TNS data, gain control data, and spectral data
*
* Return: 0 if successful, error code (< 0) if error
**************************************************************************************/
int DecodeNoiselessData(AACDecInfo *aacDecInfo, unsigned char **buf, int *bitOffset, int *bitsAvail, int ch)
{
int bitsUsed;
BitStreamInfo bsi;
PSInfoBase *psi;
ICSInfo *icsInfo;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
icsInfo = (ch == 1 && psi->commonWin == 1) ? &(psi->icsInfo[0]) : &(psi->icsInfo[ch]);
SetBitstreamPointer(&bsi, (*bitsAvail+7) >> 3, *buf);
GetBits(&bsi, *bitOffset);
if ( DecodeICS(psi, &bsi, ch) )
return ERR_AAC_INDATA_UNDERFLOW;
if (icsInfo->winSequence == 2)
DecodeSpectrumShort(psi, &bsi, ch);
else
DecodeSpectrumLong(psi, &bsi, ch);
bitsUsed = CalcBitsUsed(&bsi, *buf, *bitOffset);
*buf += ((bitsUsed + *bitOffset) >> 3);
*bitOffset = ((bitsUsed + *bitOffset) & 0x07);
*bitsAvail -= bitsUsed;
if( *bitsAvail <0 )
{
return ERR_AAC_INDATA_UNDERFLOW;
}
aacDecInfo->sbDeinterleaveReqd[ch] = 0;
aacDecInfo->tnsUsed |= psi->tnsInfo[ch].tnsDataPresent; /* set flag if TNS used for any channel */
return ERR_AAC_NONE;
}
|
1137519-player
|
aac/noiseless.c
|
C
|
lgpl
| 16,881
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: pns.c,v 1.2 2005/03/10 17:01:56 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* pns.c - perceptual noise substitution
**************************************************************************************/
#include "coder.h"
#include "assembly.h"
/**************************************************************************************
* Function: Get32BitVal
*
* Description: generate 32-bit unsigned random number
*
* Inputs: last number calculated (seed, first time through)
*
* Outputs: new number, saved in *last
*
* Return: 32-bit number, uniformly distributed between [0, 2^32)
*
* Notes: uses simple linear congruential generator
**************************************************************************************/
static unsigned int Get32BitVal(unsigned int *last)
{
unsigned int r = *last;
/* use same coefs as MPEG reference code (classic LCG)
* use unsigned multiply to force reliable wraparound behavior in C (mod 2^32)
*/
r = (1664525U * r) + 1013904223U;
*last = r;
return r;
}
/* pow(2, i/4.0) for i = [0,1,2,3], format = Q30 */
static const int pow14[4] = {
0x40000000, 0x4c1bf829, 0x5a82799a, 0x6ba27e65
};
#define NUM_ITER_INVSQRT 4
#define X0_COEF_2 0xc0000000 /* Q29: -2.0 */
#define X0_OFF_2 0x60000000 /* Q29: 3.0 */
#define Q26_3 0x0c000000 /* Q26: 3.0 */
/**************************************************************************************
* Function: InvRootR
*
* Description: use Newton's method to solve for x = 1/sqrt(r)
*
* Inputs: r in Q30 format, range = [0.25, 1] (normalize inputs to this range)
*
* Outputs: none
*
* Return: x = Q29, range = (1, 2)
*
* Notes: guaranteed to converge and not overflow for any r in this range
*
* xn+1 = xn - f(xn)/f'(xn)
* f(x) = 1/sqrt(r) - x = 0 (find root)
* = 1/x^2 - r
* f'(x) = -2/x^3
*
* so xn+1 = xn/2 * (3 - r*xn^2)
*
* NUM_ITER_INVSQRT = 3, maxDiff = 1.3747e-02
* NUM_ITER_INVSQRT = 4, maxDiff = 3.9832e-04
**************************************************************************************/
static int InvRootR(int r)
{
int i, xn, t;
/* use linear equation for initial guess
* x0 = -2*r + 3 (so x0 always >= correct answer in range [0.25, 1))
* xn = Q29 (at every step)
*/
xn = (MULSHIFT32(r, X0_COEF_2) << 2) + X0_OFF_2;
for (i = 0; i < NUM_ITER_INVSQRT; i++) {
t = MULSHIFT32(xn, xn); /* Q26 = Q29*Q29 */
t = Q26_3 - (MULSHIFT32(r, t) << 2); /* Q26 = Q26 - (Q31*Q26 << 1) */
xn = MULSHIFT32(xn, t) << (6 - 1); /* Q29 = (Q29*Q26 << 6), and -1 for division by 2 */
}
/* clip to range (1.0, 2.0)
* (because of rounding, this can converge to xn slightly > 2.0 when r is near 0.25)
*/
if (xn >> 30)
xn = (1 << 30) - 1;
return xn;
}
/**************************************************************************************
* Function: ScaleNoiseVector
*
* Description: apply scaling to vector of noise coefficients for one scalefactor band
*
* Inputs: unscaled coefficients
* number of coefficients in vector (one scalefactor band of coefs)
* scalefactor for this band (i.e. noise energy)
*
* Outputs: nVals coefficients in Q(FBITS_OUT_DQ_OFF)
*
* Return: guard bit mask (OR of abs value of all noise coefs)
**************************************************************************************/
static int ScaleNoiseVector(int *coef, int nVals, int sf)
{
int i, c, spec, energy, sq, scalef, scalei, invSqrtEnergy, z, gbMask;
energy = 0;
for (i = 0; i < nVals; i++) {
spec = coef[i];
/* max nVals = max SFB width = 96, so energy can gain < 2^7 bits in accumulation */
sq = (spec * spec) >> 8; /* spec*spec range = (-2^30, 2^30) */
energy += sq;
}
/* unless nVals == 1 (or the number generator is broken...), this should not happen */
if (energy == 0)
return 0; /* coef[i] must = 0 for i = [0, nVals-1], so gbMask = 0 */
/* pow(2, sf/4) * pow(2, FBITS_OUT_DQ_OFF) */
scalef = pow14[sf & 0x3];
scalei = (sf >> 2) + FBITS_OUT_DQ_OFF;
/* energy has implied factor of 2^-8 since we shifted the accumulator
* normalize energy to range [0.25, 1.0), calculate 1/sqrt(1), and denormalize
* i.e. divide input by 2^(30-z) and convert to Q30
* output of 1/sqrt(i) now has extra factor of 2^((30-z)/2)
* for energy > 0, z is an even number between 0 and 28
* final scaling of invSqrtEnergy:
* 2^(15 - z/2) to compensate for implicit 2^(30-z) factor in input
* +4 to compensate for implicit 2^-8 factor in input
*/
z = CLZ(energy) - 2; /* energy has at least 2 leading zeros (see acc loop) */
z &= 0xfffffffe; /* force even */
invSqrtEnergy = InvRootR(energy << z); /* energy << z must be in range [0x10000000, 0x40000000] */
scalei -= (15 - z/2 + 4); /* nInt = 1/sqrt(energy) in Q29 */
/* normalize for final scaling */
z = CLZ(invSqrtEnergy) - 1;
invSqrtEnergy <<= z;
scalei -= (z - 3 - 2); /* -2 for scalef, z-3 for invSqrtEnergy */
scalef = MULSHIFT32(scalef, invSqrtEnergy); /* scalef (input) = Q30, invSqrtEnergy = Q29 * 2^z */
gbMask = 0;
if (scalei < 0) {
scalei = -scalei;
if (scalei > 31)
scalei = 31;
for (i = 0; i < nVals; i++) {
c = MULSHIFT32(coef[i], scalef) >> scalei;
gbMask |= FASTABS(c);
coef[i] = c;
}
} else {
/* for scalei <= 16, no clipping possible (coef[i] is < 2^15 before scaling)
* for scalei > 16, just saturate exponent (rare)
* scalef is close to full-scale (since we normalized invSqrtEnergy)
* remember, we are just producing noise here
*/
if (scalei > 16)
scalei = 16;
for (i = 0; i < nVals; i++) {
c = MULSHIFT32(coef[i] << scalei, scalef);
coef[i] = c;
gbMask |= FASTABS(c);
}
}
return gbMask;
}
/**************************************************************************************
* Function: GenerateNoiseVector
*
* Description: create vector of noise coefficients for one scalefactor band
*
* Inputs: seed for number generator
* number of coefficients to generate
*
* Outputs: buffer of nVals coefficients, range = [-2^15, 2^15)
* updated seed for number generator
*
* Return: none
**************************************************************************************/
static void GenerateNoiseVector(int *coef, int *last, int nVals)
{
int i;
for (i = 0; i < nVals; i++)
coef[i] = ((signed int)Get32BitVal((unsigned int *)last)) >> 16;
}
/**************************************************************************************
* Function: CopyNoiseVector
*
* Description: copy vector of noise coefficients for one scalefactor band from L to R
*
* Inputs: buffer of left coefficients
* number of coefficients to copy
*
* Outputs: buffer of right coefficients
*
* Return: none
**************************************************************************************/
static void CopyNoiseVector(int *coefL, int *coefR, int nVals)
{
int i;
for (i = 0; i < nVals; i++)
coefR[i] = coefL[i];
}
/**************************************************************************************
* Function: PNS
*
* Description: apply perceptual noise substitution, if enabled (MPEG-4 only)
*
* Inputs: valid AACDecInfo struct
* index of current channel
*
* Outputs: shaped noise in scalefactor bands where PNS is active
* updated minimum guard bit count for this channel
*
* Return: 0 if successful, -1 if error
**************************************************************************************/
int PNS(AACDecInfo *aacDecInfo, int ch)
{
int gp, sfb, win, width, nSamps, gb, gbMask;
int *coef;
const short *sfbTab;
unsigned char *sfbCodeBook;
short *scaleFactors;
int msMaskOffset, checkCorr, genNew;
unsigned char msMask;
unsigned char *msMaskPtr;
PSInfoBase *psi;
ICSInfo *icsInfo;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return -1;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
icsInfo = (ch == 1 && psi->commonWin == 1) ? &(psi->icsInfo[0]) : &(psi->icsInfo[ch]);
if (!psi->pnsUsed[ch])
return 0;
if (icsInfo->winSequence == 2) {
sfbTab = sfBandTabShort + sfBandTabShortOffset[psi->sampRateIdx];
nSamps = NSAMPS_SHORT;
} else {
sfbTab = sfBandTabLong + sfBandTabLongOffset[psi->sampRateIdx];
nSamps = NSAMPS_LONG;
}
coef = psi->coef[ch];
sfbCodeBook = psi->sfbCodeBook[ch];
scaleFactors = psi->scaleFactors[ch];
checkCorr = (aacDecInfo->currBlockID == AAC_ID_CPE && psi->commonWin == 1 ? 1 : 0);
gbMask = 0;
for (gp = 0; gp < icsInfo->numWinGroup; gp++) {
for (win = 0; win < icsInfo->winGroupLen[gp]; win++) {
msMaskPtr = psi->msMaskBits + ((gp*icsInfo->maxSFB) >> 3);
msMaskOffset = ((gp*icsInfo->maxSFB) & 0x07);
msMask = (*msMaskPtr++) >> msMaskOffset;
for (sfb = 0; sfb < icsInfo->maxSFB; sfb++) {
width = sfbTab[sfb+1] - sfbTab[sfb];
if (sfbCodeBook[sfb] == 13) {
if (ch == 0) {
/* generate new vector, copy into ch 1 if it's possible that the channels will be correlated
* if ch 1 has PNS enabled for this SFB but it's uncorrelated (i.e. ms_used == 0),
* the copied values will be overwritten when we process ch 1
*/
GenerateNoiseVector(coef, &psi->pnsLastVal, width);
if (checkCorr && psi->sfbCodeBook[1][gp*icsInfo->maxSFB + sfb] == 13)
CopyNoiseVector(coef, psi->coef[1] + (coef - psi->coef[0]), width);
} else {
/* generate new vector if no correlation between channels */
genNew = 1;
if (checkCorr && psi->sfbCodeBook[0][gp*icsInfo->maxSFB + sfb] == 13) {
if ( (psi->msMaskPresent == 1 && (msMask & 0x01)) || psi->msMaskPresent == 2 )
genNew = 0;
}
if (genNew)
GenerateNoiseVector(coef, &psi->pnsLastVal, width);
}
gbMask |= ScaleNoiseVector(coef, width, psi->scaleFactors[ch][gp*icsInfo->maxSFB + sfb]);
}
coef += width;
/* get next mask bit (should be branchless on ARM) */
msMask >>= 1;
if (++msMaskOffset == 8) {
msMask = *msMaskPtr++;
msMaskOffset = 0;
}
}
coef += (nSamps - sfbTab[icsInfo->maxSFB]);
}
sfbCodeBook += icsInfo->maxSFB;
scaleFactors += icsInfo->maxSFB;
}
/* update guard bit count if necessary */
gb = CLZ(gbMask) - 1;
if (psi->gbCurrent[ch] > gb)
psi->gbCurrent[ch] = gb;
return 0;
}
|
1137519-player
|
aac/pns.c
|
C
|
lgpl
| 12,361
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: stproc.c,v 1.3 2005/05/24 16:01:55 albertofloyd Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* stproc.c - mid-side and intensity stereo processing
**************************************************************************************/
#include "coder.h"
#include "assembly.h"
/* pow14[0][i] = -pow(2, i/4.0)
* pow14[1][i] = +pow(2, i/4.0)
*
* i = [0,1,2,3]
* format = Q30
*/
static const int pow14[2][4] = {
{ 0xc0000000, 0xb3e407d7, 0xa57d8666, 0x945d819b },
{ 0x40000000, 0x4c1bf829, 0x5a82799a, 0x6ba27e65 }
};
/**************************************************************************************
* Function: StereoProcessGroup
*
* Description: apply mid-side and intensity stereo to group of transform coefficients
*
* Inputs: dequantized transform coefficients for both channels
* pointer to appropriate scalefactor band table
* mid-side mask enabled flag
* buffer with mid-side mask (one bit for each scalefactor band)
* bit offset into mid-side mask buffer
* max coded scalefactor band
* buffer of codebook indices for right channel
* buffer of scalefactors for right channel, range = [0, 256]
*
* Outputs: updated transform coefficients in Q(FBITS_OUT_DQ_OFF)
* updated minimum guard bit count for both channels
*
* Return: none
*
* Notes: assume no guard bits in input
* gains 0 int bits
**************************************************************************************/
static void StereoProcessGroup(int *coefL, int *coefR, const short *sfbTab,
int msMaskPres, unsigned char *msMaskPtr, int msMaskOffset, int maxSFB,
unsigned char *cbRight, short *sfRight, int *gbCurrent)
{
int sfb, width, cbIdx, sf, cl, cr, scalef, scalei;
int gbMaskL, gbMaskR;
unsigned char msMask;
msMask = (*msMaskPtr++) >> msMaskOffset;
gbMaskL = 0;
gbMaskR = 0;
for (sfb = 0; sfb < maxSFB; sfb++) {
width = sfbTab[sfb+1] - sfbTab[sfb]; /* assume >= 0 (see sfBandTabLong/sfBandTabShort) */
cbIdx = cbRight[sfb];
if (cbIdx == 14 || cbIdx == 15) {
/* intensity stereo */
if (msMaskPres == 1 && (msMask & 0x01))
cbIdx ^= 0x01; /* invert_intensity(): 14 becomes 15, or 15 becomes 14 */
sf = -sfRight[sfb]; /* negative since we use identity 0.5^(x) = 2^(-x) (see spec) */
cbIdx &= 0x01; /* choose - or + scale factor */
scalef = pow14[cbIdx][sf & 0x03];
scalei = (sf >> 2) + 2; /* +2 to compensate for scalef = Q30 */
if (scalei > 0) {
if (scalei > 30)
scalei = 30;
do {
cr = MULSHIFT32(*coefL++, scalef);
CLIP_2N(cr, 31-scalei);
cr <<= scalei;
gbMaskR |= FASTABS(cr);
*coefR++ = cr;
} while (--width);
} else {
scalei = -scalei;
if (scalei > 31)
scalei = 31;
do {
cr = MULSHIFT32(*coefL++, scalef) >> scalei;
gbMaskR |= FASTABS(cr);
*coefR++ = cr;
} while (--width);
}
} else if ( cbIdx != 13 && ((msMaskPres == 1 && (msMask & 0x01)) || msMaskPres == 2) ) {
/* mid-side stereo (assumes no GB in inputs) */
do {
cl = *coefL;
cr = *coefR;
if ( (FASTABS(cl) | FASTABS(cr)) >> 30 ) {
/* avoid overflow (rare) */
cl >>= 1;
sf = cl + (cr >> 1); CLIP_2N(sf, 30); sf <<= 1;
cl = cl - (cr >> 1); CLIP_2N(cl, 30); cl <<= 1;
} else {
/* usual case */
sf = cl + cr;
cl -= cr;
}
*coefL++ = sf;
gbMaskL |= FASTABS(sf);
*coefR++ = cl;
gbMaskR |= FASTABS(cl);
} while (--width);
} else {
/* nothing to do */
coefL += width;
coefR += width;
}
/* get next mask bit (should be branchless on ARM) */
msMask >>= 1;
if (++msMaskOffset == 8) {
msMask = *msMaskPtr++;
msMaskOffset = 0;
}
}
cl = CLZ(gbMaskL) - 1;
if (gbCurrent[0] > cl)
gbCurrent[0] = cl;
cr = CLZ(gbMaskR) - 1;
if (gbCurrent[1] > cr)
gbCurrent[1] = cr;
return;
}
/**************************************************************************************
* Function: StereoProcess
*
* Description: apply mid-side and intensity stereo, if enabled
*
* Inputs: valid AACDecInfo struct (including dequantized transform coefficients)
*
* Outputs: updated transform coefficients in Q(FBITS_OUT_DQ_OFF)
* updated minimum guard bit count for both channels
*
* Return: 0 if successful, -1 if error
**************************************************************************************/
int StereoProcess(AACDecInfo *aacDecInfo)
{
PSInfoBase *psi;
ICSInfo *icsInfo;
int gp, win, nSamps, msMaskOffset;
int *coefL, *coefR;
unsigned char *msMaskPtr;
const short *sfbTab;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return -1;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
/* mid-side and intensity stereo require common_window == 1 (see MPEG4 spec, Correction 2, 2004) */
if (psi->commonWin != 1 || aacDecInfo->currBlockID != AAC_ID_CPE)
return 0;
/* nothing to do */
if (!psi->msMaskPresent && !psi->intensityUsed[1])
return 0;
icsInfo = &(psi->icsInfo[0]);
if (icsInfo->winSequence == 2) {
sfbTab = sfBandTabShort + sfBandTabShortOffset[psi->sampRateIdx];
nSamps = NSAMPS_SHORT;
} else {
sfbTab = sfBandTabLong + sfBandTabLongOffset[psi->sampRateIdx];
nSamps = NSAMPS_LONG;
}
coefL = psi->coef[0];
coefR = psi->coef[1];
/* do fused mid-side/intensity processing for each block (one long or eight short) */
msMaskOffset = 0;
msMaskPtr = psi->msMaskBits;
for (gp = 0; gp < icsInfo->numWinGroup; gp++) {
for (win = 0; win < icsInfo->winGroupLen[gp]; win++) {
StereoProcessGroup(coefL, coefR, sfbTab, psi->msMaskPresent,
msMaskPtr, msMaskOffset, icsInfo->maxSFB, psi->sfbCodeBook[1] + gp*icsInfo->maxSFB,
psi->scaleFactors[1] + gp*icsInfo->maxSFB, psi->gbCurrent);
coefL += nSamps;
coefR += nSamps;
}
/* we use one bit per sfb, so there are maxSFB bits for each window group */
msMaskPtr += (msMaskOffset + icsInfo->maxSFB) >> 3;
msMaskOffset = (msMaskOffset + icsInfo->maxSFB) & 0x07;
}
ASSERT(coefL == psi->coef[0] + 1024);
ASSERT(coefR == psi->coef[1] + 1024);
return 0;
}
|
1137519-player
|
aac/stproc.c
|
C
|
lgpl
| 8,038
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: dct4.c,v 1.1 2005/02/26 01:47:34 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com), Ken Cooke (kenc@real.com)
* February 2005
*
* dct4.c - optimized DCT-IV
**************************************************************************************/
#include "coder.h"
#include "assembly.h"
static const int nmdctTab[NUM_IMDCT_SIZES] = {128, 1024};
static const int postSkip[NUM_IMDCT_SIZES] = {15, 1};
/**************************************************************************************
* Function: PreMultiply
*
* Description: pre-twiddle stage of DCT4
*
* Inputs: table index (for transform size)
* buffer of nmdct samples
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: minimum 1 GB in, 2 GB out, gains 5 (short) or 8 (long) frac bits
* i.e. gains 2-7= -5 int bits (short) or 2-10 = -8 int bits (long)
* normalization by -1/N is rolled into tables here (see trigtabs.c)
* uses 3-mul, 3-add butterflies instead of 4-mul, 2-add
**************************************************************************************/
static void PreMultiply(int tabidx, int *zbuf1)
{
int i, nmdct, ar1, ai1, ar2, ai2, z1, z2;
int t, cms2, cps2a, sin2a, cps2b, sin2b;
int *zbuf2;
const int *csptr;
nmdct = nmdctTab[tabidx];
zbuf2 = zbuf1 + nmdct - 1;
csptr = cos4sin4tab + cos4sin4tabOffset[tabidx];
/* whole thing should fit in registers - verify that compiler does this */
for (i = nmdct >> 2; i != 0; i--) {
/* cps2 = (cos+sin), sin2 = sin, cms2 = (cos-sin) */
cps2a = *csptr++;
sin2a = *csptr++;
cps2b = *csptr++;
sin2b = *csptr++;
ar1 = *(zbuf1 + 0);
ai2 = *(zbuf1 + 1);
ai1 = *(zbuf2 + 0);
ar2 = *(zbuf2 - 1);
/* gain 2 ints bit from MULSHIFT32 by Q30, but drop 7 or 10 int bits from table scaling of 1/M
* max per-sample gain (ignoring implicit scaling) = MAX(sin(angle)+cos(angle)) = 1.414
* i.e. gain 1 GB since worst case is sin(angle) = cos(angle) = 0.707 (Q30), gain 2 from
* extra sign bits, and eat one in adding
*/
t = MULSHIFT32(sin2a, ar1 + ai1);
z2 = MULSHIFT32(cps2a, ai1) - t;
cms2 = cps2a - 2*sin2a;
z1 = MULSHIFT32(cms2, ar1) + t;
*zbuf1++ = z1; /* cos*ar1 + sin*ai1 */
*zbuf1++ = z2; /* cos*ai1 - sin*ar1 */
t = MULSHIFT32(sin2b, ar2 + ai2);
z2 = MULSHIFT32(cps2b, ai2) - t;
cms2 = cps2b - 2*sin2b;
z1 = MULSHIFT32(cms2, ar2) + t;
*zbuf2-- = z2; /* cos*ai2 - sin*ar2 */
*zbuf2-- = z1; /* cos*ar2 + sin*ai2 */
}
}
/**************************************************************************************
* Function: PostMultiply
*
* Description: post-twiddle stage of DCT4
*
* Inputs: table index (for transform size)
* buffer of nmdct samples
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: minimum 1 GB in, 2 GB out - gains 2 int bits
* uses 3-mul, 3-add butterflies instead of 4-mul, 2-add
**************************************************************************************/
static void PostMultiply(int tabidx, int *fft1)
{
int i, nmdct, ar1, ai1, ar2, ai2, skipFactor;
int t, cms2, cps2, sin2;
int *fft2;
const int *csptr;
nmdct = nmdctTab[tabidx];
csptr = cos1sin1tab;
skipFactor = postSkip[tabidx];
fft2 = fft1 + nmdct - 1;
/* load coeffs for first pass
* cps2 = (cos+sin), sin2 = sin, cms2 = (cos-sin)
*/
cps2 = *csptr++;
sin2 = *csptr;
csptr += skipFactor;
cms2 = cps2 - 2*sin2;
for (i = nmdct >> 2; i != 0; i--) {
ar1 = *(fft1 + 0);
ai1 = *(fft1 + 1);
ar2 = *(fft2 - 1);
ai2 = *(fft2 + 0);
/* gain 2 ints bit from MULSHIFT32 by Q30
* max per-sample gain = MAX(sin(angle)+cos(angle)) = 1.414
* i.e. gain 1 GB since worst case is sin(angle) = cos(angle) = 0.707 (Q30), gain 2 from
* extra sign bits, and eat one in adding
*/
t = MULSHIFT32(sin2, ar1 + ai1);
*fft2-- = t - MULSHIFT32(cps2, ai1); /* sin*ar1 - cos*ai1 */
*fft1++ = t + MULSHIFT32(cms2, ar1); /* cos*ar1 + sin*ai1 */
cps2 = *csptr++;
sin2 = *csptr;
csptr += skipFactor;
ai2 = -ai2;
t = MULSHIFT32(sin2, ar2 + ai2);
*fft2-- = t - MULSHIFT32(cps2, ai2); /* sin*ar1 - cos*ai1 */
cms2 = cps2 - 2*sin2;
*fft1++ = t + MULSHIFT32(cms2, ar2); /* cos*ar1 + sin*ai1 */
}
}
/**************************************************************************************
* Function: PreMultiplyRescale
*
* Description: pre-twiddle stage of DCT4, with rescaling for extra guard bits
*
* Inputs: table index (for transform size)
* buffer of nmdct samples
* number of guard bits to add to input before processing
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: see notes on PreMultiply(), above
**************************************************************************************/
static void PreMultiplyRescale(int tabidx, int *zbuf1, int es)
{
int i, nmdct, ar1, ai1, ar2, ai2, z1, z2;
int t, cms2, cps2a, sin2a, cps2b, sin2b;
int *zbuf2;
const int *csptr;
nmdct = nmdctTab[tabidx];
zbuf2 = zbuf1 + nmdct - 1;
csptr = cos4sin4tab + cos4sin4tabOffset[tabidx];
/* whole thing should fit in registers - verify that compiler does this */
for (i = nmdct >> 2; i != 0; i--) {
/* cps2 = (cos+sin), sin2 = sin, cms2 = (cos-sin) */
cps2a = *csptr++;
sin2a = *csptr++;
cps2b = *csptr++;
sin2b = *csptr++;
ar1 = *(zbuf1 + 0) >> es;
ai1 = *(zbuf2 + 0) >> es;
ai2 = *(zbuf1 + 1) >> es;
t = MULSHIFT32(sin2a, ar1 + ai1);
z2 = MULSHIFT32(cps2a, ai1) - t;
cms2 = cps2a - 2*sin2a;
z1 = MULSHIFT32(cms2, ar1) + t;
*zbuf1++ = z1;
*zbuf1++ = z2;
ar2 = *(zbuf2 - 1) >> es; /* do here to free up register used for es */
t = MULSHIFT32(sin2b, ar2 + ai2);
z2 = MULSHIFT32(cps2b, ai2) - t;
cms2 = cps2b - 2*sin2b;
z1 = MULSHIFT32(cms2, ar2) + t;
*zbuf2-- = z2;
*zbuf2-- = z1;
}
}
/**************************************************************************************
* Function: PostMultiplyRescale
*
* Description: post-twiddle stage of DCT4, with rescaling for extra guard bits
*
* Inputs: table index (for transform size)
* buffer of nmdct samples
* number of guard bits to remove from output
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: clips output to [-2^30, 2^30 - 1], guaranteeing at least 1 guard bit
* see notes on PostMultiply(), above
**************************************************************************************/
static void PostMultiplyRescale(int tabidx, int *fft1, int es)
{
int i, nmdct, ar1, ai1, ar2, ai2, skipFactor, z;
int t, cs2, sin2;
int *fft2;
const int *csptr;
nmdct = nmdctTab[tabidx];
csptr = cos1sin1tab;
skipFactor = postSkip[tabidx];
fft2 = fft1 + nmdct - 1;
/* load coeffs for first pass
* cps2 = (cos+sin), sin2 = sin, cms2 = (cos-sin)
*/
cs2 = *csptr++;
sin2 = *csptr;
csptr += skipFactor;
for (i = nmdct >> 2; i != 0; i--) {
ar1 = *(fft1 + 0);
ai1 = *(fft1 + 1);
ai2 = *(fft2 + 0);
t = MULSHIFT32(sin2, ar1 + ai1);
z = t - MULSHIFT32(cs2, ai1);
CLIP_2N_SHIFT(z, es);
*fft2-- = z;
cs2 -= 2*sin2;
z = t + MULSHIFT32(cs2, ar1);
CLIP_2N_SHIFT(z, es);
*fft1++ = z;
cs2 = *csptr++;
sin2 = *csptr;
csptr += skipFactor;
ar2 = *fft2;
ai2 = -ai2;
t = MULSHIFT32(sin2, ar2 + ai2);
z = t - MULSHIFT32(cs2, ai2);
CLIP_2N_SHIFT(z, es);
*fft2-- = z;
cs2 -= 2*sin2;
z = t + MULSHIFT32(cs2, ar2);
CLIP_2N_SHIFT(z, es);
*fft1++ = z;
cs2 += 2*sin2;
}
}
/**************************************************************************************
* Function: DCT4
*
* Description: type-IV DCT
*
* Inputs: table index (for transform size)
* buffer of nmdct samples
* number of guard bits in the input buffer
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: operates in-place
* if number of guard bits in input is < GBITS_IN_DCT4, the input is
* scaled (>>) before the DCT4 and rescaled (<<, with clipping) after
* the DCT4 (rare)
* the output has FBITS_LOST_DCT4 fewer fraction bits than the input
* the output will always have at least 1 guard bit (GBITS_IN_DCT4 >= 4)
* int bits gained per stage (PreMul + FFT + PostMul)
* short blocks = (-5 + 4 + 2) = 1 total
* long blocks = (-8 + 7 + 2) = 1 total
**************************************************************************************/
void DCT4(int tabidx, int *coef, int gb)
{
int es;
/* fast in-place DCT-IV - adds guard bits if necessary */
if (gb < GBITS_IN_DCT4) {
es = GBITS_IN_DCT4 - gb;
PreMultiplyRescale(tabidx, coef, es);
R4FFT(tabidx, coef);
PostMultiplyRescale(tabidx, coef, es);
} else {
PreMultiply(tabidx, coef);
R4FFT(tabidx, coef);
PostMultiply(tabidx, coef);
}
}
|
1137519-player
|
aac/dct4.c
|
C
|
lgpl
| 10,855
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: huffman.c,v 1.2 2005/05/24 16:01:55 albertofloyd Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* huffman.c - Huffman decoding
**************************************************************************************/
#include "coder.h"
/**************************************************************************************
* Function: DecodeHuffmanScalar
*
* Description: decode one Huffman symbol from bitstream
*
* Inputs: pointers to Huffman table and info struct
* left-aligned bit buffer with >= huffTabInfo->maxBits bits
*
* Outputs: decoded symbol in *val
*
* Return: number of bits in symbol
*
* Notes: assumes canonical Huffman codes:
* first CW always 0, we have "count" CW's of length "nBits" bits
* starting CW for codes of length nBits+1 =
* (startCW[nBits] + count[nBits]) << 1
* if there are no codes at nBits, then we just keep << 1 each time
* (since count[nBits] = 0)
**************************************************************************************/
int DecodeHuffmanScalar(const signed short *huffTab, const HuffInfo *huffTabInfo, unsigned int bitBuf, signed int *val)
{
unsigned int count, start, shift, t;
const unsigned char *countPtr;
const signed short *map;
map = huffTab + huffTabInfo->offset;
countPtr = huffTabInfo->count;
start = 0;
count = 0;
shift = 32;
do {
start += count;
start <<= 1;
map += count;
count = *countPtr++;
shift--;
t = (bitBuf >> shift) - start;
} while (t >= count);
*val = (signed int)map[t];
return (countPtr - huffTabInfo->count);
}
#define APPLY_SIGN(v, s) {(v) ^= ((signed int)(s) >> 31); (v) -= ((signed int)(s) >> 31);}
#define GET_QUAD_SIGNBITS(v) (((unsigned int)(v) << 17) >> 29) /* bits 14-12, unsigned */
#define GET_QUAD_W(v) (((signed int)(v) << 20) >> 29) /* bits 11-9, sign-extend */
#define GET_QUAD_X(v) (((signed int)(v) << 23) >> 29) /* bits 8-6, sign-extend */
#define GET_QUAD_Y(v) (((signed int)(v) << 26) >> 29) /* bits 5-3, sign-extend */
#define GET_QUAD_Z(v) (((signed int)(v) << 29) >> 29) /* bits 2-0, sign-extend */
#define GET_PAIR_SIGNBITS(v) (((unsigned int)(v) << 20) >> 30) /* bits 11-10, unsigned */
#define GET_PAIR_Y(v) (((signed int)(v) << 22) >> 27) /* bits 9-5, sign-extend */
#define GET_PAIR_Z(v) (((signed int)(v) << 27) >> 27) /* bits 4-0, sign-extend */
#define GET_ESC_SIGNBITS(v) (((unsigned int)(v) << 18) >> 30) /* bits 13-12, unsigned */
#define GET_ESC_Y(v) (((signed int)(v) << 20) >> 26) /* bits 11-6, sign-extend */
#define GET_ESC_Z(v) (((signed int)(v) << 26) >> 26) /* bits 5-0, sign-extend */
/**************************************************************************************
* Function: UnpackZeros
*
* Description: fill a section of coefficients with zeros
*
* Inputs: number of coefficients
*
* Outputs: nVals zeros, starting at coef
*
* Return: none
*
* Notes: assumes nVals is always a multiple of 4 because all scalefactor bands
* are a multiple of 4 coefficients long
**************************************************************************************/
static void UnpackZeros(int nVals, int *coef)
{
while (nVals > 0) {
*coef++ = 0;
*coef++ = 0;
*coef++ = 0;
*coef++ = 0;
nVals -= 4;
}
}
/**************************************************************************************
* Function: UnpackQuads
*
* Description: decode a section of 4-way vector Huffman coded coefficients
*
* Inputs BitStreamInfo struct pointing to start of codewords for this section
* index of Huffman codebook
* number of coefficients
*
* Outputs: nVals coefficients, starting at coef
*
* Return: none
*
* Notes: assumes nVals is always a multiple of 4 because all scalefactor bands
* are a multiple of 4 coefficients long
**************************************************************************************/
static void UnpackQuads(BitStreamInfo *bsi, int cb, int nVals, int *coef)
{
int w, x, y, z, maxBits, nCodeBits, nSignBits, val;
unsigned int bitBuf;
maxBits = huffTabSpecInfo[cb - HUFFTAB_SPEC_OFFSET].maxBits + 4;
while (nVals > 0) {
/* decode quad */
bitBuf = GetBitsNoAdvance(bsi, maxBits) << (32 - maxBits);
nCodeBits = DecodeHuffmanScalar(huffTabSpec, &huffTabSpecInfo[cb - HUFFTAB_SPEC_OFFSET], bitBuf, &val);
w = GET_QUAD_W(val);
x = GET_QUAD_X(val);
y = GET_QUAD_Y(val);
z = GET_QUAD_Z(val);
bitBuf <<= nCodeBits;
nSignBits = (int)GET_QUAD_SIGNBITS(val);
AdvanceBitstream(bsi, nCodeBits + nSignBits);
if (nSignBits) {
if (w) {APPLY_SIGN(w, bitBuf); bitBuf <<= 1;}
if (x) {APPLY_SIGN(x, bitBuf); bitBuf <<= 1;}
if (y) {APPLY_SIGN(y, bitBuf); bitBuf <<= 1;}
if (z) {APPLY_SIGN(z, bitBuf); bitBuf <<= 1;}
}
*coef++ = w; *coef++ = x; *coef++ = y; *coef++ = z;
nVals -= 4;
}
}
/**************************************************************************************
* Function: UnpackPairsNoEsc
*
* Description: decode a section of 2-way vector Huffman coded coefficients,
* using non-esc tables (5 through 10)
*
* Inputs BitStreamInfo struct pointing to start of codewords for this section
* index of Huffman codebook (must not be the escape codebook)
* number of coefficients
*
* Outputs: nVals coefficients, starting at coef
*
* Return: none
*
* Notes: assumes nVals is always a multiple of 2 because all scalefactor bands
* are a multiple of 4 coefficients long
**************************************************************************************/
static void UnpackPairsNoEsc(BitStreamInfo *bsi, int cb, int nVals, int *coef)
{
int y, z, maxBits, nCodeBits, nSignBits, val;
unsigned int bitBuf;
maxBits = huffTabSpecInfo[cb - HUFFTAB_SPEC_OFFSET].maxBits + 2;
while (nVals > 0) {
/* decode pair */
bitBuf = GetBitsNoAdvance(bsi, maxBits) << (32 - maxBits);
nCodeBits = DecodeHuffmanScalar(huffTabSpec, &huffTabSpecInfo[cb-HUFFTAB_SPEC_OFFSET], bitBuf, &val);
y = GET_PAIR_Y(val);
z = GET_PAIR_Z(val);
bitBuf <<= nCodeBits;
nSignBits = GET_PAIR_SIGNBITS(val);
AdvanceBitstream(bsi, nCodeBits + nSignBits);
if (nSignBits) {
if (y) {APPLY_SIGN(y, bitBuf); bitBuf <<= 1;}
if (z) {APPLY_SIGN(z, bitBuf); bitBuf <<= 1;}
}
*coef++ = y; *coef++ = z;
nVals -= 2;
}
}
/**************************************************************************************
* Function: UnpackPairsEsc
*
* Description: decode a section of 2-way vector Huffman coded coefficients,
* using esc table (11)
*
* Inputs BitStreamInfo struct pointing to start of codewords for this section
* index of Huffman codebook (must be the escape codebook)
* number of coefficients
*
* Outputs: nVals coefficients, starting at coef
*
* Return: none
*
* Notes: assumes nVals is always a multiple of 2 because all scalefactor bands
* are a multiple of 4 coefficients long
**************************************************************************************/
static void UnpackPairsEsc(BitStreamInfo *bsi, int cb, int nVals, int *coef)
{
int y, z, maxBits, nCodeBits, nSignBits, n, val;
unsigned int bitBuf;
maxBits = huffTabSpecInfo[cb - HUFFTAB_SPEC_OFFSET].maxBits + 2;
while (nVals > 0) {
/* decode pair with escape value */
bitBuf = GetBitsNoAdvance(bsi, maxBits) << (32 - maxBits);
nCodeBits = DecodeHuffmanScalar(huffTabSpec, &huffTabSpecInfo[cb-HUFFTAB_SPEC_OFFSET], bitBuf, &val);
y = GET_ESC_Y(val);
z = GET_ESC_Z(val);
bitBuf <<= nCodeBits;
nSignBits = GET_ESC_SIGNBITS(val);
AdvanceBitstream(bsi, nCodeBits + nSignBits);
if (y == 16) {
n = 4;
while (GetBits(bsi, 1) == 1)
n++;
y = (1 << n) + GetBits(bsi, n);
}
if (z == 16) {
n = 4;
while (GetBits(bsi, 1) == 1)
n++;
z = (1 << n) + GetBits(bsi, n);
}
if (nSignBits) {
if (y) {APPLY_SIGN(y, bitBuf); bitBuf <<= 1;}
if (z) {APPLY_SIGN(z, bitBuf); bitBuf <<= 1;}
}
*coef++ = y; *coef++ = z;
nVals -= 2;
}
}
/**************************************************************************************
* Function: DecodeSpectrumLong
*
* Description: decode transform coefficients for frame with one long block
*
* Inputs: platform specific info struct
* BitStreamInfo struct pointing to start of spectral data
* (14496-3, table 4.4.29)
* index of current channel
*
* Outputs: decoded, quantized coefficients for this channel
*
* Return: none
*
* Notes: adds in pulse data if present
* fills coefficient buffer with zeros in any region not coded with
* codebook in range [1, 11] (including sfb's above sfbMax)
**************************************************************************************/
void DecodeSpectrumLong(PSInfoBase *psi, BitStreamInfo *bsi, int ch)
{
int i, sfb, cb, nVals, offset;
const short *sfbTab;
unsigned char *sfbCodeBook;
int *coef;
ICSInfo *icsInfo;
PulseInfo *pi;
coef = psi->coef[ch];
icsInfo = (ch == 1 && psi->commonWin == 1) ? &(psi->icsInfo[0]) : &(psi->icsInfo[ch]);
/* decode long block */
sfbTab = sfBandTabLong + sfBandTabLongOffset[psi->sampRateIdx];
sfbCodeBook = psi->sfbCodeBook[ch];
for (sfb = 0; sfb < icsInfo->maxSFB; sfb++) {
cb = *sfbCodeBook++;
nVals = sfbTab[sfb+1] - sfbTab[sfb];
if (cb == 0)
UnpackZeros(nVals, coef);
else if (cb <= 4)
UnpackQuads(bsi, cb, nVals, coef);
else if (cb <= 10)
UnpackPairsNoEsc(bsi, cb, nVals, coef);
else if (cb == 11)
UnpackPairsEsc(bsi, cb, nVals, coef);
else
UnpackZeros(nVals, coef);
coef += nVals;
}
/* fill with zeros above maxSFB */
nVals = NSAMPS_LONG - sfbTab[sfb];
UnpackZeros(nVals, coef);
/* add pulse data, if present */
pi = &psi->pulseInfo[ch];
if (pi->pulseDataPresent) {
coef = psi->coef[ch];
offset = sfbTab[pi->startSFB];
for (i = 0; i < pi->numPulse; i++) {
offset += pi->offset[i];
if (coef[offset] > 0)
coef[offset] += pi->amp[i];
else
coef[offset] -= pi->amp[i];
}
ASSERT(offset < NSAMPS_LONG);
}
}
/**************************************************************************************
* Function: DecodeSpectrumShort
*
* Description: decode transform coefficients for frame with eight short blocks
*
* Inputs: platform specific info struct
* BitStreamInfo struct pointing to start of spectral data
* (14496-3, table 4.4.29)
* index of current channel
*
* Outputs: decoded, quantized coefficients for this channel
*
* Return: none
*
* Notes: fills coefficient buffer with zeros in any region not coded with
* codebook in range [1, 11] (including sfb's above sfbMax)
* deinterleaves window groups into 8 windows
**************************************************************************************/
void DecodeSpectrumShort(PSInfoBase *psi, BitStreamInfo *bsi, int ch)
{
int gp, cb, nVals=0, win, offset, sfb;
const short *sfbTab;
unsigned char *sfbCodeBook;
int *coef;
ICSInfo *icsInfo;
coef = psi->coef[ch];
icsInfo = (ch == 1 && psi->commonWin == 1) ? &(psi->icsInfo[0]) : &(psi->icsInfo[ch]);
/* decode short blocks, deinterleaving in-place */
sfbTab = sfBandTabShort + sfBandTabShortOffset[psi->sampRateIdx];
sfbCodeBook = psi->sfbCodeBook[ch];
for (gp = 0; gp < icsInfo->numWinGroup; gp++) {
for (sfb = 0; sfb < icsInfo->maxSFB; sfb++) {
nVals = sfbTab[sfb+1] - sfbTab[sfb];
cb = *sfbCodeBook++;
for (win = 0; win < icsInfo->winGroupLen[gp]; win++) {
offset = win*NSAMPS_SHORT;
if (cb == 0)
UnpackZeros(nVals, coef + offset);
else if (cb <= 4)
UnpackQuads(bsi, cb, nVals, coef + offset);
else if (cb <= 10)
UnpackPairsNoEsc(bsi, cb, nVals, coef + offset);
else if (cb == 11)
UnpackPairsEsc(bsi, cb, nVals, coef + offset);
else
UnpackZeros(nVals, coef + offset);
}
coef += nVals;
}
/* fill with zeros above maxSFB */
for (win = 0; win < icsInfo->winGroupLen[gp]; win++) {
offset = win*NSAMPS_SHORT;
nVals = NSAMPS_SHORT - sfbTab[sfb];
UnpackZeros(nVals, coef + offset);
}
coef += nVals;
coef += (icsInfo->winGroupLen[gp] - 1)*NSAMPS_SHORT;
}
ASSERT(coef == psi->coef[ch] + NSAMPS_LONG);
}
|
1137519-player
|
aac/huffman.c
|
C
|
lgpl
| 14,394
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: assembly.h,v 1.9 2007/02/28 07:10:21 gahluwalia Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* assembly.h - inline assembly language functions and prototypes
*
* MULSHIFT32(x, y) signed multiply of two 32-bit integers (x and y),
* returns top 32-bits of 64-bit result
* CLIPTOSHORT(x) convert 32-bit integer to 16-bit short,
* clipping to [-32768, 32767]
* FASTABS(x) branchless absolute value of signed integer x
* CLZ(x) count leading zeros on signed integer x
* MADD64(sum64, x, y) 64-bit multiply accumulate: sum64 += (x*y)
**************************************************************************************/
#ifndef _ASSEMBLY_H
#define _ASSEMBLY_H
/* toolchain: MSFT Visual C++
* target architecture: x86
*/
#if (defined (_WIN32) && !defined (_WIN32_WCE)) || (defined (__WINS__) && defined (_SYMBIAN)) || (defined (WINCE_EMULATOR)) || (defined (_OPENWAVE_SIMULATOR))
#pragma warning( disable : 4035 ) /* complains about inline asm not returning a value */
static __inline int MULSHIFT32(int x, int y)
{
__asm {
mov eax, x
imul y
mov eax, edx
}
}
static __inline short CLIPTOSHORT(int x)
{
int sign;
/* clip to [-32768, 32767] */
sign = x >> 31;
if (sign != (x >> 15))
x = sign ^ ((1 << 15) - 1);
return (short)x;
}
static __inline int FASTABS(int x)
{
int sign;
sign = x >> (sizeof(int) * 8 - 1);
x ^= sign;
x -= sign;
return x;
}
static __inline int CLZ(int x)
{
int numZeros;
if (!x)
return 32;
/* count leading zeros with binary search */
numZeros = 1;
if (!((unsigned int)x >> 16)) { numZeros += 16; x <<= 16; }
if (!((unsigned int)x >> 24)) { numZeros += 8; x <<= 8; }
if (!((unsigned int)x >> 28)) { numZeros += 4; x <<= 4; }
if (!((unsigned int)x >> 30)) { numZeros += 2; x <<= 2; }
numZeros -= ((unsigned int)x >> 31);
return numZeros;
}
#ifdef __CW32__
typedef long long Word64;
#else
typedef __int64 Word64;
#endif
typedef union _U64 {
Word64 w64;
struct {
/* x86 = little endian */
unsigned int lo32;
signed int hi32;
} r;
} U64;
/* returns 64-bit value in [edx:eax] */
static __inline Word64 MADD64(Word64 sum64, int x, int y)
{
#if (defined (_SYMBIAN_61_) || defined (_SYMBIAN_70_)) && defined (__WINS__) && !defined (__CW32__)
/* Workaround for the Symbian emulator because of non existing longlong.lib and
* hence __allmul not defined. */
__asm {
mov eax, x
imul y
add dword ptr sum64, eax
adc dword ptr sum64 + 4, edx
}
#else
sum64 += (Word64)x * (Word64)y;
#endif
return sum64;
}
/* toolchain: MSFT Embedded Visual C++
* target architecture: ARM v.4 and above (require 'M' type processor for 32x32->64 multiplier)
*/
#elif defined (_WIN32) && defined (_WIN32_WCE) && defined (ARM)
static __inline short CLIPTOSHORT(int x)
{
int sign;
/* clip to [-32768, 32767] */
sign = x >> 31;
if (sign != (x >> 15))
x = sign ^ ((1 << 15) - 1);
return (short)x;
}
static __inline int FASTABS(int x)
{
int sign;
sign = x >> (sizeof(int) * 8 - 1);
x ^= sign;
x -= sign;
return x;
}
static __inline int CLZ(int x)
{
int numZeros;
if (!x)
return 32;
/* count leading zeros with binary search (function should be 17 ARM instructions total) */
numZeros = 1;
if (!((unsigned int)x >> 16)) { numZeros += 16; x <<= 16; }
if (!((unsigned int)x >> 24)) { numZeros += 8; x <<= 8; }
if (!((unsigned int)x >> 28)) { numZeros += 4; x <<= 4; }
if (!((unsigned int)x >> 30)) { numZeros += 2; x <<= 2; }
numZeros -= ((unsigned int)x >> 31);
return numZeros;
}
/* implemented in asmfunc.s */
#ifdef __cplusplus
extern "C" {
#endif
typedef __int64 Word64;
typedef union _U64 {
Word64 w64;
struct {
/* ARM WinCE = little endian */
unsigned int lo32;
signed int hi32;
} r;
} U64;
/* manual name mangling for just this platform (must match labels in .s file) */
#define MULSHIFT32 raac_MULSHIFT32
#define MADD64 raac_MADD64
int MULSHIFT32(int x, int y);
Word64 MADD64(Word64 sum64, int x, int y);
#ifdef __cplusplus
}
#endif
/* toolchain: ARM ADS or RealView
* target architecture: ARM v.4 and above (requires 'M' type processor for 32x32->64 multiplier)
*/
#elif (defined (__arm) && defined (__ARMCC_VERSION)) || (defined(HELIX_CONFIG_SYMBIAN_GENERATE_MMP) && !defined(__GCCE__))
static __inline int MULSHIFT32(int x, int y)
{
/* rules for smull RdLo, RdHi, Rm, Rs:
* RdHi != Rm
* RdLo != Rm
* RdHi != RdLo
*/
int zlow;
__asm {
smull zlow,y,x,y
}
return y;
}
static __inline short CLIPTOSHORT(int x)
{
int sign;
/* clip to [-32768, 32767] */
sign = x >> 31;
if (sign != (x >> 15))
x = sign ^ ((1 << 15) - 1);
return (short)x;
}
static __inline int FASTABS(int x)
{
int sign;
sign = x >> (sizeof(int) * 8 - 1);
x ^= sign;
x -= sign;
return x;
}
static __inline int CLZ(int x)
{
int numZeros;
if (!x)
return 32;
/* count leading zeros with binary search (function should be 17 ARM instructions total) */
numZeros = 1;
if (!((unsigned int)x >> 16)) { numZeros += 16; x <<= 16; }
if (!((unsigned int)x >> 24)) { numZeros += 8; x <<= 8; }
if (!((unsigned int)x >> 28)) { numZeros += 4; x <<= 4; }
if (!((unsigned int)x >> 30)) { numZeros += 2; x <<= 2; }
numZeros -= ((unsigned int)x >> 31);
return numZeros;
/* ARM code would look like this, but do NOT use inline asm in ADS for this,
because you can't safely use the status register flags intermixed with C code
__asm {
mov numZeros, #1
tst x, 0xffff0000
addeq numZeros, numZeros, #16
moveq x, x, lsl #16
tst x, 0xff000000
addeq numZeros, numZeros, #8
moveq x, x, lsl #8
tst x, 0xf0000000
addeq numZeros, numZeros, #4
moveq x, x, lsl #4
tst x, 0xc0000000
addeq numZeros, numZeros, #2
moveq x, x, lsl #2
sub numZeros, numZeros, x, lsr #31
}
*/
/* reference:
numZeros = 0;
while (!(x & 0x80000000)) {
numZeros++;
x <<= 1;
}
*/
}
typedef __int64 Word64;
typedef union _U64 {
Word64 w64;
struct {
/* ARM ADS = little endian */
unsigned int lo32;
signed int hi32;
} r;
} U64;
static __inline Word64 MADD64(Word64 sum64, int x, int y)
{
U64 u;
u.w64 = sum64;
__asm {
smlal u.r.lo32, u.r.hi32, x, y
}
return u.w64;
}
/* toolchain: ARM gcc
* target architecture: ARM v.4 and above (requires 'M' type processor for 32x32->64 multiplier)
*/
#elif defined(__GNUC__) && defined(__arm__)
static __inline__ int MULSHIFT32(int x, int y)
{
int zlow;
__asm__ volatile ("smull %0,%1,%2,%3" : "=&r" (zlow), "=r" (y) : "r" (x), "1" (y) : "cc");
return y;
}
static __inline short CLIPTOSHORT(int x)
{
int sign;
/* clip to [-32768, 32767] */
sign = x >> 31;
if (sign != (x >> 15))
x = sign ^ ((1 << 15) - 1);
return (short)x;
}
static __inline int FASTABS(int x)
{
int sign;
sign = x >> (sizeof(int) * 8 - 1);
x ^= sign;
x -= sign;
return x;
}
static __inline int CLZ(int x)
{
int numZeros;
if (!x)
return (sizeof(int) * 8);
numZeros = 0;
while (!(x & 0x80000000)) {
numZeros++;
x <<= 1;
}
return numZeros;
}
typedef long long Word64;
typedef union _U64 {
Word64 w64;
struct {
/* ARM ADS = little endian */
unsigned int lo32;
signed int hi32;
} r;
} U64;
static __inline Word64 MADD64(Word64 sum64, int x, int y)
{
U64 u;
u.w64 = sum64;
__asm__ volatile ("smlal %0,%1,%2,%3" : "+&r" (u.r.lo32), "+&r" (u.r.hi32) : "r" (x), "r" (y) : "cc");
return u.w64;
}
/* toolchain: x86 gcc
* target architecture: x86
*/
#elif defined(__GNUC__) && (defined(__i386__) || defined(__amd64__)) || (defined (_SOLARIS) && !defined (__GNUC__) && defined(_SOLARISX86))
typedef long long Word64;
static __inline__ int MULSHIFT32(int x, int y)
{
int z;
z = (Word64)x * (Word64)y >> 32;
return z;
}
static __inline short CLIPTOSHORT(int x)
{
int sign;
/* clip to [-32768, 32767] */
sign = x >> 31;
if (sign != (x >> 15))
x = sign ^ ((1 << 15) - 1);
return (short)x;
}
static __inline int FASTABS(int x)
{
int sign;
sign = x >> (sizeof(int) * 8 - 1);
x ^= sign;
x -= sign;
return x;
}
static __inline int CLZ(int x)
{
int numZeros;
if (!x)
return 32;
/* count leading zeros with binary search (function should be 17 ARM instructions total) */
numZeros = 1;
if (!((unsigned int)x >> 16)) { numZeros += 16; x <<= 16; }
if (!((unsigned int)x >> 24)) { numZeros += 8; x <<= 8; }
if (!((unsigned int)x >> 28)) { numZeros += 4; x <<= 4; }
if (!((unsigned int)x >> 30)) { numZeros += 2; x <<= 2; }
numZeros -= ((unsigned int)x >> 31);
return numZeros;
}
typedef union _U64 {
Word64 w64;
struct {
/* x86 = little endian */
unsigned int lo32;
signed int hi32;
} r;
} U64;
static __inline Word64 MADD64(Word64 sum64, int x, int y)
{
sum64 += (Word64)x * (Word64)y;
return sum64;
}
#elif defined(__GNUC__) && (defined(__powerpc__) || defined(__POWERPC__)) || (defined (_SOLARIS) && !defined (__GNUC__) && !defined (_SOLARISX86))
typedef long long Word64;
static __inline__ int MULSHIFT32(int x, int y)
{
int z;
z = (Word64)x * (Word64)y >> 32;
return z;
}
static __inline short CLIPTOSHORT(int x)
{
int sign;
/* clip to [-32768, 32767] */
sign = x >> 31;
if (sign != (x >> 15))
x = sign ^ ((1 << 15) - 1);
return (short)x;
}
static __inline int FASTABS(int x)
{
int sign;
sign = x >> (sizeof(int) * 8 - 1);
x ^= sign;
x -= sign;
return x;
}
static __inline int CLZ(int x)
{
int numZeros;
if (!x)
return 32;
/* count leading zeros with binary search (function should be 17 ARM instructions total) */
numZeros = 1;
if (!((unsigned int)x >> 16)) { numZeros += 16; x <<= 16; }
if (!((unsigned int)x >> 24)) { numZeros += 8; x <<= 8; }
if (!((unsigned int)x >> 28)) { numZeros += 4; x <<= 4; }
if (!((unsigned int)x >> 30)) { numZeros += 2; x <<= 2; }
numZeros -= ((unsigned int)x >> 31);
return numZeros;
}
typedef union _U64 {
Word64 w64;
struct {
/* PowerPC = big endian */
signed int hi32;
unsigned int lo32;
} r;
} U64;
static __inline Word64 MADD64(Word64 sum64, int x, int y)
{
sum64 += (Word64)x * (Word64)y;
return sum64;
}
#else
#error Unsupported platform in assembly.h
#endif /* platforms */
#endif /* _ASSEMBLY_H */
|
1137519-player
|
aac/assembly.h
|
C
|
lgpl
| 14,155
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: decelmnt.c,v 1.1 2005/02/26 01:47:34 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* decelmnt.c - syntactic element decoding
**************************************************************************************/
#include "coder.h"
/**************************************************************************************
* Function: DecodeSingleChannelElement
*
* Description: decode one SCE
*
* Inputs: BitStreamInfo struct pointing to start of SCE (14496-3, table 4.4.4)
*
* Outputs: updated element instance tag
*
* Return: 0 if successful, -1 if error
*
* Notes: doesn't decode individual channel stream (part of DecodeNoiselessData)
**************************************************************************************/
static int DecodeSingleChannelElement(AACDecInfo *aacDecInfo, BitStreamInfo *bsi)
{
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return -1;
/* read instance tag */
aacDecInfo->currInstTag = GetBits(bsi, NUM_INST_TAG_BITS);
return 0;
}
/**************************************************************************************
* Function: DecodeChannelPairElement
*
* Description: decode one CPE
*
* Inputs: BitStreamInfo struct pointing to start of CPE (14496-3, table 4.4.5)
*
* Outputs: updated element instance tag
* updated commonWin
* updated ICS info, if commonWin == 1
* updated mid-side stereo info, if commonWin == 1
*
* Return: 0 if successful, -1 if error
*
* Notes: doesn't decode individual channel stream (part of DecodeNoiselessData)
**************************************************************************************/
static int DecodeChannelPairElement(AACDecInfo *aacDecInfo, BitStreamInfo *bsi)
{
int sfb, gp, maskOffset;
unsigned char currBit, *maskPtr;
PSInfoBase *psi;
ICSInfo *icsInfo;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return -1;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
icsInfo = psi->icsInfo;
/* read instance tag */
aacDecInfo->currInstTag = GetBits(bsi, NUM_INST_TAG_BITS);
/* read common window flag and mid-side info (if present)
* store msMask bits in psi->msMaskBits[] as follows:
* long blocks - pack bits for each SFB in range [0, maxSFB) starting with lsb of msMaskBits[0]
* short blocks - pack bits for each SFB in range [0, maxSFB), for each group [0, 7]
* msMaskPresent = 0 means no M/S coding
* = 1 means psi->msMaskBits contains 1 bit per SFB to toggle M/S coding
* = 2 means all SFB's are M/S coded (so psi->msMaskBits is not needed)
*/
psi->commonWin = GetBits(bsi, 1);
if (psi->commonWin) {
DecodeICSInfo(bsi, icsInfo, psi->sampRateIdx);
psi->msMaskPresent = GetBits(bsi, 2);
if (psi->msMaskPresent == 1) {
maskPtr = psi->msMaskBits;
*maskPtr = 0;
maskOffset = 0;
for (gp = 0; gp < icsInfo->numWinGroup; gp++) {
for (sfb = 0; sfb < icsInfo->maxSFB; sfb++) {
currBit = (unsigned char)GetBits(bsi, 1);
*maskPtr |= currBit << maskOffset;
if (++maskOffset == 8) {
maskPtr++;
*maskPtr = 0;
maskOffset = 0;
}
}
}
}
}
return 0;
}
/**************************************************************************************
* Function: DecodeLFEChannelElement
*
* Description: decode one LFE
*
* Inputs: BitStreamInfo struct pointing to start of LFE (14496-3, table 4.4.9)
*
* Outputs: updated element instance tag
*
* Return: 0 if successful, -1 if error
*
* Notes: doesn't decode individual channel stream (part of DecodeNoiselessData)
**************************************************************************************/
static int DecodeLFEChannelElement(AACDecInfo *aacDecInfo, BitStreamInfo *bsi)
{
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return -1;
/* read instance tag */
aacDecInfo->currInstTag = GetBits(bsi, NUM_INST_TAG_BITS);
return 0;
}
/**************************************************************************************
* Function: DecodeDataStreamElement
*
* Description: decode one DSE
*
* Inputs: BitStreamInfo struct pointing to start of DSE (14496-3, table 4.4.10)
*
* Outputs: updated element instance tag
* filled in data stream buffer
*
* Return: 0 if successful, -1 if error
**************************************************************************************/
static int DecodeDataStreamElement(AACDecInfo *aacDecInfo, BitStreamInfo *bsi)
{
unsigned int byteAlign, dataCount;
unsigned char *dataBuf;
PSInfoBase *psi;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return -1;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
aacDecInfo->currInstTag = GetBits(bsi, NUM_INST_TAG_BITS);
byteAlign = GetBits(bsi, 1);
dataCount = GetBits(bsi, 8);
if (dataCount == 255)
dataCount += GetBits(bsi, 8);
if (byteAlign)
ByteAlignBitstream(bsi);
psi->dataCount = dataCount;
dataBuf = psi->dataBuf;
while (dataCount--)
*dataBuf++ = GetBits(bsi, 8);
return 0;
}
/**************************************************************************************
* Function: DecodeProgramConfigElement
*
* Description: decode one PCE
*
* Inputs: BitStreamInfo struct pointing to start of PCE (14496-3, table 4.4.2)
*
* Outputs: filled-in ProgConfigElement struct
* updated BitStreamInfo struct
*
* Return: 0 if successful, error code (< 0) if error
*
* Notes: #define KEEP_PCE_COMMENTS to save the comment field of the PCE
* (otherwise we just skip it in the bitstream, to save memory)
**************************************************************************************/
int DecodeProgramConfigElement(ProgConfigElement *pce, BitStreamInfo *bsi)
{
int i;
pce->elemInstTag = GetBits(bsi, 4);
pce->profile = GetBits(bsi, 2);
pce->sampRateIdx = GetBits(bsi, 4);
pce->numFCE = GetBits(bsi, 4);
pce->numSCE = GetBits(bsi, 4);
pce->numBCE = GetBits(bsi, 4);
pce->numLCE = GetBits(bsi, 2);
pce->numADE = GetBits(bsi, 3);
pce->numCCE = GetBits(bsi, 4);
pce->monoMixdown = GetBits(bsi, 1) << 4; /* present flag */
if (pce->monoMixdown)
pce->monoMixdown |= GetBits(bsi, 4); /* element number */
pce->stereoMixdown = GetBits(bsi, 1) << 4; /* present flag */
if (pce->stereoMixdown)
pce->stereoMixdown |= GetBits(bsi, 4); /* element number */
pce->matrixMixdown = GetBits(bsi, 1) << 4; /* present flag */
if (pce->matrixMixdown) {
pce->matrixMixdown |= GetBits(bsi, 2) << 1; /* index */
pce->matrixMixdown |= GetBits(bsi, 1); /* pseudo-surround enable */
}
for (i = 0; i < pce->numFCE; i++) {
pce->fce[i] = GetBits(bsi, 1) << 4; /* is_cpe flag */
pce->fce[i] |= GetBits(bsi, 4); /* tag select */
}
for (i = 0; i < pce->numSCE; i++) {
pce->sce[i] = GetBits(bsi, 1) << 4; /* is_cpe flag */
pce->sce[i] |= GetBits(bsi, 4); /* tag select */
}
for (i = 0; i < pce->numBCE; i++) {
pce->bce[i] = GetBits(bsi, 1) << 4; /* is_cpe flag */
pce->bce[i] |= GetBits(bsi, 4); /* tag select */
}
for (i = 0; i < pce->numLCE; i++)
pce->lce[i] = GetBits(bsi, 4); /* tag select */
for (i = 0; i < pce->numADE; i++)
pce->ade[i] = GetBits(bsi, 4); /* tag select */
for (i = 0; i < pce->numCCE; i++) {
pce->cce[i] = GetBits(bsi, 1) << 4; /* independent/dependent flag */
pce->cce[i] |= GetBits(bsi, 4); /* tag select */
}
ByteAlignBitstream(bsi);
#ifdef KEEP_PCE_COMMENTS
pce->commentBytes = GetBits(bsi, 8);
for (i = 0; i < pce->commentBytes; i++)
pce->commentField[i] = GetBits(bsi, 8);
#else
/* eat comment bytes and throw away */
i = GetBits(bsi, 8);
while (i--)
GetBits(bsi, 8);
#endif
return 0;
}
/**************************************************************************************
* Function: DecodeFillElement
*
* Description: decode one fill element
*
* Inputs: BitStreamInfo struct pointing to start of fill element
* (14496-3, table 4.4.11)
*
* Outputs: updated element instance tag
* unpacked extension payload
*
* Return: 0 if successful, -1 if error
**************************************************************************************/
static int DecodeFillElement(AACDecInfo *aacDecInfo, BitStreamInfo *bsi)
{
unsigned int fillCount;
unsigned char *fillBuf;
PSInfoBase *psi;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return -1;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
fillCount = GetBits(bsi, 4);
if (fillCount == 15)
fillCount += (GetBits(bsi, 8) - 1);
psi->fillCount = fillCount;
fillBuf = psi->fillBuf;
while (fillCount--)
*fillBuf++ = GetBits(bsi, 8);
aacDecInfo->currInstTag = -1; /* fill elements don't have instance tag */
aacDecInfo->fillExtType = 0;
#ifdef AAC_ENABLE_SBR
/* check for SBR
* aacDecInfo->sbrEnabled is sticky (reset each raw_data_block), so for multichannel
* need to verify that all SCE/CPE/ICCE have valid SBR fill element following, and
* must upsample by 2 for LFE
*/
if (psi->fillCount > 0) {
aacDecInfo->fillExtType = (int)((psi->fillBuf[0] >> 4) & 0x0f);
if (aacDecInfo->fillExtType == EXT_SBR_DATA || aacDecInfo->fillExtType == EXT_SBR_DATA_CRC)
aacDecInfo->sbrEnabled = 1;
}
#endif
aacDecInfo->fillBuf = psi->fillBuf;
aacDecInfo->fillCount = psi->fillCount;
return 0;
}
/**************************************************************************************
* Function: DecodeNextElement
*
* Description: decode next syntactic element in AAC frame
*
* Inputs: valid AACDecInfo struct
* double pointer to buffer containing next element
* pointer to bit offset
* pointer to number of valid bits remaining in buf
*
* Outputs: type of element decoded (aacDecInfo->currBlockID)
* type of element decoded last time (aacDecInfo->prevBlockID)
* updated aacDecInfo state, depending on which element was decoded
* updated buffer pointer
* updated bit offset
* updated number of available bits
*
* Return: 0 if successful, error code (< 0) if error
**************************************************************************************/
int DecodeNextElement(AACDecInfo *aacDecInfo, unsigned char **buf, int *bitOffset, int *bitsAvail)
{
int err, bitsUsed;
PSInfoBase *psi;
BitStreamInfo bsi;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
/* init bitstream reader */
SetBitstreamPointer(&bsi, (*bitsAvail + 7) >> 3, *buf);
GetBits(&bsi, *bitOffset);
/* read element ID (save last ID for SBR purposes) */
aacDecInfo->prevBlockID = aacDecInfo->currBlockID;
aacDecInfo->currBlockID = GetBits(&bsi, NUM_SYN_ID_BITS);
/* set defaults (could be overwritten by DecodeXXXElement(), depending on currBlockID) */
psi->commonWin = 0;
err = 0;
switch (aacDecInfo->currBlockID) {
case AAC_ID_SCE:
err = DecodeSingleChannelElement(aacDecInfo, &bsi);
break;
case AAC_ID_CPE:
err = DecodeChannelPairElement(aacDecInfo, &bsi);
break;
case AAC_ID_CCE:
/* TODO - implement CCE decoding */
break;
case AAC_ID_LFE:
err = DecodeLFEChannelElement(aacDecInfo, &bsi);
break;
case AAC_ID_DSE:
err = DecodeDataStreamElement(aacDecInfo, &bsi);
break;
case AAC_ID_PCE:
err = DecodeProgramConfigElement(psi->pce + 0, &bsi);
break;
case AAC_ID_FIL:
err = DecodeFillElement(aacDecInfo, &bsi);
break;
case AAC_ID_END:
break;
}
if (err)
return ERR_AAC_SYNTAX_ELEMENT;
/* update bitstream reader */
bitsUsed = CalcBitsUsed(&bsi, *buf, *bitOffset);
*buf += (bitsUsed + *bitOffset) >> 3;
*bitOffset = (bitsUsed + *bitOffset) & 0x07;
*bitsAvail -= bitsUsed;
if (*bitsAvail < 0)
return ERR_AAC_INDATA_UNDERFLOW;
return ERR_AAC_NONE;
}
|
1137519-player
|
aac/decelmnt.c
|
C
|
lgpl
| 13,888
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: imdct.c,v 1.1 2005/02/26 01:47:35 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* imdct.c - inverse MDCT
**************************************************************************************/
#include "coder.h"
#include "assembly.h"
#define RND_VAL (1 << (FBITS_OUT_IMDCT-1))
#ifndef AAC_ENABLE_SBR
/**************************************************************************************
* Function: DecWindowOverlap
*
* Description: apply synthesis window, do overlap-add, clip to 16-bit PCM,
* for winSequence LONG-LONG
*
* Inputs: input buffer (output of type-IV DCT)
* overlap buffer (saved from last time)
* number of channels
* window type (sin or KBD) for input buffer
* window type (sin or KBD) for overlap buffer
*
* Outputs: one channel, one frame of 16-bit PCM, interleaved by nChans
*
* Return: none
*
* Notes: this processes one channel at a time, but skips every other sample in
* the output buffer (pcm) for stereo interleaving
* this should fit in registers on ARM
*
* TODO: ARM5E version with saturating overlap/add (QADD)
* asm code with free pointer updates, better load scheduling
**************************************************************************************/
static void DecWindowOverlap(int *buf0, int *over0, short *pcm0, int nChans, int winTypeCurr, int winTypePrev)
{
int in, w0, w1, f0, f1;
int *buf1, *over1;
short *pcm1;
const int *wndPrev, *wndCurr;
buf0 += (1024 >> 1);
buf1 = buf0 - 1;
pcm1 = pcm0 + (1024 - 1) * nChans;
over1 = over0 + 1024 - 1;
wndPrev = (winTypePrev == 1 ? kbdWindow + kbdWindowOffset[1] : sinWindow + sinWindowOffset[1]);
if (winTypeCurr == winTypePrev) {
/* cut window loads in half since current and overlap sections use same symmetric window */
do {
w0 = *wndPrev++;
w1 = *wndPrev++;
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*pcm0 = CLIPTOSHORT( (in - f0 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm0 += nChans;
in = *over1;
*pcm1 = CLIPTOSHORT( (in + f1 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm1 -= nChans;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
} else {
/* different windows for current and overlap parts - should still fit in registers on ARM w/o stack spill */
wndCurr = (winTypeCurr == 1 ? kbdWindow + kbdWindowOffset[1] : sinWindow + sinWindowOffset[1]);
do {
w0 = *wndPrev++;
w1 = *wndPrev++;
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*pcm0 = CLIPTOSHORT( (in - f0 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm0 += nChans;
in = *over1;
*pcm1 = CLIPTOSHORT( (in + f1 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm1 -= nChans;
w0 = *wndCurr++;
w1 = *wndCurr++;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
}
}
/**************************************************************************************
* Function: DecWindowOverlapLongStart
*
* Description: apply synthesis window, do overlap-add, clip to 16-bit PCM,
* for winSequence LONG-START
*
* Inputs: input buffer (output of type-IV DCT)
* overlap buffer (saved from last time)
* number of channels
* window type (sin or KBD) for input buffer
* window type (sin or KBD) for overlap buffer
*
* Outputs: one channel, one frame of 16-bit PCM, interleaved by nChans
*
* Return: none
*
* Notes: this processes one channel at a time, but skips every other sample in
* the output buffer (pcm) for stereo interleaving
* this should fit in registers on ARM
*
* TODO: ARM5E version with saturating overlap/add (QADD)
* asm code with free pointer updates, better load scheduling
**************************************************************************************/
static void DecWindowOverlapLongStart(int *buf0, int *over0, short *pcm0, int nChans, int winTypeCurr, int winTypePrev)
{
int i, in, w0, w1, f0, f1;
int *buf1, *over1;
short *pcm1;
const int *wndPrev, *wndCurr;
buf0 += (1024 >> 1);
buf1 = buf0 - 1;
pcm1 = pcm0 + (1024 - 1) * nChans;
over1 = over0 + 1024 - 1;
wndPrev = (winTypePrev == 1 ? kbdWindow + kbdWindowOffset[1] : sinWindow + sinWindowOffset[1]);
i = 448; /* 2 outputs, 2 overlaps per loop */
do {
w0 = *wndPrev++;
w1 = *wndPrev++;
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*pcm0 = CLIPTOSHORT( (in - f0 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm0 += nChans;
in = *over1;
*pcm1 = CLIPTOSHORT( (in + f1 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm1 -= nChans;
in = *buf1--;
*over1-- = 0; /* Wn = 0 for n = (2047, 2046, ... 1600) */
*over0++ = in >> 1; /* Wn = 1 for n = (1024, 1025, ... 1471) */
} while (--i);
wndCurr = (winTypeCurr == 1 ? kbdWindow + kbdWindowOffset[0] : sinWindow + sinWindowOffset[0]);
/* do 64 more loops - 2 outputs, 2 overlaps per loop */
do {
w0 = *wndPrev++;
w1 = *wndPrev++;
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*pcm0 = CLIPTOSHORT( (in - f0 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm0 += nChans;
in = *over1;
*pcm1 = CLIPTOSHORT( (in + f1 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm1 -= nChans;
w0 = *wndCurr++; /* W[0], W[1], ... --> W[255], W[254], ... */
w1 = *wndCurr++; /* W[127], W[126], ... --> W[128], W[129], ... */
in = *buf1--;
*over1-- = MULSHIFT32(w0, in); /* Wn = short window for n = (1599, 1598, ... , 1536) */
*over0++ = MULSHIFT32(w1, in); /* Wn = short window for n = (1472, 1473, ... , 1535) */
} while (over0 < over1);
}
/**************************************************************************************
* Function: DecWindowOverlapLongStop
*
* Description: apply synthesis window, do overlap-add, clip to 16-bit PCM,
* for winSequence LONG-STOP
*
* Inputs: input buffer (output of type-IV DCT)
* overlap buffer (saved from last time)
* number of channels
* window type (sin or KBD) for input buffer
* window type (sin or KBD) for overlap buffer
*
* Outputs: one channel, one frame of 16-bit PCM, interleaved by nChans
*
* Return: none
*
* Notes: this processes one channel at a time, but skips every other sample in
* the output buffer (pcm) for stereo interleaving
* this should fit in registers on ARM
*
* TODO: ARM5E version with saturating overlap/add (QADD)
* asm code with free pointer updates, better load scheduling
**************************************************************************************/
static void DecWindowOverlapLongStop(int *buf0, int *over0, short *pcm0, int nChans, int winTypeCurr, int winTypePrev)
{
int i, in, w0, w1, f0, f1;
int *buf1, *over1;
short *pcm1;
const int *wndPrev, *wndCurr;
buf0 += (1024 >> 1);
buf1 = buf0 - 1;
pcm1 = pcm0 + (1024 - 1) * nChans;
over1 = over0 + 1024 - 1;
wndPrev = (winTypePrev == 1 ? kbdWindow + kbdWindowOffset[0] : sinWindow + sinWindowOffset[0]);
wndCurr = (winTypeCurr == 1 ? kbdWindow + kbdWindowOffset[1] : sinWindow + sinWindowOffset[1]);
i = 448; /* 2 outputs, 2 overlaps per loop */
do {
/* Wn = 0 for n = (0, 1, ... 447) */
/* Wn = 1 for n = (576, 577, ... 1023) */
in = *buf0++;
f1 = in >> 1; /* scale since skipping multiply by Q31 */
in = *over0;
*pcm0 = CLIPTOSHORT( (in + RND_VAL) >> FBITS_OUT_IMDCT );
pcm0 += nChans;
in = *over1;
*pcm1 = CLIPTOSHORT( (in + f1 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm1 -= nChans;
w0 = *wndCurr++;
w1 = *wndCurr++;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (--i);
/* do 64 more loops - 2 outputs, 2 overlaps per loop */
do {
w0 = *wndPrev++; /* W[0], W[1], ...W[63] */
w1 = *wndPrev++; /* W[127], W[126], ... W[64] */
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*pcm0 = CLIPTOSHORT( (in - f0 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm0 += nChans;
in = *over1;
*pcm1 = CLIPTOSHORT( (in + f1 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm1 -= nChans;
w0 = *wndCurr++;
w1 = *wndCurr++;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
}
/**************************************************************************************
* Function: DecWindowOverlapShort
*
* Description: apply synthesis window, do overlap-add, clip to 16-bit PCM,
* for winSequence EIGHT-SHORT (does all 8 short blocks)
*
* Inputs: input buffer (output of type-IV DCT)
* overlap buffer (saved from last time)
* number of channels
* window type (sin or KBD) for input buffer
* window type (sin or KBD) for overlap buffer
*
* Outputs: one channel, one frame of 16-bit PCM, interleaved by nChans
*
* Return: none
*
* Notes: this processes one channel at a time, but skips every other sample in
* the output buffer (pcm) for stereo interleaving
* this should fit in registers on ARM
*
* TODO: ARM5E version with saturating overlap/add (QADD)
* asm code with free pointer updates, better load scheduling
**************************************************************************************/
static void DecWindowOverlapShort(int *buf0, int *over0, short *pcm0, int nChans, int winTypeCurr, int winTypePrev)
{
int i, in, w0, w1, f0, f1;
int *buf1, *over1;
short *pcm1;
const int *wndPrev, *wndCurr;
wndPrev = (winTypePrev == 1 ? kbdWindow + kbdWindowOffset[0] : sinWindow + sinWindowOffset[0]);
wndCurr = (winTypeCurr == 1 ? kbdWindow + kbdWindowOffset[0] : sinWindow + sinWindowOffset[0]);
/* pcm[0-447] = 0 + overlap[0-447] */
i = 448;
do {
f0 = *over0++;
f1 = *over0++;
*pcm0 = CLIPTOSHORT( (f0 + RND_VAL) >> FBITS_OUT_IMDCT ); pcm0 += nChans;
*pcm0 = CLIPTOSHORT( (f1 + RND_VAL) >> FBITS_OUT_IMDCT ); pcm0 += nChans;
i -= 2;
} while (i);
/* pcm[448-575] = Wp[0-127] * block0[0-127] + overlap[448-575] */
pcm1 = pcm0 + (128 - 1) * nChans;
over1 = over0 + 128 - 1;
buf0 += 64;
buf1 = buf0 - 1;
do {
w0 = *wndPrev++; /* W[0], W[1], ...W[63] */
w1 = *wndPrev++; /* W[127], W[126], ... W[64] */
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *over0;
*pcm0 = CLIPTOSHORT( (in - f0 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm0 += nChans;
in = *over1;
*pcm1 = CLIPTOSHORT( (in + f1 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm1 -= nChans;
w0 = *wndCurr++;
w1 = *wndCurr++;
in = *buf1--;
/* save over0/over1 for next short block, in the slots just vacated */
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
/* pcm[576-703] = Wc[128-255] * block0[128-255] + Wc[0-127] * block1[0-127] + overlap[576-703]
* pcm[704-831] = Wc[128-255] * block1[128-255] + Wc[0-127] * block2[0-127] + overlap[704-831]
* pcm[832-959] = Wc[128-255] * block2[128-255] + Wc[0-127] * block3[0-127] + overlap[832-959]
*/
for (i = 0; i < 3; i++) {
pcm0 += 64 * nChans;
pcm1 = pcm0 + (128 - 1) * nChans;
over0 += 64;
over1 = over0 + 128 - 1;
buf0 += 64;
buf1 = buf0 - 1;
wndCurr -= 128;
do {
w0 = *wndCurr++; /* W[0], W[1], ...W[63] */
w1 = *wndCurr++; /* W[127], W[126], ... W[64] */
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *(over0 - 128); /* from last short block */
in += *(over0 + 0); /* from last full frame */
*pcm0 = CLIPTOSHORT( (in - f0 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm0 += nChans;
in = *(over1 - 128); /* from last short block */
in += *(over1 + 0); /* from last full frame */
*pcm1 = CLIPTOSHORT( (in + f1 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm1 -= nChans;
/* save over0/over1 for next short block, in the slots just vacated */
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
}
/* pcm[960-1023] = Wc[128-191] * block3[128-191] + Wc[0-63] * block4[0-63] + overlap[960-1023]
* over[0-63] = Wc[192-255] * block3[192-255] + Wc[64-127] * block4[64-127]
*/
pcm0 += 64 * nChans;
over0 -= 832; /* points at overlap[64] */
over1 = over0 + 128 - 1; /* points at overlap[191] */
buf0 += 64;
buf1 = buf0 - 1;
wndCurr -= 128;
do {
w0 = *wndCurr++; /* W[0], W[1], ...W[63] */
w1 = *wndCurr++; /* W[127], W[126], ... W[64] */
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
in = *(over0 + 768); /* from last short block */
in += *(over0 + 896); /* from last full frame */
*pcm0 = CLIPTOSHORT( (in - f0 + RND_VAL) >> FBITS_OUT_IMDCT );
pcm0 += nChans;
in = *(over1 + 768); /* from last short block */
*(over1 - 128) = in + f1;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in); /* save in overlap[128-191] */
*over0++ = MULSHIFT32(w1, in); /* save in overlap[64-127] */
} while (over0 < over1);
/* over0 now points at overlap[128] */
/* over[64-191] = Wc[128-255] * block4[128-255] + Wc[0-127] * block5[0-127]
* over[192-319] = Wc[128-255] * block5[128-255] + Wc[0-127] * block6[0-127]
* over[320-447] = Wc[128-255] * block6[128-255] + Wc[0-127] * block7[0-127]
* over[448-576] = Wc[128-255] * block7[128-255]
*/
for (i = 0; i < 3; i++) {
over0 += 64;
over1 = over0 + 128 - 1;
buf0 += 64;
buf1 = buf0 - 1;
wndCurr -= 128;
do {
w0 = *wndCurr++; /* W[0], W[1], ...W[63] */
w1 = *wndCurr++; /* W[127], W[126], ... W[64] */
in = *buf0++;
f0 = MULSHIFT32(w0, in);
f1 = MULSHIFT32(w1, in);
/* from last short block */
*(over0 - 128) -= f0;
*(over1 - 128)+= f1;
in = *buf1--;
*over1-- = MULSHIFT32(w0, in);
*over0++ = MULSHIFT32(w1, in);
} while (over0 < over1);
}
/* over[576-1024] = 0 */
i = 448;
over0 += 64;
do {
*over0++ = 0;
*over0++ = 0;
*over0++ = 0;
*over0++ = 0;
i -= 4;
} while (i);
}
#endif /* !AAC_ENABLE_SBR */
/**************************************************************************************
* Function: IMDCT
*
* Description: inverse transform and convert to 16-bit PCM
*
* Inputs: valid AACDecInfo struct
* index of current channel (0 for SCE/LFE, 0 or 1 for CPE)
* output channel (range = [0, nChans-1])
*
* Outputs: complete frame of decoded PCM, after inverse transform
*
* Return: 0 if successful, -1 if error
*
* Notes: If AAC_ENABLE_SBR is defined at compile time then window + overlap
* does NOT clip to 16-bit PCM and does NOT interleave channels
* If AAC_ENABLE_SBR is NOT defined at compile time, then window + overlap
* does clip to 16-bit PCM and interleaves channels
* If SBR is enabled at compile time, but we don't know whether it is
* actually used for this frame (e.g. the first frame of a stream),
* we need to produce both clipped 16-bit PCM in outbuf AND
* unclipped 32-bit PCM in the SBR input buffer. In this case we make
* a separate pass over the 32-bit PCM to produce 16-bit PCM output.
* This inflicts a slight performance hit when decoding non-SBR files.
**************************************************************************************/
int IMDCT(AACDecInfo *aacDecInfo, int ch, int chOut, short *outbuf)
{
int i;
PSInfoBase *psi;
ICSInfo *icsInfo;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return -1;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
icsInfo = (ch == 1 && psi->commonWin == 1) ? &(psi->icsInfo[0]) : &(psi->icsInfo[ch]);
outbuf += chOut;
/* optimized type-IV DCT (operates inplace) */
if (icsInfo->winSequence == 2) {
/* 8 short blocks */
for (i = 0; i < 8; i++)
DCT4(0, psi->coef[ch] + i*128, psi->gbCurrent[ch]);
} else {
/* 1 long block */
DCT4(1, psi->coef[ch], psi->gbCurrent[ch]);
}
#ifdef AAC_ENABLE_SBR
/* window, overlap-add, don't clip to short (send to SBR decoder)
* store the decoded 32-bit samples in top half (second AAC_MAX_NSAMPS samples) of coef buffer
*/
if (icsInfo->winSequence == 0)
DecWindowOverlapNoClip(psi->coef[ch], psi->overlap[chOut], psi->sbrWorkBuf[ch], icsInfo->winShape, psi->prevWinShape[chOut]);
else if (icsInfo->winSequence == 1)
DecWindowOverlapLongStartNoClip(psi->coef[ch], psi->overlap[chOut], psi->sbrWorkBuf[ch], icsInfo->winShape, psi->prevWinShape[chOut]);
else if (icsInfo->winSequence == 2)
DecWindowOverlapShortNoClip(psi->coef[ch], psi->overlap[chOut], psi->sbrWorkBuf[ch], icsInfo->winShape, psi->prevWinShape[chOut]);
else if (icsInfo->winSequence == 3)
DecWindowOverlapLongStopNoClip(psi->coef[ch], psi->overlap[chOut], psi->sbrWorkBuf[ch], icsInfo->winShape, psi->prevWinShape[chOut]);
if (!aacDecInfo->sbrEnabled) {
for (i = 0; i < AAC_MAX_NSAMPS; i++) {
*outbuf = CLIPTOSHORT((psi->sbrWorkBuf[ch][i] + RND_VAL) >> FBITS_OUT_IMDCT);
outbuf += aacDecInfo->nChans;
}
}
aacDecInfo->rawSampleBuf[ch] = psi->sbrWorkBuf[ch];
aacDecInfo->rawSampleBytes = sizeof(int);
aacDecInfo->rawSampleFBits = FBITS_OUT_IMDCT;
#else
/* window, overlap-add, round to PCM - optimized for each window sequence */
if (icsInfo->winSequence == 0)
DecWindowOverlap(psi->coef[ch], psi->overlap[chOut], outbuf, aacDecInfo->nChans, icsInfo->winShape, psi->prevWinShape[chOut]);
else if (icsInfo->winSequence == 1)
DecWindowOverlapLongStart(psi->coef[ch], psi->overlap[chOut], outbuf, aacDecInfo->nChans, icsInfo->winShape, psi->prevWinShape[chOut]);
else if (icsInfo->winSequence == 2)
DecWindowOverlapShort(psi->coef[ch], psi->overlap[chOut], outbuf, aacDecInfo->nChans, icsInfo->winShape, psi->prevWinShape[chOut]);
else if (icsInfo->winSequence == 3)
DecWindowOverlapLongStop(psi->coef[ch], psi->overlap[chOut], outbuf, aacDecInfo->nChans, icsInfo->winShape, psi->prevWinShape[chOut]);
aacDecInfo->rawSampleBuf[ch] = 0;
aacDecInfo->rawSampleBytes = 0;
aacDecInfo->rawSampleFBits = 0;
#endif
psi->prevWinShape[chOut] = icsInfo->winShape;
return 0;
}
|
1137519-player
|
aac/imdct.c
|
C
|
lgpl
| 20,283
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: statname.h,v 1.1 2005/02/26 01:47:34 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* statname.h - name mangling macros for static linking
**************************************************************************************/
#ifndef _STATNAME_H
#define _STATNAME_H
/* define STAT_PREFIX to a unique name for static linking
* all the C functions and global variables will be mangled by the preprocessor
* e.g. void DCT4(...) becomes void raac_DCT4(...)
*/
#define STAT_PREFIX raac
#define STATCC1(x,y,z) STATCC2(x,y,z)
#define STATCC2(x,y,z) x##y##z
#ifdef STAT_PREFIX
#define STATNAME(func) STATCC1(STAT_PREFIX, _, func)
#else
#define STATNAME(func) func
#endif
/* these symbols are common to all implementations */
#define AllocateBuffers STATNAME(AllocateBuffers)
#define FreeBuffers STATNAME(FreeBuffers)
#define ClearBuffer STATNAME(ClearBuffer)
#define SetRawBlockParams STATNAME(SetRawBlockParams)
#define PrepareRawBlock STATNAME(PrepareRawBlock)
#define FlushCodec STATNAME(FlushCodec)
#define UnpackADTSHeader STATNAME(UnpackADTSHeader)
#define GetADTSChannelMapping STATNAME(GetADTSChannelMapping)
#define UnpackADIFHeader STATNAME(UnpackADIFHeader)
#define DecodeNextElement STATNAME(DecodeNextElement)
#define DecodeNoiselessData STATNAME(DecodeNoiselessData)
#define Dequantize STATNAME(Dequantize)
#define StereoProcess STATNAME(StereoProcess)
#define DeinterleaveShortBlocks STATNAME(DeinterleaveShortBlocks)
#define PNS STATNAME(PNS)
#define TNSFilter STATNAME(TNSFilter)
#define IMDCT STATNAME(IMDCT)
#define InitSBR STATNAME(InitSBR)
#define DecodeSBRBitstream STATNAME(DecodeSBRBitstream)
#define DecodeSBRData STATNAME(DecodeSBRData)
#define FreeSBR STATNAME(FreeSBR)
#define FlushCodecSBR STATNAME(FlushCodecSBR)
/* global ROM tables */
#define sampRateTab STATNAME(sampRateTab)
#define predSFBMax STATNAME(predSFBMax)
#define channelMapTab STATNAME(channelMapTab)
#define elementNumChans STATNAME(elementNumChans)
#define sfBandTotalShort STATNAME(sfBandTotalShort)
#define sfBandTotalLong STATNAME(sfBandTotalLong)
#define sfBandTabShortOffset STATNAME(sfBandTabShortOffset)
#define sfBandTabShort STATNAME(sfBandTabShort)
#define sfBandTabLongOffset STATNAME(sfBandTabLongOffset)
#define sfBandTabLong STATNAME(sfBandTabLong)
#define tnsMaxBandsShortOffset STATNAME(tnsMaxBandsShortOffset)
#define tnsMaxBandsShort STATNAME(tnsMaxBandsShort)
#define tnsMaxOrderShort STATNAME(tnsMaxOrderShort)
#define tnsMaxBandsLongOffset STATNAME(tnsMaxBandsLongOffset)
#define tnsMaxBandsLong STATNAME(tnsMaxBandsLong)
#define tnsMaxOrderLong STATNAME(tnsMaxOrderLong)
/* in your implementation's top-level include file (e.g. real\coder.h) you should
* add new #define sym STATNAME(sym) lines for all the
* additional global functions or variables which your
* implementation uses
*/
#endif /* _STATNAME_H */
|
1137519-player
|
aac/statname.h
|
C
|
lgpl
| 4,772
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: fft.c,v 1.1 2005/02/26 01:47:34 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com), Ken Cooke (kenc@real.com)
* February 2005
*
* fft.c - Ken's optimized radix-4 DIT FFT, optional radix-8 first pass for odd log2(N)
**************************************************************************************/
#include "coder.h"
#include "assembly.h"
#define NUM_FFT_SIZES 2
static const int nfftTab[NUM_FFT_SIZES] = {64, 512};
static const int nfftlog2Tab[NUM_FFT_SIZES] = {6, 9};
#define SQRT1_2 0x5a82799a /* sqrt(1/2) in Q31 */
#define swapcplx(p0,p1) \
t = p0; t1 = *(&(p0)+1); p0 = p1; *(&(p0)+1) = *(&(p1)+1); p1 = t; *(&(p1)+1) = t1
/**************************************************************************************
* Function: BitReverse
*
* Description: Ken's fast in-place bit reverse, using super-small table
*
* Inputs: buffer of samples
* table index (for transform size)
*
* Outputs: bit-reversed samples in same buffer
*
* Return: none
**************************************************************************************/
static void BitReverse(int *inout, int tabidx)
{
int *part0, *part1;
int a,b, t,t1;
const unsigned char* tab = bitrevtab + bitrevtabOffset[tabidx];
int nbits = nfftlog2Tab[tabidx];
part0 = inout;
part1 = inout + (1 << nbits);
while ((a = *tab++) != 0) {
b = *tab++;
swapcplx(part0[4*a+0], part0[4*b+0]); /* 0xxx0 <-> 0yyy0 */
swapcplx(part0[4*a+2], part1[4*b+0]); /* 0xxx1 <-> 1yyy0 */
swapcplx(part1[4*a+0], part0[4*b+2]); /* 1xxx0 <-> 0yyy1 */
swapcplx(part1[4*a+2], part1[4*b+2]); /* 1xxx1 <-> 1yyy1 */
}
do {
swapcplx(part0[4*a+2], part1[4*a+0]); /* 0xxx1 <-> 1xxx0 */
} while ((a = *tab++) != 0);
}
/**************************************************************************************
* Function: R4FirstPass
*
* Description: radix-4 trivial pass for decimation-in-time FFT
*
* Inputs: buffer of (bit-reversed) samples
* number of R4 butterflies per group (i.e. nfft / 4)
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: assumes 2 guard bits, gains no integer bits,
* guard bits out = guard bits in - 2
**************************************************************************************/
static void R4FirstPass(int *x, int bg)
{
int ar, ai, br, bi, cr, ci, dr, di;
for (; bg != 0; bg--) {
ar = x[0] + x[2];
br = x[0] - x[2];
ai = x[1] + x[3];
bi = x[1] - x[3];
cr = x[4] + x[6];
dr = x[4] - x[6];
ci = x[5] + x[7];
di = x[5] - x[7];
/* max per-sample gain = 4.0 (adding 4 inputs together) */
x[0] = ar + cr;
x[4] = ar - cr;
x[1] = ai + ci;
x[5] = ai - ci;
x[2] = br + di;
x[6] = br - di;
x[3] = bi - dr;
x[7] = bi + dr;
x += 8;
}
}
/**************************************************************************************
* Function: R8FirstPass
*
* Description: radix-8 trivial pass for decimation-in-time FFT
*
* Inputs: buffer of (bit-reversed) samples
* number of R8 butterflies per group (i.e. nfft / 8)
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: assumes 3 guard bits, gains 1 integer bit
* guard bits out = guard bits in - 3 (if inputs are full scale)
* or guard bits in - 2 (if inputs bounded to +/- sqrt(2)/2)
* see scaling comments in code
**************************************************************************************/
static void R8FirstPass(int *x, int bg)
{
int ar, ai, br, bi, cr, ci, dr, di;
int sr, si, tr, ti, ur, ui, vr, vi;
int wr, wi, xr, xi, yr, yi, zr, zi;
for (; bg != 0; bg--) {
ar = x[0] + x[2];
br = x[0] - x[2];
ai = x[1] + x[3];
bi = x[1] - x[3];
cr = x[4] + x[6];
dr = x[4] - x[6];
ci = x[5] + x[7];
di = x[5] - x[7];
sr = ar + cr;
ur = ar - cr;
si = ai + ci;
ui = ai - ci;
tr = br - di;
vr = br + di;
ti = bi + dr;
vi = bi - dr;
ar = x[ 8] + x[10];
br = x[ 8] - x[10];
ai = x[ 9] + x[11];
bi = x[ 9] - x[11];
cr = x[12] + x[14];
dr = x[12] - x[14];
ci = x[13] + x[15];
di = x[13] - x[15];
/* max gain of wr/wi/yr/yi vs input = 2
* (sum of 4 samples >> 1)
*/
wr = (ar + cr) >> 1;
yr = (ar - cr) >> 1;
wi = (ai + ci) >> 1;
yi = (ai - ci) >> 1;
/* max gain of output vs input = 4
* (sum of 4 samples >> 1 + sum of 4 samples >> 1)
*/
x[ 0] = (sr >> 1) + wr;
x[ 8] = (sr >> 1) - wr;
x[ 1] = (si >> 1) + wi;
x[ 9] = (si >> 1) - wi;
x[ 4] = (ur >> 1) + yi;
x[12] = (ur >> 1) - yi;
x[ 5] = (ui >> 1) - yr;
x[13] = (ui >> 1) + yr;
ar = br - di;
cr = br + di;
ai = bi + dr;
ci = bi - dr;
/* max gain of xr/xi/zr/zi vs input = 4*sqrt(2)/2 = 2*sqrt(2)
* (sum of 8 samples, multiply by sqrt(2)/2, implicit >> 1 from Q31)
*/
xr = MULSHIFT32(SQRT1_2, ar - ai);
xi = MULSHIFT32(SQRT1_2, ar + ai);
zr = MULSHIFT32(SQRT1_2, cr - ci);
zi = MULSHIFT32(SQRT1_2, cr + ci);
/* max gain of output vs input = (2 + 2*sqrt(2) ~= 4.83)
* (sum of 4 samples >> 1, plus xr/xi/zr/zi with gain of 2*sqrt(2))
* in absolute terms, we have max gain of appx 9.656 (4 + 0.707*8)
* but we also gain 1 int bit (from MULSHIFT32 or from explicit >> 1)
*/
x[ 6] = (tr >> 1) - xr;
x[14] = (tr >> 1) + xr;
x[ 7] = (ti >> 1) - xi;
x[15] = (ti >> 1) + xi;
x[ 2] = (vr >> 1) + zi;
x[10] = (vr >> 1) - zi;
x[ 3] = (vi >> 1) - zr;
x[11] = (vi >> 1) + zr;
x += 16;
}
}
/**************************************************************************************
* Function: R4Core
*
* Description: radix-4 pass for decimation-in-time FFT
*
* Inputs: buffer of samples
* number of R4 butterflies per group
* number of R4 groups per pass
* pointer to twiddle factors tables
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: gain 2 integer bits per pass (see scaling comments in code)
* min 1 GB in
* gbOut = gbIn - 1 (short block) or gbIn - 2 (long block)
* uses 3-mul, 3-add butterflies instead of 4-mul, 2-add
**************************************************************************************/
static void R4Core(int *x, int bg, int gp, int *wtab)
{
int ar, ai, br, bi, cr, ci, dr, di, tr, ti;
int wd, ws, wi;
int i, j, step;
int *xptr, *wptr;
for (; bg != 0; gp <<= 2, bg >>= 2) {
step = 2*gp;
xptr = x;
/* max per-sample gain, per group < 1 + 3*sqrt(2) ~= 5.25 if inputs x are full-scale
* do 3 groups for long block, 2 groups for short block (gain 2 int bits per group)
*
* very conservative scaling:
* group 1: max gain = 5.25, int bits gained = 2, gb used = 1 (2^3 = 8)
* group 2: max gain = 5.25^2 = 27.6, int bits gained = 4, gb used = 1 (2^5 = 32)
* group 3: max gain = 5.25^3 = 144.7, int bits gained = 6, gb used = 2 (2^8 = 256)
*/
for (i = bg; i != 0; i--) {
wptr = wtab;
for (j = gp; j != 0; j--) {
ar = xptr[0];
ai = xptr[1];
xptr += step;
/* gain 2 int bits for br/bi, cr/ci, dr/di (MULSHIFT32 by Q30)
* gain 1 net GB
*/
ws = wptr[0];
wi = wptr[1];
br = xptr[0];
bi = xptr[1];
wd = ws + 2*wi;
tr = MULSHIFT32(wi, br + bi);
br = MULSHIFT32(wd, br) - tr; /* cos*br + sin*bi */
bi = MULSHIFT32(ws, bi) + tr; /* cos*bi - sin*br */
xptr += step;
ws = wptr[2];
wi = wptr[3];
cr = xptr[0];
ci = xptr[1];
wd = ws + 2*wi;
tr = MULSHIFT32(wi, cr + ci);
cr = MULSHIFT32(wd, cr) - tr;
ci = MULSHIFT32(ws, ci) + tr;
xptr += step;
ws = wptr[4];
wi = wptr[5];
dr = xptr[0];
di = xptr[1];
wd = ws + 2*wi;
tr = MULSHIFT32(wi, dr + di);
dr = MULSHIFT32(wd, dr) - tr;
di = MULSHIFT32(ws, di) + tr;
wptr += 6;
tr = ar;
ti = ai;
ar = (tr >> 2) - br;
ai = (ti >> 2) - bi;
br = (tr >> 2) + br;
bi = (ti >> 2) + bi;
tr = cr;
ti = ci;
cr = tr + dr;
ci = di - ti;
dr = tr - dr;
di = di + ti;
xptr[0] = ar + ci;
xptr[1] = ai + dr;
xptr -= step;
xptr[0] = br - cr;
xptr[1] = bi - di;
xptr -= step;
xptr[0] = ar - ci;
xptr[1] = ai - dr;
xptr -= step;
xptr[0] = br + cr;
xptr[1] = bi + di;
xptr += 2;
}
xptr += 3*step;
}
wtab += 3*step;
}
}
/**************************************************************************************
* Function: R4FFT
*
* Description: Ken's very fast in-place radix-4 decimation-in-time FFT
*
* Inputs: table index (for transform size)
* buffer of samples (non bit-reversed)
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: assumes 5 guard bits in for nfft <= 512
* gbOut = gbIn - 4 (assuming input is from PreMultiply)
* gains log2(nfft) - 2 int bits total
* so gain 7 int bits (LONG), 4 int bits (SHORT)
**************************************************************************************/
void R4FFT(int tabidx, int *x)
{
int order = nfftlog2Tab[tabidx];
int nfft = nfftTab[tabidx];
/* decimation in time */
BitReverse(x, tabidx);
if (order & 0x1) {
/* long block: order = 9, nfft = 512 */
R8FirstPass(x, nfft >> 3); /* gain 1 int bit, lose 2 GB */
R4Core(x, nfft >> 5, 8, (int *)twidTabOdd); /* gain 6 int bits, lose 2 GB */
} else {
/* short block: order = 6, nfft = 64 */
R4FirstPass(x, nfft >> 2); /* gain 0 int bits, lose 2 GB */
R4Core(x, nfft >> 4, 4, (int *)twidTabEven); /* gain 4 int bits, lose 1 GB */
}
}
|
1137519-player
|
aac/fft.c
|
C
|
lgpl
| 11,573
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: aactabs.c,v 1.1 2005/02/26 01:47:31 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com), Ken Cooke (kenc@real.com)
* February 2005
*
* aactabs.c - platform-independent tables for AAC decoder (global, read-only)
**************************************************************************************/
#include "aaccommon.h"
/* sample rates (table 4.5.1) */
const int sampRateTab[NUM_SAMPLE_RATES] = {
96000, 88200, 64000, 48000, 44100, 32000,
24000, 22050, 16000, 12000, 11025, 8000
};
/* max scalefactor band for prediction (main profile only) */
const int predSFBMax[NUM_SAMPLE_RATES] = {
33, 33, 38, 40, 40, 40, 41, 41, 37, 37, 37, 34
};
/* channel mapping (table 1.6.3.4) (-1 = unknown, so need to determine mapping based on rules in 8.5.1) */
const int channelMapTab[NUM_DEF_CHAN_MAPS] = {
-1, 1, 2, 3, 4, 5, 6, 8
};
/* number of channels in each element (SCE, CPE, etc.)
* see AACElementID in aaccommon.h
*/
const int elementNumChans[NUM_ELEMENTS] = {
1, 2, 0, 1, 0, 0, 0, 0
};
/* total number of scale factor bands in one window */
const unsigned char sfBandTotalShort[NUM_SAMPLE_RATES] = {
12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15
};
const unsigned char sfBandTotalLong[NUM_SAMPLE_RATES] = {
41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40
};
/* scale factor band tables */
const int sfBandTabShortOffset[NUM_SAMPLE_RATES] = {0, 0, 0, 13, 13, 13, 28, 28, 44, 44, 44, 60};
const short sfBandTabShort[76] = {
/* short block 64, 88, 96 kHz [13] (tables 4.5.24, 4.5.26) */
0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128,
/* short block 32, 44, 48 kHz [15] (table 4.5.15) */
0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128,
/* short block 22, 24 kHz [16] (table 4.5.22) */
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128,
/* short block 11, 12, 16 kHz [16] (table 4.5.20) */
0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128,
/* short block 8 kHz [16] (table 4.5.18) */
0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128
};
const int sfBandTabLongOffset[NUM_SAMPLE_RATES] = {0, 0, 42, 90, 90, 140, 192, 192, 240, 240, 240, 284};
const short sfBandTabLong[325] = {
/* long block 88, 96 kHz [42] (table 4.5.25) */
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52,
56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 156, 172, 188, 212,
240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024,
/* long block 64 kHz [48] (table 4.5.13) */
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64,
72, 80, 88, 100, 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384,
424, 464, 504, 544, 584, 624, 664, 704, 744, 784, 824, 864, 904, 944, 984, 1024,
/* long block 44, 48 kHz [50] (table 4.5.14) */
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88,
96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448,
480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024,
/* long block 32 kHz [52] (table 4.5.16) */
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96,
108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512,
544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024,
/* long block 22, 24 kHz [48] (table 4.5.21) */
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76,
84, 92, 100, 108, 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284,
308, 336, 364, 396, 432, 468, 508, 552, 600, 652, 704, 768, 832, 896, 960, 1024,
/* long block 11, 12, 16 kHz [44] (table 4.5.19) */
0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124,
136, 148, 160, 172, 184, 196, 212, 228, 244, 260, 280, 300, 320, 344, 368,
396, 424, 456, 492, 532, 572, 616, 664, 716, 772, 832, 896, 960, 1024,
/* long block 8 kHz [41] (table 4.5.17) */
0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156,
172, 188, 204, 220, 236, 252, 268, 288, 308, 328, 348, 372, 396, 420,
448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, 1024
};
/* TNS max bands (table 4.139) and max order (table 4.138) */
const int tnsMaxBandsShortOffset[AAC_NUM_PROFILES] = {0, 0, 12};
const unsigned char tnsMaxBandsShort[2*NUM_SAMPLE_RATES] = {
9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, /* short block, Main/LC */
7, 7, 7, 6, 6, 6, 7, 7, 8, 8, 8, 7 /* short block, SSR */
};
const unsigned char tnsMaxOrderShort[AAC_NUM_PROFILES] = {7, 7, 7};
const int tnsMaxBandsLongOffset[AAC_NUM_PROFILES] = {0, 0, 12};
const unsigned char tnsMaxBandsLong[2*NUM_SAMPLE_RATES] = {
31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, /* long block, Main/LC */
28, 28, 27, 26, 26, 26, 29, 29, 23, 23, 23, 19, /* long block, SSR */
};
const unsigned char tnsMaxOrderLong[AAC_NUM_PROFILES] = {20, 12, 12};
|
1137519-player
|
aac/aactabs.c
|
C
|
lgpl
| 6,831
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbr.c,v 1.4 2008/01/15 21:20:31 ehyche Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbr.c - top level functions for SBR
**************************************************************************************/
#ifdef USE_DEFAULT_STDLIB
#include <stdlib.h>
#else
#include "hlxclib/stdlib.h"
#endif
#if defined(REAL_FORMAT_SDK)
#include "rm_memory_shim.h"
#define malloc hx_realformatsdk_malloc
#define free hx_realformatsdk_free
#endif /* #if defined(REAL_FORMAT_SDK) */
#include "sbr.h"
/**************************************************************************************
* Function: InitSBRState
*
* Description: initialize PSInfoSBR struct at start of stream or after flush
*
* Inputs: valid AACDecInfo struct
*
* Outputs: PSInfoSBR struct with proper initial state
*
* Return: none
**************************************************************************************/
static void InitSBRState(PSInfoSBR *psi)
{
int i, ch;
unsigned char *c;
if (!psi)
return;
/* clear SBR state structure */
c = (unsigned char *)psi;
for (i = 0; i < (int)sizeof(PSInfoSBR); i++)
*c++ = 0;
/* initialize non-zero state variables */
for (ch = 0; ch < AAC_MAX_NCHANS; ch++) {
psi->sbrChan[ch].reset = 1;
psi->sbrChan[ch].laPrev = -1;
}
}
/**************************************************************************************
* Function: InitSBR
*
* Description: initialize SBR decoder
*
* Inputs: valid AACDecInfo struct
*
* Outputs: PSInfoSBR struct to hold SBR state information
*
* Return: 0 if successful, error code (< 0) if error
*
* Note: memory allocation for SBR is only done here
**************************************************************************************/
int InitSBR(AACDecInfo *aacDecInfo)
{
PSInfoSBR *psi;
if (!aacDecInfo)
return ERR_AAC_NULL_POINTER;
/* allocate SBR state structure */
psi = (PSInfoSBR *)malloc(sizeof(PSInfoSBR));
if (!psi)
return ERR_AAC_SBR_INIT;
InitSBRState(psi);
aacDecInfo->psInfoSBR = psi;
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: FreeSBR
*
* Description: free SBR decoder
*
* Inputs: valid AACDecInfo struct
*
* Outputs: none
*
* Return: none
*
* Note: memory deallocation for SBR is only done here
**************************************************************************************/
void FreeSBR(AACDecInfo *aacDecInfo)
{
if (aacDecInfo && aacDecInfo->psInfoSBR)
free(aacDecInfo->psInfoSBR);
return;
}
/**************************************************************************************
* Function: DecodeSBRBitstream
*
* Description: decode sideband information for SBR
*
* Inputs: valid AACDecInfo struct
* fill buffer with SBR extension block
* number of bytes in fill buffer
* base output channel (range = [0, nChans-1])
*
* Outputs: initialized state structs (SBRHdr, SBRGrid, SBRFreq, SBRChan)
*
* Return: 0 if successful, error code (< 0) if error
*
* Notes: SBR payload should be in aacDecInfo->fillBuf
* returns with no error if fill buffer is not an SBR extension block,
* or if current block is not a fill block (e.g. for LFE upsampling)
**************************************************************************************/
int DecodeSBRBitstream(AACDecInfo *aacDecInfo, int chBase)
{
int headerFlag;
BitStreamInfo bsi;
PSInfoSBR *psi;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoSBR)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoSBR *)(aacDecInfo->psInfoSBR);
if (aacDecInfo->currBlockID != AAC_ID_FIL || (aacDecInfo->fillExtType != EXT_SBR_DATA && aacDecInfo->fillExtType != EXT_SBR_DATA_CRC))
return ERR_AAC_NONE;
SetBitstreamPointer(&bsi, aacDecInfo->fillCount, aacDecInfo->fillBuf);
if (GetBits(&bsi, 4) != (unsigned int)aacDecInfo->fillExtType)
return ERR_AAC_SBR_BITSTREAM;
if (aacDecInfo->fillExtType == EXT_SBR_DATA_CRC)
psi->crcCheckWord = GetBits(&bsi, 10);
headerFlag = GetBits(&bsi, 1);
if (headerFlag) {
/* get sample rate index for output sample rate (2x base rate) */
psi->sampRateIdx = GetSampRateIdx(2 * aacDecInfo->sampRate);
if (psi->sampRateIdx < 0 || psi->sampRateIdx >= NUM_SAMPLE_RATES)
return ERR_AAC_SBR_BITSTREAM;
else if (psi->sampRateIdx >= NUM_SAMPLE_RATES_SBR)
return ERR_AAC_SBR_SINGLERATE_UNSUPPORTED;
/* reset flag = 1 if header values changed */
if (UnpackSBRHeader(&bsi, &(psi->sbrHdr[chBase])))
psi->sbrChan[chBase].reset = 1;
/* first valid SBR header should always trigger CalcFreqTables(), since psi->reset was set in InitSBR() */
if (psi->sbrChan[chBase].reset)
CalcFreqTables(&(psi->sbrHdr[chBase+0]), &(psi->sbrFreq[chBase]), psi->sampRateIdx);
/* copy and reset state to right channel for CPE */
if (aacDecInfo->prevBlockID == AAC_ID_CPE)
psi->sbrChan[chBase+1].reset = psi->sbrChan[chBase+0].reset;
}
/* if no header has been received, upsample only */
if (psi->sbrHdr[chBase].count == 0)
return ERR_AAC_NONE;
if (aacDecInfo->prevBlockID == AAC_ID_SCE) {
UnpackSBRSingleChannel(&bsi, psi, chBase);
} else if (aacDecInfo->prevBlockID == AAC_ID_CPE) {
UnpackSBRChannelPair(&bsi, psi, chBase);
} else {
return ERR_AAC_SBR_BITSTREAM;
}
ByteAlignBitstream(&bsi);
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: DecodeSBRData
*
* Description: apply SBR to one frame of PCM data
*
* Inputs: 1024 samples of decoded 32-bit PCM, before SBR
* size of input PCM samples (must be 4 bytes)
* number of fraction bits in input PCM samples
* base output channel (range = [0, nChans-1])
* initialized state structs (SBRHdr, SBRGrid, SBRFreq, SBRChan)
*
* Outputs: 2048 samples of decoded 16-bit PCM, after SBR
*
* Return: 0 if successful, error code (< 0) if error
**************************************************************************************/
int DecodeSBRData(AACDecInfo *aacDecInfo, int chBase, short *outbuf)
{
int k, l, ch, chBlock, qmfaBands, qmfsBands;
int upsampleOnly, gbIdx, gbMask;
int *inbuf;
short *outptr;
PSInfoSBR *psi;
SBRHeader *sbrHdr;
SBRGrid *sbrGrid;
SBRFreq *sbrFreq;
SBRChan *sbrChan;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoSBR)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoSBR *)(aacDecInfo->psInfoSBR);
/* same header and freq tables for both channels in CPE */
sbrHdr = &(psi->sbrHdr[chBase]);
sbrFreq = &(psi->sbrFreq[chBase]);
/* upsample only if we haven't received an SBR header yet or if we have an LFE block */
if (aacDecInfo->currBlockID == AAC_ID_LFE) {
chBlock = 1;
upsampleOnly = 1;
} else if (aacDecInfo->currBlockID == AAC_ID_FIL) {
if (aacDecInfo->prevBlockID == AAC_ID_SCE)
chBlock = 1;
else if (aacDecInfo->prevBlockID == AAC_ID_CPE)
chBlock = 2;
else
return ERR_AAC_NONE;
upsampleOnly = (sbrHdr->count == 0 ? 1 : 0);
if (aacDecInfo->fillExtType != EXT_SBR_DATA && aacDecInfo->fillExtType != EXT_SBR_DATA_CRC)
return ERR_AAC_NONE;
} else {
/* ignore non-SBR blocks */
return ERR_AAC_NONE;
}
if (upsampleOnly) {
sbrFreq->kStart = 32;
sbrFreq->numQMFBands = 0;
}
for (ch = 0; ch < chBlock; ch++) {
sbrGrid = &(psi->sbrGrid[chBase + ch]);
sbrChan = &(psi->sbrChan[chBase + ch]);
if (aacDecInfo->rawSampleBuf[ch] == 0 || aacDecInfo->rawSampleBytes != 4)
return ERR_AAC_SBR_PCM_FORMAT;
inbuf = (int *)aacDecInfo->rawSampleBuf[ch];
outptr = outbuf + chBase + ch;
/* restore delay buffers (could use ring buffer or keep in temp buffer for nChans == 1) */
for (l = 0; l < HF_GEN; l++) {
for (k = 0; k < 64; k++) {
psi->XBuf[l][k][0] = psi->XBufDelay[chBase + ch][l][k][0];
psi->XBuf[l][k][1] = psi->XBufDelay[chBase + ch][l][k][1];
}
}
/* step 1 - analysis QMF */
qmfaBands = sbrFreq->kStart;
for (l = 0; l < 32; l++) {
gbMask = QMFAnalysis(inbuf + l*32, psi->delayQMFA[chBase + ch], psi->XBuf[l + HF_GEN][0],
aacDecInfo->rawSampleFBits, &(psi->delayIdxQMFA[chBase + ch]), qmfaBands);
gbIdx = ((l + HF_GEN) >> 5) & 0x01;
sbrChan->gbMask[gbIdx] |= gbMask; /* gbIdx = (0 if i < 32), (1 if i >= 32) */
}
if (upsampleOnly) {
/* no SBR - just run synthesis QMF to upsample by 2x */
qmfsBands = 32;
for (l = 0; l < 32; l++) {
/* step 4 - synthesis QMF */
QMFSynthesis(psi->XBuf[l + HF_ADJ][0], psi->delayQMFS[chBase + ch], &(psi->delayIdxQMFS[chBase + ch]), qmfsBands, outptr, aacDecInfo->nChans);
outptr += 64*aacDecInfo->nChans;
}
} else {
/* if previous frame had lower SBR starting freq than current, zero out the synthesized QMF
* bands so they aren't used as sources for patching
* after patch generation, restore from delay buffer
* can only happen after header reset
*/
for (k = sbrFreq->kStartPrev; k < sbrFreq->kStart; k++) {
for (l = 0; l < sbrGrid->envTimeBorder[0] + HF_ADJ; l++) {
psi->XBuf[l][k][0] = 0;
psi->XBuf[l][k][1] = 0;
}
}
/* step 2 - HF generation */
GenerateHighFreq(psi, sbrGrid, sbrFreq, sbrChan, ch);
/* restore SBR bands that were cleared before patch generation (time slots 0, 1 no longer needed) */
for (k = sbrFreq->kStartPrev; k < sbrFreq->kStart; k++) {
for (l = HF_ADJ; l < sbrGrid->envTimeBorder[0] + HF_ADJ; l++) {
psi->XBuf[l][k][0] = psi->XBufDelay[chBase + ch][l][k][0];
psi->XBuf[l][k][1] = psi->XBufDelay[chBase + ch][l][k][1];
}
}
/* step 3 - HF adjustment */
AdjustHighFreq(psi, sbrHdr, sbrGrid, sbrFreq, sbrChan, ch);
/* step 4 - synthesis QMF */
qmfsBands = sbrFreq->kStartPrev + sbrFreq->numQMFBandsPrev;
for (l = 0; l < sbrGrid->envTimeBorder[0]; l++) {
/* if new envelope starts mid-frame, use old settings until start of first envelope in this frame */
QMFSynthesis(psi->XBuf[l + HF_ADJ][0], psi->delayQMFS[chBase + ch], &(psi->delayIdxQMFS[chBase + ch]), qmfsBands, outptr, aacDecInfo->nChans);
outptr += 64*aacDecInfo->nChans;
}
qmfsBands = sbrFreq->kStart + sbrFreq->numQMFBands;
for ( ; l < 32; l++) {
/* use new settings for rest of frame (usually the entire frame, unless the first envelope starts mid-frame) */
QMFSynthesis(psi->XBuf[l + HF_ADJ][0], psi->delayQMFS[chBase + ch], &(psi->delayIdxQMFS[chBase + ch]), qmfsBands, outptr, aacDecInfo->nChans);
outptr += 64*aacDecInfo->nChans;
}
}
/* save delay */
for (l = 0; l < HF_GEN; l++) {
for (k = 0; k < 64; k++) {
psi->XBufDelay[chBase + ch][l][k][0] = psi->XBuf[l+32][k][0];
psi->XBufDelay[chBase + ch][l][k][1] = psi->XBuf[l+32][k][1];
}
}
sbrChan->gbMask[0] = sbrChan->gbMask[1];
sbrChan->gbMask[1] = 0;
if (sbrHdr->count > 0)
sbrChan->reset = 0;
}
sbrFreq->kStartPrev = sbrFreq->kStart;
sbrFreq->numQMFBandsPrev = sbrFreq->numQMFBands;
if (aacDecInfo->nChans > 0 && (chBase + ch) == aacDecInfo->nChans)
psi->frameCount++;
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: FlushCodecSBR
*
* Description: flush internal SBR codec state (after seeking, for example)
*
* Inputs: valid AACDecInfo struct
*
* Outputs: updated state variables for SBR
*
* Return: 0 if successful, error code (< 0) if error
*
* Notes: SBR is heavily dependent on state from previous frames
* (e.g. delta coded scalefactors, previous envelope boundaries, etc.)
* On flush, we reset everything as if SBR had just been initialized
* for the first time. This triggers "upsample-only" mode until
* the first valid SBR header is received. Then SBR starts as usual.
**************************************************************************************/
int FlushCodecSBR(AACDecInfo *aacDecInfo)
{
PSInfoSBR *psi;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoSBR)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoSBR *)(aacDecInfo->psInfoSBR);
InitSBRState(psi);
return 0;
}
|
1137519-player
|
aac/sbr.c
|
C
|
lgpl
| 14,080
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: aacdec.c,v 1.1 2005/02/26 01:47:31 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com), Ken Cooke (kenc@real.com)
* February 2005
*
* aacdec.c - platform-independent top level decoder API
**************************************************************************************/
#include "aaccommon.h"
/**************************************************************************************
* Function: AACInitDecoder
*
* Description: allocate memory for platform-specific data
* clear all the user-accessible fields
* initialize SBR decoder if enabled
*
* Inputs: none
*
* Outputs: none
*
* Return: handle to AAC decoder instance, 0 if malloc fails
**************************************************************************************/
HAACDecoder AACInitDecoder(void)
{
AACDecInfo *aacDecInfo;
aacDecInfo = AllocateBuffers();
if (!aacDecInfo)
return 0;
#ifdef AAC_ENABLE_SBR
if (InitSBR(aacDecInfo)) {
AACFreeDecoder(aacDecInfo);
return 0;
}
#endif
return (HAACDecoder)aacDecInfo;
}
/**************************************************************************************
* Function: AACFreeDecoder
*
* Description: free platform-specific data allocated by AACInitDecoder
* free SBR decoder if enabled
*
* Inputs: valid AAC decoder instance pointer (HAACDecoder)
*
* Outputs: none
*
* Return: none
**************************************************************************************/
void AACFreeDecoder(HAACDecoder hAACDecoder)
{
AACDecInfo *aacDecInfo = (AACDecInfo *)hAACDecoder;
if (!aacDecInfo)
return;
#ifdef AAC_ENABLE_SBR
FreeSBR(aacDecInfo);
#endif
FreeBuffers(aacDecInfo);
}
/**************************************************************************************
* Function: AACFindSyncWord
*
* Description: locate the next byte-alinged sync word in the raw AAC stream
*
* Inputs: buffer to search for sync word
* max number of bytes to search in buffer
*
* Outputs: none
*
* Return: offset to first sync word (bytes from start of buf)
* -1 if sync not found after searching nBytes
**************************************************************************************/
int AACFindSyncWord(unsigned char *buf, int nBytes)
{
int i;
/* find byte-aligned syncword (12 bits = 0xFFF) */
for (i = 0; i < nBytes - 1; i++) {
if ( (buf[i+0] & SYNCWORDH) == SYNCWORDH && (buf[i+1] & SYNCWORDL) == SYNCWORDL )
return i;
}
return -1;
}
/**************************************************************************************
* Function: AACGetLastFrameInfo
*
* Description: get info about last AAC frame decoded (number of samples decoded,
* sample rate, bit rate, etc.)
*
* Inputs: valid AAC decoder instance pointer (HAACDecoder)
* pointer to AACFrameInfo struct
*
* Outputs: filled-in AACFrameInfo struct
*
* Return: none
*
* Notes: call this right after calling AACDecode()
**************************************************************************************/
void AACGetLastFrameInfo(HAACDecoder hAACDecoder, AACFrameInfo *aacFrameInfo)
{
AACDecInfo *aacDecInfo = (AACDecInfo *)hAACDecoder;
if (!aacDecInfo) {
aacFrameInfo->bitRate = 0;
aacFrameInfo->nChans = 0;
aacFrameInfo->sampRateCore = 0;
aacFrameInfo->sampRateOut = 0;
aacFrameInfo->bitsPerSample = 0;
aacFrameInfo->outputSamps = 0;
aacFrameInfo->profile = 0;
aacFrameInfo->tnsUsed = 0;
aacFrameInfo->pnsUsed = 0;
} else {
aacFrameInfo->bitRate = aacDecInfo->bitRate;
aacFrameInfo->nChans = aacDecInfo->nChans;
aacFrameInfo->sampRateCore = aacDecInfo->sampRate;
aacFrameInfo->sampRateOut = aacDecInfo->sampRate * (aacDecInfo->sbrEnabled ? 2 : 1);
aacFrameInfo->bitsPerSample = 16;
aacFrameInfo->outputSamps = aacDecInfo->nChans * AAC_MAX_NSAMPS * (aacDecInfo->sbrEnabled ? 2 : 1);
aacFrameInfo->profile = aacDecInfo->profile;
aacFrameInfo->tnsUsed = aacDecInfo->tnsUsed;
aacFrameInfo->pnsUsed = aacDecInfo->pnsUsed;
}
}
/**************************************************************************************
* Function: AACSetRawBlockParams
*
* Description: set internal state variables for decoding a stream of raw data blocks
*
* Inputs: valid AAC decoder instance pointer (HAACDecoder)
* flag indicating source of parameters
* AACFrameInfo struct, with the members nChans, sampRate, and profile
* optionally filled-in
*
* Outputs: updated codec state
*
* Return: 0 if successful, error code (< 0) if error
*
* Notes: if copyLast == 1, then the codec sets up its internal state (for
* decoding raw blocks) based on previously-decoded ADTS header info
* if copyLast == 0, then the codec uses the values passed in
* aacFrameInfo to configure its internal state (useful when the
* source is MP4 format, for example)
**************************************************************************************/
int AACSetRawBlockParams(HAACDecoder hAACDecoder, int copyLast, AACFrameInfo *aacFrameInfo)
{
AACDecInfo *aacDecInfo = (AACDecInfo *)hAACDecoder;
if (!aacDecInfo)
return ERR_AAC_NULL_POINTER;
aacDecInfo->format = AAC_FF_RAW;
if (copyLast)
return SetRawBlockParams(aacDecInfo, 1, 0, 0, 0);
else
return SetRawBlockParams(aacDecInfo, 0, aacFrameInfo->nChans, aacFrameInfo->sampRateCore, aacFrameInfo->profile);
}
/**************************************************************************************
* Function: AACFlushCodec
*
* Description: flush internal codec state (after seeking, for example)
*
* Inputs: valid AAC decoder instance pointer (HAACDecoder)
*
* Outputs: updated state variables in aacDecInfo
*
* Return: 0 if successful, error code (< 0) if error
**************************************************************************************/
int AACFlushCodec(HAACDecoder hAACDecoder)
{
int ch;
AACDecInfo *aacDecInfo = (AACDecInfo *)hAACDecoder;
if (!aacDecInfo)
return ERR_AAC_NULL_POINTER;
/* reset common state variables which change per-frame
* don't touch state variables which are (usually) constant for entire clip
* (nChans, sampRate, profile, format, sbrEnabled)
*/
aacDecInfo->prevBlockID = AAC_ID_INVALID;
aacDecInfo->currBlockID = AAC_ID_INVALID;
aacDecInfo->currInstTag = -1;
for (ch = 0; ch < MAX_NCHANS_ELEM; ch++)
aacDecInfo->sbDeinterleaveReqd[ch] = 0;
aacDecInfo->adtsBlocksLeft = 0;
aacDecInfo->tnsUsed = 0;
aacDecInfo->pnsUsed = 0;
/* reset internal codec state (flush overlap buffers, etc.) */
FlushCodec(aacDecInfo);
#ifdef AAC_ENABLE_SBR
FlushCodecSBR(aacDecInfo);
#endif
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: AACDecode
*
* Description: decode AAC frame
*
* Inputs: valid AAC decoder instance pointer (HAACDecoder)
* double pointer to buffer of AAC data
* pointer to number of valid bytes remaining in inbuf
* pointer to outbuf, big enough to hold one frame of decoded PCM samples
* (outbuf must be double-sized if SBR enabled)
*
* Outputs: PCM data in outbuf, interleaved LRLRLR... if stereo
* number of output samples = 1024 per channel (2048 if SBR enabled)
* updated inbuf pointer
* updated bytesLeft
*
* Return: 0 if successful, error code (< 0) if error
*
* Notes: inbuf pointer and bytesLeft are not updated until whole frame is
* successfully decoded, so if ERR_AAC_INDATA_UNDERFLOW is returned
* just call AACDecode again with more data in inbuf
**************************************************************************************/
int AACDecode(HAACDecoder hAACDecoder, unsigned char **inbuf, int *bytesLeft, short *outbuf)
{
int err, offset, bitOffset, bitsAvail;
int ch, baseChan, baseChanSBR, elementChans;
unsigned char *inptr;
AACDecInfo *aacDecInfo = (AACDecInfo *)hAACDecoder;
#ifdef AAC_ENABLE_SBR
int elementChansSBR;
#endif
if (!aacDecInfo)
return ERR_AAC_NULL_POINTER;
/* make local copies (see "Notes" above) */
inptr = *inbuf;
bitOffset = 0;
bitsAvail = (*bytesLeft) << 3;
/* first time through figure out what the file format is */
if (aacDecInfo->format == AAC_FF_Unknown) {
if (bitsAvail < 32)
return ERR_AAC_INDATA_UNDERFLOW;
if (IS_ADIF(inptr)) {
/* unpack ADIF header */
aacDecInfo->format = AAC_FF_ADIF;
err = UnpackADIFHeader(aacDecInfo, &inptr, &bitOffset, &bitsAvail);
if (err)
return err;
} else {
/* assume ADTS by default */
aacDecInfo->format = AAC_FF_ADTS;
}
}
/* if ADTS, search for start of next frame */
if (aacDecInfo->format == AAC_FF_ADTS) {
/* can have 1-4 raw data blocks per ADTS frame (header only present for first one) */
if (aacDecInfo->adtsBlocksLeft == 0) {
offset = AACFindSyncWord(inptr, bitsAvail >> 3);
if (offset < 0)
return ERR_AAC_INDATA_UNDERFLOW;
inptr += offset;
bitsAvail -= (offset << 3);
err = UnpackADTSHeader(aacDecInfo, &inptr, &bitOffset, &bitsAvail);
if (err)
return err;
if (aacDecInfo->nChans == -1) {
/* figure out implicit channel mapping if necessary */
err = GetADTSChannelMapping(aacDecInfo, inptr, bitOffset, bitsAvail);
if (err)
return err;
}
}
aacDecInfo->adtsBlocksLeft--;
} else if (aacDecInfo->format == AAC_FF_RAW) {
err = PrepareRawBlock(aacDecInfo);
if (err)
return err;
}
/* check for valid number of channels */
if (aacDecInfo->nChans > AAC_MAX_NCHANS || aacDecInfo->nChans <= 0)
return ERR_AAC_NCHANS_TOO_HIGH;
/* will be set later if active in this frame */
aacDecInfo->tnsUsed = 0;
aacDecInfo->pnsUsed = 0;
bitOffset = 0;
baseChan = 0;
baseChanSBR = 0;
do {
/* parse next syntactic element */
err = DecodeNextElement(aacDecInfo, &inptr, &bitOffset, &bitsAvail);
if (err)
return err;
elementChans = elementNumChans[aacDecInfo->currBlockID];
if (baseChan + elementChans > AAC_MAX_NCHANS)
return ERR_AAC_NCHANS_TOO_HIGH;
/* noiseless decoder and dequantizer */
for (ch = 0; ch < elementChans; ch++) {
err = DecodeNoiselessData(aacDecInfo, &inptr, &bitOffset, &bitsAvail, ch);
if (err)
return err;
if (Dequantize(aacDecInfo, ch))
return ERR_AAC_DEQUANT;
}
/* mid-side and intensity stereo */
if (aacDecInfo->currBlockID == AAC_ID_CPE) {
if (StereoProcess(aacDecInfo))
return ERR_AAC_STEREO_PROCESS;
}
/* PNS, TNS, inverse transform */
for (ch = 0; ch < elementChans; ch++) {
if (PNS(aacDecInfo, ch))
return ERR_AAC_PNS;
if (aacDecInfo->sbDeinterleaveReqd[ch]) {
/* deinterleave short blocks, if required */
if (DeinterleaveShortBlocks(aacDecInfo, ch))
return ERR_AAC_SHORT_BLOCK_DEINT;
aacDecInfo->sbDeinterleaveReqd[ch] = 0;
}
if (TNSFilter(aacDecInfo, ch))
return ERR_AAC_TNS;
if (IMDCT(aacDecInfo, ch, baseChan + ch, outbuf))
return ERR_AAC_IMDCT;
}
#ifdef AAC_ENABLE_SBR
if (aacDecInfo->sbrEnabled && (aacDecInfo->currBlockID == AAC_ID_FIL || aacDecInfo->currBlockID == AAC_ID_LFE)) {
if (aacDecInfo->currBlockID == AAC_ID_LFE)
elementChansSBR = elementNumChans[AAC_ID_LFE];
else if (aacDecInfo->currBlockID == AAC_ID_FIL && (aacDecInfo->prevBlockID == AAC_ID_SCE || aacDecInfo->prevBlockID == AAC_ID_CPE))
elementChansSBR = elementNumChans[aacDecInfo->prevBlockID];
else
elementChansSBR = 0;
if (baseChanSBR + elementChansSBR > AAC_MAX_NCHANS)
return ERR_AAC_SBR_NCHANS_TOO_HIGH;
/* parse SBR extension data if present (contained in a fill element) */
if (DecodeSBRBitstream(aacDecInfo, baseChanSBR))
return ERR_AAC_SBR_BITSTREAM;
/* apply SBR */
if (DecodeSBRData(aacDecInfo, baseChanSBR, outbuf))
return ERR_AAC_SBR_DATA;
baseChanSBR += elementChansSBR;
}
#endif
baseChan += elementChans;
} while (aacDecInfo->currBlockID != AAC_ID_END);
/* byte align after each raw_data_block */
if (bitOffset) {
inptr++;
bitsAvail -= (8-bitOffset);
bitOffset = 0;
if (bitsAvail < 0)
return ERR_AAC_INDATA_UNDERFLOW;
}
/* update pointers */
aacDecInfo->frameCount++;
*bytesLeft -= (inptr - *inbuf);
*inbuf = inptr;
return ERR_AAC_NONE;
}
|
1137519-player
|
aac/aacdec.c
|
C
|
lgpl
| 14,333
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbrhfgen.c,v 1.2 2005/05/19 20:45:20 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbrhfgen.c - high frequency generation for SBR
**************************************************************************************/
#include "sbr.h"
#include "assembly.h"
#define FBITS_LPCOEFS 29 /* Q29 for range of (-4, 4) */
#define MAG_16 (16 * (1 << (32 - (2*(32-FBITS_LPCOEFS))))) /* i.e. 16 in Q26 format */
#define RELAX_COEF 0x7ffff79c /* 1.0 / (1.0 + 1e-6), Q31 */
/* newBWTab[prev invfMode][curr invfMode], format = Q31 (table 4.158)
* sample file which uses all of these: al_sbr_sr_64_2_fsaac32.aac
*/
static const int newBWTab[4][4] = {
{0x00000000, 0x4ccccccd, 0x73333333, 0x7d70a3d7},
{0x4ccccccd, 0x60000000, 0x73333333, 0x7d70a3d7},
{0x00000000, 0x60000000, 0x73333333, 0x7d70a3d7},
{0x00000000, 0x60000000, 0x73333333, 0x7d70a3d7},
};
/**************************************************************************************
* Function: CVKernel1
*
* Description: kernel of covariance matrix calculation for p01, p11, p12, p22
*
* Inputs: buffer of low-freq samples, starting at time index = 0,
* freq index = patch subband
*
* Outputs: 64-bit accumulators for p01re, p01im, p12re, p12im, p11re, p22re
* stored in accBuf
*
* Return: none
*
* Notes: this is carefully written to be efficient on ARM
* use the assembly code version in sbrcov.s when building for ARM!
**************************************************************************************/
#if (defined (__arm) && defined (__ARMCC_VERSION)) || (defined (_WIN32) && defined (_WIN32_WCE) && defined (ARM)) || (defined(__GNUC__) && defined(__arm__))
#ifdef __cplusplus
extern "C"
#endif
void CVKernel1(int *XBuf, int *accBuf);
#else
void CVKernel1(int *XBuf, int *accBuf)
{
U64 p01re, p01im, p12re, p12im, p11re, p22re;
int n, x0re, x0im, x1re, x1im;
x0re = XBuf[0];
x0im = XBuf[1];
XBuf += (2*64);
x1re = XBuf[0];
x1im = XBuf[1];
XBuf += (2*64);
p01re.w64 = p01im.w64 = 0;
p12re.w64 = p12im.w64 = 0;
p11re.w64 = 0;
p22re.w64 = 0;
p12re.w64 = MADD64(p12re.w64, x1re, x0re);
p12re.w64 = MADD64(p12re.w64, x1im, x0im);
p12im.w64 = MADD64(p12im.w64, x0re, x1im);
p12im.w64 = MADD64(p12im.w64, -x0im, x1re);
p22re.w64 = MADD64(p22re.w64, x0re, x0re);
p22re.w64 = MADD64(p22re.w64, x0im, x0im);
for (n = (NUM_TIME_SLOTS*SAMPLES_PER_SLOT + 6); n != 0; n--) {
/* 4 input, 3*2 acc, 1 ptr, 1 loop counter = 12 registers (use same for x0im, -x0im) */
x0re = x1re;
x0im = x1im;
x1re = XBuf[0];
x1im = XBuf[1];
p01re.w64 = MADD64(p01re.w64, x1re, x0re);
p01re.w64 = MADD64(p01re.w64, x1im, x0im);
p01im.w64 = MADD64(p01im.w64, x0re, x1im);
p01im.w64 = MADD64(p01im.w64, -x0im, x1re);
p11re.w64 = MADD64(p11re.w64, x0re, x0re);
p11re.w64 = MADD64(p11re.w64, x0im, x0im);
XBuf += (2*64);
}
/* these can be derived by slight changes to account for boundary conditions */
p12re.w64 += p01re.w64;
p12re.w64 = MADD64(p12re.w64, x1re, -x0re);
p12re.w64 = MADD64(p12re.w64, x1im, -x0im);
p12im.w64 += p01im.w64;
p12im.w64 = MADD64(p12im.w64, x0re, -x1im);
p12im.w64 = MADD64(p12im.w64, x0im, x1re);
p22re.w64 += p11re.w64;
p22re.w64 = MADD64(p22re.w64, x0re, -x0re);
p22re.w64 = MADD64(p22re.w64, x0im, -x0im);
accBuf[0] = p01re.r.lo32; accBuf[1] = p01re.r.hi32;
accBuf[2] = p01im.r.lo32; accBuf[3] = p01im.r.hi32;
accBuf[4] = p11re.r.lo32; accBuf[5] = p11re.r.hi32;
accBuf[6] = p12re.r.lo32; accBuf[7] = p12re.r.hi32;
accBuf[8] = p12im.r.lo32; accBuf[9] = p12im.r.hi32;
accBuf[10] = p22re.r.lo32; accBuf[11] = p22re.r.hi32;
}
#endif
/**************************************************************************************
* Function: CalcCovariance1
*
* Description: calculate covariance matrix for p01, p12, p11, p22 (4.6.18.6.2)
*
* Inputs: buffer of low-freq samples, starting at time index 0,
* freq index = patch subband
*
* Outputs: complex covariance elements p01re, p01im, p12re, p12im, p11re, p22re
* (p11im = p22im = 0)
* format = integer (Q0) * 2^N, with scalefactor N >= 0
*
* Return: scalefactor N
*
* Notes: outputs are normalized to have 1 GB (sign in at least top 2 bits)
**************************************************************************************/
static int CalcCovariance1(int *XBuf, int *p01reN, int *p01imN, int *p12reN, int *p12imN, int *p11reN, int *p22reN)
{
int accBuf[2*6];
int n, z, s, loShift, hiShift, gbMask;
U64 p01re, p01im, p12re, p12im, p11re, p22re;
CVKernel1(XBuf, accBuf);
p01re.r.lo32 = accBuf[0]; p01re.r.hi32 = accBuf[1];
p01im.r.lo32 = accBuf[2]; p01im.r.hi32 = accBuf[3];
p11re.r.lo32 = accBuf[4]; p11re.r.hi32 = accBuf[5];
p12re.r.lo32 = accBuf[6]; p12re.r.hi32 = accBuf[7];
p12im.r.lo32 = accBuf[8]; p12im.r.hi32 = accBuf[9];
p22re.r.lo32 = accBuf[10]; p22re.r.hi32 = accBuf[11];
/* 64-bit accumulators now have 2*FBITS_OUT_QMFA fraction bits
* want to scale them down to integers (32-bit signed, Q0)
* with scale factor of 2^n, n >= 0
* leave 2 GB's for calculating determinant, so take top 30 non-zero bits
*/
gbMask = ((p01re.r.hi32) ^ (p01re.r.hi32 >> 31)) | ((p01im.r.hi32) ^ (p01im.r.hi32 >> 31));
gbMask |= ((p12re.r.hi32) ^ (p12re.r.hi32 >> 31)) | ((p12im.r.hi32) ^ (p12im.r.hi32 >> 31));
gbMask |= ((p11re.r.hi32) ^ (p11re.r.hi32 >> 31)) | ((p22re.r.hi32) ^ (p22re.r.hi32 >> 31));
if (gbMask == 0) {
s = p01re.r.hi32 >> 31; gbMask = (p01re.r.lo32 ^ s) - s;
s = p01im.r.hi32 >> 31; gbMask |= (p01im.r.lo32 ^ s) - s;
s = p12re.r.hi32 >> 31; gbMask |= (p12re.r.lo32 ^ s) - s;
s = p12im.r.hi32 >> 31; gbMask |= (p12im.r.lo32 ^ s) - s;
s = p11re.r.hi32 >> 31; gbMask |= (p11re.r.lo32 ^ s) - s;
s = p22re.r.hi32 >> 31; gbMask |= (p22re.r.lo32 ^ s) - s;
z = 32 + CLZ(gbMask);
} else {
gbMask = FASTABS(p01re.r.hi32) | FASTABS(p01im.r.hi32);
gbMask |= FASTABS(p12re.r.hi32) | FASTABS(p12im.r.hi32);
gbMask |= FASTABS(p11re.r.hi32) | FASTABS(p22re.r.hi32);
z = CLZ(gbMask);
}
n = 64 - z; /* number of non-zero bits in bottom of 64-bit word */
if (n <= 30) {
loShift = (30 - n);
*p01reN = p01re.r.lo32 << loShift; *p01imN = p01im.r.lo32 << loShift;
*p12reN = p12re.r.lo32 << loShift; *p12imN = p12im.r.lo32 << loShift;
*p11reN = p11re.r.lo32 << loShift; *p22reN = p22re.r.lo32 << loShift;
return -(loShift + 2*FBITS_OUT_QMFA);
} else if (n < 32 + 30) {
loShift = (n - 30);
hiShift = 32 - loShift;
*p01reN = (p01re.r.hi32 << hiShift) | (p01re.r.lo32 >> loShift);
*p01imN = (p01im.r.hi32 << hiShift) | (p01im.r.lo32 >> loShift);
*p12reN = (p12re.r.hi32 << hiShift) | (p12re.r.lo32 >> loShift);
*p12imN = (p12im.r.hi32 << hiShift) | (p12im.r.lo32 >> loShift);
*p11reN = (p11re.r.hi32 << hiShift) | (p11re.r.lo32 >> loShift);
*p22reN = (p22re.r.hi32 << hiShift) | (p22re.r.lo32 >> loShift);
return (loShift - 2*FBITS_OUT_QMFA);
} else {
hiShift = n - (32 + 30);
*p01reN = p01re.r.hi32 >> hiShift; *p01imN = p01im.r.hi32 >> hiShift;
*p12reN = p12re.r.hi32 >> hiShift; *p12imN = p12im.r.hi32 >> hiShift;
*p11reN = p11re.r.hi32 >> hiShift; *p22reN = p22re.r.hi32 >> hiShift;
return (32 - 2*FBITS_OUT_QMFA - hiShift);
}
return 0;
}
/**************************************************************************************
* Function: CVKernel2
*
* Description: kernel of covariance matrix calculation for p02
*
* Inputs: buffer of low-freq samples, starting at time index = 0,
* freq index = patch subband
*
* Outputs: 64-bit accumulators for p02re, p02im stored in accBuf
*
* Return: none
*
* Notes: this is carefully written to be efficient on ARM
* use the assembly code version in sbrcov.s when building for ARM!
**************************************************************************************/
#if (defined (__arm) && defined (__ARMCC_VERSION)) || (defined (_WIN32) && defined (_WIN32_WCE) && defined (ARM)) || (defined(__GNUC__) && defined(__arm__))
#ifdef __cplusplus
extern "C"
#endif
void CVKernel2(int *XBuf, int *accBuf);
#else
void CVKernel2(int *XBuf, int *accBuf)
{
U64 p02re, p02im;
int n, x0re, x0im, x1re, x1im, x2re, x2im;
p02re.w64 = p02im.w64 = 0;
x0re = XBuf[0];
x0im = XBuf[1];
XBuf += (2*64);
x1re = XBuf[0];
x1im = XBuf[1];
XBuf += (2*64);
for (n = (NUM_TIME_SLOTS*SAMPLES_PER_SLOT + 6); n != 0; n--) {
/* 6 input, 2*2 acc, 1 ptr, 1 loop counter = 12 registers (use same for x0im, -x0im) */
x2re = XBuf[0];
x2im = XBuf[1];
p02re.w64 = MADD64(p02re.w64, x2re, x0re);
p02re.w64 = MADD64(p02re.w64, x2im, x0im);
p02im.w64 = MADD64(p02im.w64, x0re, x2im);
p02im.w64 = MADD64(p02im.w64, -x0im, x2re);
x0re = x1re;
x0im = x1im;
x1re = x2re;
x1im = x2im;
XBuf += (2*64);
}
accBuf[0] = p02re.r.lo32;
accBuf[1] = p02re.r.hi32;
accBuf[2] = p02im.r.lo32;
accBuf[3] = p02im.r.hi32;
}
#endif
/**************************************************************************************
* Function: CalcCovariance2
*
* Description: calculate covariance matrix for p02 (4.6.18.6.2)
*
* Inputs: buffer of low-freq samples, starting at time index = 0,
* freq index = patch subband
*
* Outputs: complex covariance element p02re, p02im
* format = integer (Q0) * 2^N, with scalefactor N >= 0
*
* Return: scalefactor N
*
* Notes: outputs are normalized to have 1 GB (sign in at least top 2 bits)
**************************************************************************************/
static int CalcCovariance2(int *XBuf, int *p02reN, int *p02imN)
{
U64 p02re, p02im;
int n, z, s, loShift, hiShift, gbMask;
int accBuf[2*2];
CVKernel2(XBuf, accBuf);
p02re.r.lo32 = accBuf[0];
p02re.r.hi32 = accBuf[1];
p02im.r.lo32 = accBuf[2];
p02im.r.hi32 = accBuf[3];
/* 64-bit accumulators now have 2*FBITS_OUT_QMFA fraction bits
* want to scale them down to integers (32-bit signed, Q0)
* with scale factor of 2^n, n >= 0
* leave 1 GB for calculating determinant, so take top 30 non-zero bits
*/
gbMask = ((p02re.r.hi32) ^ (p02re.r.hi32 >> 31)) | ((p02im.r.hi32) ^ (p02im.r.hi32 >> 31));
if (gbMask == 0) {
s = p02re.r.hi32 >> 31; gbMask = (p02re.r.lo32 ^ s) - s;
s = p02im.r.hi32 >> 31; gbMask |= (p02im.r.lo32 ^ s) - s;
z = 32 + CLZ(gbMask);
} else {
gbMask = FASTABS(p02re.r.hi32) | FASTABS(p02im.r.hi32);
z = CLZ(gbMask);
}
n = 64 - z; /* number of non-zero bits in bottom of 64-bit word */
if (n <= 30) {
loShift = (30 - n);
*p02reN = p02re.r.lo32 << loShift;
*p02imN = p02im.r.lo32 << loShift;
return -(loShift + 2*FBITS_OUT_QMFA);
} else if (n < 32 + 30) {
loShift = (n - 30);
hiShift = 32 - loShift;
*p02reN = (p02re.r.hi32 << hiShift) | (p02re.r.lo32 >> loShift);
*p02imN = (p02im.r.hi32 << hiShift) | (p02im.r.lo32 >> loShift);
return (loShift - 2*FBITS_OUT_QMFA);
} else {
hiShift = n - (32 + 30);
*p02reN = p02re.r.hi32 >> hiShift;
*p02imN = p02im.r.hi32 >> hiShift;
return (32 - 2*FBITS_OUT_QMFA - hiShift);
}
return 0;
}
/**************************************************************************************
* Function: CalcLPCoefs
*
* Description: calculate linear prediction coefficients for one subband (4.6.18.6.2)
*
* Inputs: buffer of low-freq samples, starting at time index = 0,
* freq index = patch subband
* number of guard bits in input sample buffer
*
* Outputs: complex LP coefficients a0re, a0im, a1re, a1im, format = Q29
*
* Return: none
*
* Notes: output coefficients (a0re, a0im, a1re, a1im) clipped to range (-4, 4)
* if the comples coefficients have magnitude >= 4.0, they are all
* set to 0 (see spec)
**************************************************************************************/
static void CalcLPCoefs(int *XBuf, int *a0re, int *a0im, int *a1re, int *a1im, int gb)
{
int zFlag, n1, n2, nd, d, dInv, tre, tim;
int p01re, p01im, p02re, p02im, p12re, p12im, p11re, p22re;
/* pre-scale to avoid overflow - probably never happens in practice (see QMFA)
* max bit growth per accumulator = 38*2 = 76 mul-adds (X * X)
* using 64-bit MADD, so if X has n guard bits, X*X has 2n+1 guard bits
* gain 1 extra sign bit per multiply, so ensure ceil(log2(76/2) / 2) = 3 guard bits on inputs
*/
if (gb < 3) {
nd = 3 - gb;
for (n1 = (NUM_TIME_SLOTS*SAMPLES_PER_SLOT + 6 + 2); n1 != 0; n1--) {
XBuf[0] >>= nd; XBuf[1] >>= nd;
XBuf += (2*64);
}
XBuf -= (2*64*(NUM_TIME_SLOTS*SAMPLES_PER_SLOT + 6 + 2));
}
/* calculate covariance elements */
n1 = CalcCovariance1(XBuf, &p01re, &p01im, &p12re, &p12im, &p11re, &p22re);
n2 = CalcCovariance2(XBuf, &p02re, &p02im);
/* normalize everything to larger power of 2 scalefactor, call it n1 */
if (n1 < n2) {
nd = MIN(n2 - n1, 31);
p01re >>= nd; p01im >>= nd;
p12re >>= nd; p12im >>= nd;
p11re >>= nd; p22re >>= nd;
n1 = n2;
} else if (n1 > n2) {
nd = MIN(n1 - n2, 31);
p02re >>= nd; p02im >>= nd;
}
/* calculate determinant of covariance matrix (at least 1 GB in pXX) */
d = MULSHIFT32(p12re, p12re) + MULSHIFT32(p12im, p12im);
d = MULSHIFT32(d, RELAX_COEF) << 1;
d = MULSHIFT32(p11re, p22re) - d;
ASSERT(d >= 0); /* should never be < 0 */
zFlag = 0;
*a0re = *a0im = 0;
*a1re = *a1im = 0;
if (d > 0) {
/* input = Q31 d = Q(-2*n1 - 32 + nd) = Q31 * 2^(31 + 2*n1 + 32 - nd)
* inverse = Q29 dInv = Q29 * 2^(-31 - 2*n1 - 32 + nd) = Q(29 + 31 + 2*n1 + 32 - nd)
*
* numerator has same Q format as d, since it's sum of normalized squares
* so num * inverse = Q(-2*n1 - 32) * Q(29 + 31 + 2*n1 + 32 - nd)
* = Q(29 + 31 - nd), drop low 32 in MULSHIFT32
* = Q(29 + 31 - 32 - nd) = Q(28 - nd)
*/
nd = CLZ(d) - 1;
d <<= nd;
dInv = InvRNormalized(d);
/* 1 GB in pXX */
tre = MULSHIFT32(p01re, p12re) - MULSHIFT32(p01im, p12im) - MULSHIFT32(p02re, p11re);
tre = MULSHIFT32(tre, dInv);
tim = MULSHIFT32(p01re, p12im) + MULSHIFT32(p01im, p12re) - MULSHIFT32(p02im, p11re);
tim = MULSHIFT32(tim, dInv);
/* if d is extremely small, just set coefs to 0 (would have poor precision anyway) */
if (nd > 28 || (FASTABS(tre) >> (28 - nd)) >= 4 || (FASTABS(tim) >> (28 - nd)) >= 4) {
zFlag = 1;
} else {
*a1re = tre << (FBITS_LPCOEFS - 28 + nd); /* i.e. convert Q(28 - nd) to Q(29) */
*a1im = tim << (FBITS_LPCOEFS - 28 + nd);
}
}
if (p11re) {
/* input = Q31 p11re = Q(-n1 + nd) = Q31 * 2^(31 + n1 - nd)
* inverse = Q29 dInv = Q29 * 2^(-31 - n1 + nd) = Q(29 + 31 + n1 - nd)
*
* numerator is Q(-n1 - 3)
* so num * inverse = Q(-n1 - 3) * Q(29 + 31 + n1 - nd)
* = Q(29 + 31 - 3 - nd), drop low 32 in MULSHIFT32
* = Q(29 + 31 - 3 - 32 - nd) = Q(25 - nd)
*/
nd = CLZ(p11re) - 1; /* assume positive */
p11re <<= nd;
dInv = InvRNormalized(p11re);
/* a1re, a1im = Q29, so scaled by (n1 + 3) */
tre = (p01re >> 3) + MULSHIFT32(p12re, *a1re) + MULSHIFT32(p12im, *a1im);
tre = -MULSHIFT32(tre, dInv);
tim = (p01im >> 3) - MULSHIFT32(p12im, *a1re) + MULSHIFT32(p12re, *a1im);
tim = -MULSHIFT32(tim, dInv);
if (nd > 25 || (FASTABS(tre) >> (25 - nd)) >= 4 || (FASTABS(tim) >> (25 - nd)) >= 4) {
zFlag = 1;
} else {
*a0re = tre << (FBITS_LPCOEFS - 25 + nd); /* i.e. convert Q(25 - nd) to Q(29) */
*a0im = tim << (FBITS_LPCOEFS - 25 + nd);
}
}
/* see 4.6.18.6.2 - if magnitude of a0 or a1 >= 4 then a0 = a1 = 0
* i.e. a0re < 4, a0im < 4, a1re < 4, a1im < 4
* Q29*Q29 = Q26
*/
if (zFlag || MULSHIFT32(*a0re, *a0re) + MULSHIFT32(*a0im, *a0im) >= MAG_16 || MULSHIFT32(*a1re, *a1re) + MULSHIFT32(*a1im, *a1im) >= MAG_16) {
*a0re = *a0im = 0;
*a1re = *a1im = 0;
}
/* no need to clip - we never changed the XBuf data, just used it to calculate a0 and a1 */
if (gb < 3) {
nd = 3 - gb;
for (n1 = (NUM_TIME_SLOTS*SAMPLES_PER_SLOT + 6 + 2); n1 != 0; n1--) {
XBuf[0] <<= nd; XBuf[1] <<= nd;
XBuf += (2*64);
}
}
}
/**************************************************************************************
* Function: GenerateHighFreq
*
* Description: generate high frequencies with SBR (4.6.18.6)
*
* Inputs: initialized PSInfoSBR struct
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* initialized SBRChan struct for this channel
* index of current channel (0 for SCE, 0 or 1 for CPE)
*
* Outputs: new high frequency samples starting at frequency kStart
*
* Return: none
**************************************************************************************/
void GenerateHighFreq(PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch)
{
int band, newBW, c, t, gb, gbMask, gbIdx;
int currPatch, p, x, k, g, i, iStart, iEnd, bw, bwsq;
int a0re, a0im, a1re, a1im;
int x1re, x1im, x2re, x2im;
int ACCre, ACCim;
int *XBufLo, *XBufHi;
/* calculate array of chirp factors */
for (band = 0; band < sbrFreq->numNoiseFloorBands; band++) {
c = sbrChan->chirpFact[band]; /* previous (bwArray') */
newBW = newBWTab[sbrChan->invfMode[0][band]][sbrChan->invfMode[1][band]];
/* weighted average of new and old (can't overflow - total gain = 1.0) */
if (newBW < c)
t = MULSHIFT32(newBW, 0x60000000) + MULSHIFT32(0x20000000, c); /* new is smaller: 0.75*new + 0.25*old */
else
t = MULSHIFT32(newBW, 0x74000000) + MULSHIFT32(0x0c000000, c); /* new is larger: 0.90625*new + 0.09375*old */
t <<= 1;
if (t < 0x02000000) /* below 0.015625, clip to 0 */
t = 0;
if (t > 0x7f800000) /* clip to 0.99609375 */
t = 0x7f800000;
/* save curr as prev for next time */
sbrChan->chirpFact[band] = t;
sbrChan->invfMode[0][band] = sbrChan->invfMode[1][band];
}
iStart = sbrGrid->envTimeBorder[0] + HF_ADJ;
iEnd = sbrGrid->envTimeBorder[sbrGrid->numEnv] + HF_ADJ;
/* generate new high freqs from low freqs, patches, and chirp factors */
k = sbrFreq->kStart;
g = 0;
bw = sbrChan->chirpFact[g];
bwsq = MULSHIFT32(bw, bw) << 1;
gbMask = (sbrChan->gbMask[0] | sbrChan->gbMask[1]); /* older 32 | newer 8 */
gb = CLZ(gbMask) - 1;
for (currPatch = 0; currPatch < sbrFreq->numPatches; currPatch++) {
for (x = 0; x < sbrFreq->patchNumSubbands[currPatch]; x++) {
/* map k to corresponding noise floor band */
if (k >= sbrFreq->freqNoise[g+1]) {
g++;
bw = sbrChan->chirpFact[g]; /* Q31 */
bwsq = MULSHIFT32(bw, bw) << 1; /* Q31 */
}
p = sbrFreq->patchStartSubband[currPatch] + x; /* low QMF band */
XBufHi = psi->XBuf[iStart][k];
if (bw) {
CalcLPCoefs(psi->XBuf[0][p], &a0re, &a0im, &a1re, &a1im, gb);
a0re = MULSHIFT32(bw, a0re); /* Q31 * Q29 = Q28 */
a0im = MULSHIFT32(bw, a0im);
a1re = MULSHIFT32(bwsq, a1re);
a1im = MULSHIFT32(bwsq, a1im);
XBufLo = psi->XBuf[iStart-2][p];
x2re = XBufLo[0]; /* RE{XBuf[n-2]} */
x2im = XBufLo[1]; /* IM{XBuf[n-2]} */
XBufLo += (64*2);
x1re = XBufLo[0]; /* RE{XBuf[n-1]} */
x1im = XBufLo[1]; /* IM{XBuf[n-1]} */
XBufLo += (64*2);
for (i = iStart; i < iEnd; i++) {
/* a0re/im, a1re/im are Q28 with at least 1 GB,
* so the summing for AACre/im is fine (1 GB in, plus 1 from MULSHIFT32)
*/
ACCre = MULSHIFT32(x2re, a1re) - MULSHIFT32(x2im, a1im);
ACCim = MULSHIFT32(x2re, a1im) + MULSHIFT32(x2im, a1re);
x2re = x1re;
x2im = x1im;
ACCre += MULSHIFT32(x1re, a0re) - MULSHIFT32(x1im, a0im);
ACCim += MULSHIFT32(x1re, a0im) + MULSHIFT32(x1im, a0re);
x1re = XBufLo[0]; /* RE{XBuf[n]} */
x1im = XBufLo[1]; /* IM{XBuf[n]} */
XBufLo += (64*2);
/* lost 4 fbits when scaling by a0re/im, a1re/im (Q28) */
CLIP_2N_SHIFT30(ACCre, 4);
ACCre += x1re;
CLIP_2N_SHIFT30(ACCim, 4);
ACCim += x1im;
XBufHi[0] = ACCre;
XBufHi[1] = ACCim;
XBufHi += (64*2);
/* update guard bit masks */
gbMask = FASTABS(ACCre);
gbMask |= FASTABS(ACCim);
gbIdx = (i >> 5) & 0x01; /* 0 if i < 32, 1 if i >= 32 */
sbrChan->gbMask[gbIdx] |= gbMask;
}
} else {
XBufLo = (int *)psi->XBuf[iStart][p];
for (i = iStart; i < iEnd; i++) {
XBufHi[0] = XBufLo[0];
XBufHi[1] = XBufLo[1];
XBufLo += (64*2);
XBufHi += (64*2);
}
}
k++; /* high QMF band */
}
}
}
|
1137519-player
|
aac/sbrhfgen.c
|
C
|
lgpl
| 22,355
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbrqmf.c,v 1.2 2005/05/19 20:45:20 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbrqmf.c - analysis and synthesis QMF filters for SBR
**************************************************************************************/
#include "sbr.h"
#include "assembly.h"
/* PreMultiply64() table
* format = Q30
* reordered for sequential access
*
* for (i = 0; i < 64/4; i++) {
* angle = (i + 0.25) * M_PI / nmdct;
* x = (cos(angle) + sin(angle));
* x = sin(angle);
*
* angle = (nmdct/2 - 1 - i + 0.25) * M_PI / nmdct;
* x = (cos(angle) + sin(angle));
* x = sin(angle);
* }
*/
static const int cos4sin4tab64[64] = {
0x40c7d2bd, 0x00c90e90, 0x424ff28f, 0x3ff4e5e0, 0x43cdd89a, 0x03ecadcf, 0x454149fc, 0x3fc395f9,
0x46aa0d6d, 0x070de172, 0x4807eb4b, 0x3f6af2e3, 0x495aada2, 0x0a2abb59, 0x4aa22036, 0x3eeb3347,
0x4bde1089, 0x0d415013, 0x4d0e4de2, 0x3e44a5ef, 0x4e32a956, 0x104fb80e, 0x4f4af5d1, 0x3d77b192,
0x50570819, 0x135410c3, 0x5156b6d9, 0x3c84d496, 0x5249daa2, 0x164c7ddd, 0x53304df6, 0x3b6ca4c4,
0x5409ed4b, 0x19372a64, 0x54d69714, 0x3a2fcee8, 0x55962bc0, 0x1c1249d8, 0x56488dc5, 0x38cf1669,
0x56eda1a0, 0x1edc1953, 0x57854ddd, 0x374b54ce, 0x580f7b19, 0x2192e09b, 0x588c1404, 0x35a5793c,
0x58fb0568, 0x2434f332, 0x595c3e2a, 0x33de87de, 0x59afaf4c, 0x26c0b162, 0x59f54bee, 0x31f79948,
0x5a2d0957, 0x29348937, 0x5a56deec, 0x2ff1d9c7, 0x5a72c63b, 0x2b8ef77d, 0x5a80baf6, 0x2dce88aa,
};
/* PostMultiply64() table
* format = Q30
* reordered for sequential access
*
* for (i = 0; i <= (32/2); i++) {
* angle = i * M_PI / 64;
* x = (cos(angle) + sin(angle));
* x = sin(angle);
* }
*/
static const int cos1sin1tab64[34] = {
0x40000000, 0x00000000, 0x43103085, 0x0323ecbe, 0x45f704f7, 0x0645e9af, 0x48b2b335, 0x09640837,
0x4b418bbe, 0x0c7c5c1e, 0x4da1fab5, 0x0f8cfcbe, 0x4fd288dc, 0x1294062f, 0x51d1dc80, 0x158f9a76,
0x539eba45, 0x187de2a7, 0x553805f2, 0x1b5d100a, 0x569cc31b, 0x1e2b5d38, 0x57cc15bc, 0x20e70f32,
0x58c542c5, 0x238e7673, 0x5987b08a, 0x261feffa, 0x5a12e720, 0x2899e64a, 0x5a6690ae, 0x2afad269,
0x5a82799a, 0x2d413ccd,
};
/**************************************************************************************
* Function: PreMultiply64
*
* Description: pre-twiddle stage of 64-point DCT-IV
*
* Inputs: buffer of 64 samples
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: minimum 1 GB in, 2 GB out, gains 2 int bits
* gbOut = gbIn + 1
* output is limited to sqrt(2)/2 plus GB in full GB
* uses 3-mul, 3-add butterflies instead of 4-mul, 2-add
**************************************************************************************/
static void PreMultiply64(int *zbuf1)
{
int i, ar1, ai1, ar2, ai2, z1, z2;
int t, cms2, cps2a, sin2a, cps2b, sin2b;
int *zbuf2;
const int *csptr;
zbuf2 = zbuf1 + 64 - 1;
csptr = cos4sin4tab64;
/* whole thing should fit in registers - verify that compiler does this */
for (i = 64 >> 2; i != 0; i--) {
/* cps2 = (cos+sin), sin2 = sin, cms2 = (cos-sin) */
cps2a = *csptr++;
sin2a = *csptr++;
cps2b = *csptr++;
sin2b = *csptr++;
ar1 = *(zbuf1 + 0);
ai2 = *(zbuf1 + 1);
ai1 = *(zbuf2 + 0);
ar2 = *(zbuf2 - 1);
/* gain 2 ints bit from MULSHIFT32 by Q30
* max per-sample gain (ignoring implicit scaling) = MAX(sin(angle)+cos(angle)) = 1.414
* i.e. gain 1 GB since worst case is sin(angle) = cos(angle) = 0.707 (Q30), gain 2 from
* extra sign bits, and eat one in adding
*/
t = MULSHIFT32(sin2a, ar1 + ai1);
z2 = MULSHIFT32(cps2a, ai1) - t;
cms2 = cps2a - 2*sin2a;
z1 = MULSHIFT32(cms2, ar1) + t;
*zbuf1++ = z1; /* cos*ar1 + sin*ai1 */
*zbuf1++ = z2; /* cos*ai1 - sin*ar1 */
t = MULSHIFT32(sin2b, ar2 + ai2);
z2 = MULSHIFT32(cps2b, ai2) - t;
cms2 = cps2b - 2*sin2b;
z1 = MULSHIFT32(cms2, ar2) + t;
*zbuf2-- = z2; /* cos*ai2 - sin*ar2 */
*zbuf2-- = z1; /* cos*ar2 + sin*ai2 */
}
}
/**************************************************************************************
* Function: PostMultiply64
*
* Description: post-twiddle stage of 64-point type-IV DCT
*
* Inputs: buffer of 64 samples
* number of output samples to calculate
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: minimum 1 GB in, 2 GB out, gains 2 int bits
* gbOut = gbIn + 1
* output is limited to sqrt(2)/2 plus GB in full GB
* nSampsOut is rounded up to next multiple of 4, since we calculate
* 4 samples per loop
**************************************************************************************/
static void PostMultiply64(int *fft1, int nSampsOut)
{
int i, ar1, ai1, ar2, ai2;
int t, cms2, cps2, sin2;
int *fft2;
const int *csptr;
csptr = cos1sin1tab64;
fft2 = fft1 + 64 - 1;
/* load coeffs for first pass
* cps2 = (cos+sin)/2, sin2 = sin/2, cms2 = (cos-sin)/2
*/
cps2 = *csptr++;
sin2 = *csptr++;
cms2 = cps2 - 2*sin2;
for (i = (nSampsOut + 3) >> 2; i != 0; i--) {
ar1 = *(fft1 + 0);
ai1 = *(fft1 + 1);
ar2 = *(fft2 - 1);
ai2 = *(fft2 + 0);
/* gain 2 int bits (multiplying by Q30), max gain = sqrt(2) */
t = MULSHIFT32(sin2, ar1 + ai1);
*fft2-- = t - MULSHIFT32(cps2, ai1);
*fft1++ = t + MULSHIFT32(cms2, ar1);
cps2 = *csptr++;
sin2 = *csptr++;
ai2 = -ai2;
t = MULSHIFT32(sin2, ar2 + ai2);
*fft2-- = t - MULSHIFT32(cps2, ai2);
cms2 = cps2 - 2*sin2;
*fft1++ = t + MULSHIFT32(cms2, ar2);
}
}
/**************************************************************************************
* Function: QMFAnalysisConv
*
* Description: convolution kernel for analysis QMF
*
* Inputs: pointer to coefficient table, reordered for sequential access
* delay buffer of size 32*10 = 320 real-valued PCM samples
* index for delay ring buffer (range = [0, 9])
*
* Outputs: 64 consecutive 32-bit samples
*
* Return: none
*
* Notes: this is carefully written to be efficient on ARM
* use the assembly code version in sbrqmfak.s when building for ARM!
**************************************************************************************/
#if (defined (__arm) && defined (__ARMCC_VERSION)) || (defined (_WIN32) && defined (_WIN32_WCE) && defined (ARM)) || (defined(__GNUC__) && defined(__arm__))
#ifdef __cplusplus
extern "C"
#endif
void QMFAnalysisConv(int *cTab, int *delay, int dIdx, int *uBuf);
#else
void QMFAnalysisConv(int *cTab, int *delay, int dIdx, int *uBuf)
{
int k, dOff;
int *cPtr0, *cPtr1;
U64 u64lo, u64hi;
dOff = dIdx*32 + 31;
cPtr0 = cTab;
cPtr1 = cTab + 33*5 - 1;
/* special first pass since we need to flip sign to create cTab[384], cTab[512] */
u64lo.w64 = 0;
u64hi.w64 = 0;
u64lo.w64 = MADD64(u64lo.w64, *cPtr0++, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64hi.w64 = MADD64(u64hi.w64, *cPtr0++, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64lo.w64 = MADD64(u64lo.w64, *cPtr0++, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64hi.w64 = MADD64(u64hi.w64, *cPtr0++, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64lo.w64 = MADD64(u64lo.w64, *cPtr0++, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64hi.w64 = MADD64(u64hi.w64, *cPtr1--, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64lo.w64 = MADD64(u64lo.w64, -(*cPtr1--), delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64hi.w64 = MADD64(u64hi.w64, *cPtr1--, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64lo.w64 = MADD64(u64lo.w64, -(*cPtr1--), delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64hi.w64 = MADD64(u64hi.w64, *cPtr1--, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
uBuf[0] = u64lo.r.hi32;
uBuf[32] = u64hi.r.hi32;
uBuf++;
dOff--;
/* max gain for any sample in uBuf, after scaling by cTab, ~= 0.99
* so we can just sum the uBuf values with no overflow problems
*/
for (k = 1; k <= 31; k++) {
u64lo.w64 = 0;
u64hi.w64 = 0;
u64lo.w64 = MADD64(u64lo.w64, *cPtr0++, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64hi.w64 = MADD64(u64hi.w64, *cPtr0++, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64lo.w64 = MADD64(u64lo.w64, *cPtr0++, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64hi.w64 = MADD64(u64hi.w64, *cPtr0++, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64lo.w64 = MADD64(u64lo.w64, *cPtr0++, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64hi.w64 = MADD64(u64hi.w64, *cPtr1--, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64lo.w64 = MADD64(u64lo.w64, *cPtr1--, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64hi.w64 = MADD64(u64hi.w64, *cPtr1--, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64lo.w64 = MADD64(u64lo.w64, *cPtr1--, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
u64hi.w64 = MADD64(u64hi.w64, *cPtr1--, delay[dOff]); dOff -= 32; if (dOff < 0) {dOff += 320;}
uBuf[0] = u64lo.r.hi32;
uBuf[32] = u64hi.r.hi32;
uBuf++;
dOff--;
}
}
#endif
/**************************************************************************************
* Function: QMFAnalysis
*
* Description: 32-subband analysis QMF (4.6.18.4.1)
*
* Inputs: 32 consecutive samples of decoded 32-bit PCM, format = Q(fBitsIn)
* delay buffer of size 32*10 = 320 PCM samples
* number of fraction bits in input PCM
* index for delay ring buffer (range = [0, 9])
* number of subbands to calculate (range = [0, 32])
*
* Outputs: qmfaBands complex subband samples, format = Q(FBITS_OUT_QMFA)
* updated delay buffer
* updated delay index
*
* Return: guard bit mask
*
* Notes: output stored as RE{X0}, IM{X0}, RE{X1}, IM{X1}, ... RE{X31}, IM{X31}
* output stored in int buffer of size 64*2 = 128
* (zero-filled from XBuf[2*qmfaBands] to XBuf[127])
**************************************************************************************/
int QMFAnalysis(int *inbuf, int *delay, int *XBuf, int fBitsIn, int *delayIdx, int qmfaBands)
{
int n, y, shift, gbMask;
int *delayPtr, *uBuf, *tBuf;
/* use XBuf[128] as temp buffer for reordering */
uBuf = XBuf; /* first 64 samples */
tBuf = XBuf + 64; /* second 64 samples */
/* overwrite oldest PCM with new PCM
* delay[n] has 1 GB after shifting (either << or >>)
*/
delayPtr = delay + (*delayIdx * 32);
if (fBitsIn > FBITS_IN_QMFA) {
shift = MIN(fBitsIn - FBITS_IN_QMFA, 31);
for (n = 32; n != 0; n--) {
y = (*inbuf) >> shift;
inbuf++;
*delayPtr++ = y;
}
} else {
shift = MIN(FBITS_IN_QMFA - fBitsIn, 30);
for (n = 32; n != 0; n--) {
y = *inbuf++;
CLIP_2N_SHIFT30(y, shift);
*delayPtr++ = y;
}
}
QMFAnalysisConv((int *)cTabA, delay, *delayIdx, uBuf);
/* uBuf has at least 2 GB right now (1 from clipping to Q(FBITS_IN_QMFA), one from
* the scaling by cTab (MULSHIFT32(*delayPtr--, *cPtr++), with net gain of < 1.0)
* TODO - fuse with QMFAnalysisConv to avoid separate reordering
*/
tBuf[2*0 + 0] = uBuf[0];
tBuf[2*0 + 1] = uBuf[1];
for (n = 1; n < 31; n++) {
tBuf[2*n + 0] = -uBuf[64-n];
tBuf[2*n + 1] = uBuf[n+1];
}
tBuf[2*31 + 1] = uBuf[32];
tBuf[2*31 + 0] = -uBuf[33];
/* fast in-place DCT-IV - only need 2*qmfaBands output samples */
PreMultiply64(tBuf); /* 2 GB in, 3 GB out */
FFT32C(tBuf); /* 3 GB in, 1 GB out */
PostMultiply64(tBuf, qmfaBands*2); /* 1 GB in, 2 GB out */
/* TODO - roll into PostMultiply (if enough registers) */
gbMask = 0;
for (n = 0; n < qmfaBands; n++) {
XBuf[2*n+0] = tBuf[ n + 0]; /* implicit scaling of 2 in our output Q format */
gbMask |= FASTABS(XBuf[2*n+0]);
XBuf[2*n+1] = -tBuf[63 - n];
gbMask |= FASTABS(XBuf[2*n+1]);
}
/* fill top section with zeros for HF generation */
for ( ; n < 64; n++) {
XBuf[2*n+0] = 0;
XBuf[2*n+1] = 0;
}
*delayIdx = (*delayIdx == NUM_QMF_DELAY_BUFS - 1 ? 0 : *delayIdx + 1);
/* minimum of 2 GB in output */
return gbMask;
}
/* lose FBITS_LOST_DCT4_64 in DCT4, gain 6 for implicit scaling by 1/64, lose 1 for cTab multiply (Q31) */
#define FBITS_OUT_QMFS (FBITS_IN_QMFS - FBITS_LOST_DCT4_64 + 6 - 1)
#define RND_VAL (1 << (FBITS_OUT_QMFS-1))
/**************************************************************************************
* Function: QMFSynthesisConv
*
* Description: final convolution kernel for synthesis QMF
*
* Inputs: pointer to coefficient table, reordered for sequential access
* delay buffer of size 64*10 = 640 complex samples (1280 ints)
* index for delay ring buffer (range = [0, 9])
* number of QMF subbands to process (range = [0, 64])
* number of channels
*
* Outputs: 64 consecutive 16-bit PCM samples, interleaved by factor of nChans
*
* Return: none
*
* Notes: this is carefully written to be efficient on ARM
* use the assembly code version in sbrqmfsk.s when building for ARM!
**************************************************************************************/
#if (defined (__arm) && defined (__ARMCC_VERSION)) || (defined (_WIN32) && defined (_WIN32_WCE) && defined (ARM)) || (defined(__GNUC__) && defined(__arm__))
#ifdef __cplusplus
extern "C"
#endif
void QMFSynthesisConv(int *cPtr, int *delay, int dIdx, short *outbuf, int nChans);
#else
void QMFSynthesisConv(int *cPtr, int *delay, int dIdx, short *outbuf, int nChans)
{
int k, dOff0, dOff1;
U64 sum64;
dOff0 = (dIdx)*128;
dOff1 = dOff0 - 1;
if (dOff1 < 0)
dOff1 += 1280;
/* scaling note: total gain of coefs (cPtr[0]-cPtr[9] for any k) is < 2.0, so 1 GB in delay values is adequate */
for (k = 0; k <= 63; k++) {
sum64.w64 = 0;
sum64.w64 = MADD64(sum64.w64, *cPtr++, delay[dOff0]); dOff0 -= 256; if (dOff0 < 0) {dOff0 += 1280;}
sum64.w64 = MADD64(sum64.w64, *cPtr++, delay[dOff1]); dOff1 -= 256; if (dOff1 < 0) {dOff1 += 1280;}
sum64.w64 = MADD64(sum64.w64, *cPtr++, delay[dOff0]); dOff0 -= 256; if (dOff0 < 0) {dOff0 += 1280;}
sum64.w64 = MADD64(sum64.w64, *cPtr++, delay[dOff1]); dOff1 -= 256; if (dOff1 < 0) {dOff1 += 1280;}
sum64.w64 = MADD64(sum64.w64, *cPtr++, delay[dOff0]); dOff0 -= 256; if (dOff0 < 0) {dOff0 += 1280;}
sum64.w64 = MADD64(sum64.w64, *cPtr++, delay[dOff1]); dOff1 -= 256; if (dOff1 < 0) {dOff1 += 1280;}
sum64.w64 = MADD64(sum64.w64, *cPtr++, delay[dOff0]); dOff0 -= 256; if (dOff0 < 0) {dOff0 += 1280;}
sum64.w64 = MADD64(sum64.w64, *cPtr++, delay[dOff1]); dOff1 -= 256; if (dOff1 < 0) {dOff1 += 1280;}
sum64.w64 = MADD64(sum64.w64, *cPtr++, delay[dOff0]); dOff0 -= 256; if (dOff0 < 0) {dOff0 += 1280;}
sum64.w64 = MADD64(sum64.w64, *cPtr++, delay[dOff1]); dOff1 -= 256; if (dOff1 < 0) {dOff1 += 1280;}
dOff0++;
dOff1--;
*outbuf = CLIPTOSHORT((sum64.r.hi32 + RND_VAL) >> FBITS_OUT_QMFS);
outbuf += nChans;
}
}
#endif
/**************************************************************************************
* Function: QMFSynthesis
*
* Description: 64-subband synthesis QMF (4.6.18.4.2)
*
* Inputs: 64 consecutive complex subband QMF samples, format = Q(FBITS_IN_QMFS)
* delay buffer of size 64*10 = 640 complex samples (1280 ints)
* index for delay ring buffer (range = [0, 9])
* number of QMF subbands to process (range = [0, 64])
* number of channels
*
* Outputs: 64 consecutive 16-bit PCM samples, interleaved by factor of nChans
* updated delay buffer
* updated delay index
*
* Return: none
*
* Notes: assumes MIN_GBITS_IN_QMFS guard bits in input, either from
* QMFAnalysis (if upsampling only) or from MapHF (if SBR on)
**************************************************************************************/
void QMFSynthesis(int *inbuf, int *delay, int *delayIdx, int qmfsBands, short *outbuf, int nChans)
{
int n, a0, a1, b0, b1, dOff0, dOff1, dIdx;
int *tBufLo, *tBufHi;
dIdx = *delayIdx;
tBufLo = delay + dIdx*128 + 0;
tBufHi = delay + dIdx*128 + 127;
/* reorder inputs to DCT-IV, only use first qmfsBands (complex) samples
* TODO - fuse with PreMultiply64 to avoid separate reordering steps
*/
for (n = 0; n < qmfsBands >> 1; n++) {
a0 = *inbuf++;
b0 = *inbuf++;
a1 = *inbuf++;
b1 = *inbuf++;
*tBufLo++ = a0;
*tBufLo++ = a1;
*tBufHi-- = b0;
*tBufHi-- = b1;
}
if (qmfsBands & 0x01) {
a0 = *inbuf++;
b0 = *inbuf++;
*tBufLo++ = a0;
*tBufHi-- = b0;
*tBufLo++ = 0;
*tBufHi-- = 0;
n++;
}
for ( ; n < 32; n++) {
*tBufLo++ = 0;
*tBufHi-- = 0;
*tBufLo++ = 0;
*tBufHi-- = 0;
}
tBufLo = delay + dIdx*128 + 0;
tBufHi = delay + dIdx*128 + 64;
/* 2 GB in, 3 GB out */
PreMultiply64(tBufLo);
PreMultiply64(tBufHi);
/* 3 GB in, 1 GB out */
FFT32C(tBufLo);
FFT32C(tBufHi);
/* 1 GB in, 2 GB out */
PostMultiply64(tBufLo, 64);
PostMultiply64(tBufHi, 64);
/* could fuse with PostMultiply64 to avoid separate pass */
dOff0 = dIdx*128;
dOff1 = dIdx*128 + 64;
for (n = 32; n != 0; n--) {
a0 = (*tBufLo++);
a1 = (*tBufLo++);
b0 = (*tBufHi++);
b1 = -(*tBufHi++);
delay[dOff0++] = (b0 - a0);
delay[dOff0++] = (b1 - a1);
delay[dOff1++] = (b0 + a0);
delay[dOff1++] = (b1 + a1);
}
QMFSynthesisConv((int *)cTabS, delay, dIdx, outbuf, nChans);
*delayIdx = (*delayIdx == NUM_QMF_DELAY_BUFS - 1 ? 0 : *delayIdx + 1);
}
|
1137519-player
|
aac/sbrqmf.c
|
C
|
lgpl
| 19,430
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: trigtabs.c,v 1.1 2005/02/26 01:47:35 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com), Ken Cooke (kenc@real.com)
* February 2005
*
* trigtabs.c - tables of sin, cos, etc. for IMDCT
**************************************************************************************/
#include "coder.h"
const int cos4sin4tabOffset[NUM_IMDCT_SIZES] = {0, 128};
/* PreMultiply() tables
* format = Q30 * 2^[-7, -10] for nmdct = [128, 1024]
* reordered for sequential access
*
* invM = -1.0 / nmdct;
* for (i = 0; i < nmdct/4; i++) {
* angle = (i + 0.25) * M_PI / nmdct;
* x = invM * (cos(angle) + sin(angle));
* x = invM * sin(angle);
*
* angle = (nmdct/2 - 1 - i + 0.25) * M_PI / nmdct;
* x = invM * (cos(angle) + sin(angle));
* x = invM * sin(angle);
* }
*/
const int cos4sin4tab[128 + 1024] = {
/* 128 - format = Q30 * 2^-7 */
0xbf9bc731, 0xff9b783c, 0xbed5332c, 0xc002c697, 0xbe112251, 0xfe096c8d, 0xbd4f9c30, 0xc00f1c4a,
0xbc90a83f, 0xfc77ae5e, 0xbbd44dd9, 0xc0254e27, 0xbb1a9443, 0xfae67ba2, 0xba6382a6, 0xc04558c0,
0xb9af200f, 0xf9561237, 0xb8fd7373, 0xc06f3726, 0xb84e83ac, 0xf7c6afdc, 0xb7a25779, 0xc0a2e2e3,
0xb6f8f57c, 0xf6389228, 0xb652643e, 0xc0e05401, 0xb5aeaa2a, 0xf4abf67e, 0xb50dcd90, 0xc1278104,
0xb46fd4a4, 0xf3211a07, 0xb3d4c57c, 0xc1785ef4, 0xb33ca614, 0xf19839a6, 0xb2a77c49, 0xc1d2e158,
0xb2154dda, 0xf01191f3, 0xb186206b, 0xc236fa3b, 0xb0f9f981, 0xee8d5f29, 0xb070de82, 0xc2a49a2e,
0xafead4b9, 0xed0bdd25, 0xaf67e14f, 0xc31bb049, 0xaee80952, 0xeb8d475b, 0xae6b51ae, 0xc39c2a2f,
0xadf1bf34, 0xea11d8c8, 0xad7b5692, 0xc425f410, 0xad081c5a, 0xe899cbf1, 0xac9814fd, 0xc4b8f8ad,
0xac2b44cc, 0xe7255ad1, 0xabc1aff9, 0xc555215a, 0xab5b5a96, 0xe5b4bed8, 0xaaf84896, 0xc5fa5603,
0xaa987dca, 0xe44830dd, 0xaa3bfde3, 0xc6a87d2d, 0xa9e2cc73, 0xe2dfe917, 0xa98cece9, 0xc75f7bfe,
0xa93a6296, 0xe17c1f15, 0xa8eb30a7, 0xc81f363d, 0xa89f5a2b, 0xe01d09b4, 0xa856e20e, 0xc8e78e5b,
0xa811cb1b, 0xdec2df18, 0xa7d017fc, 0xc9b86572, 0xa791cb39, 0xdd6dd4a2, 0xa756e73a, 0xca919b4e,
0xa71f6e43, 0xdc1e1ee9, 0xa6eb6279, 0xcb730e70, 0xa6bac5dc, 0xdad3f1b1, 0xa68d9a4c, 0xcc5c9c14,
0xa663e188, 0xd98f7fe6, 0xa63d9d2b, 0xcd4e2037, 0xa61aceaf, 0xd850fb8e, 0xa5fb776b, 0xce47759a,
0xa5df9894, 0xd71895c9, 0xa5c7333e, 0xcf4875ca, 0xa5b2485a, 0xd5e67ec1, 0xa5a0d8b5, 0xd050f926,
0xa592e4fd, 0xd4bae5ab, 0xa5886dba, 0xd160d6e5, 0xa5817354, 0xd395f8ba, 0xa57df60f, 0xd277e518,
/* 1024 - format = Q30 * 2^-10 */
0xbff3703e, 0xfff36f02, 0xbfda5824, 0xc0000b1a, 0xbfc149ed, 0xffc12b16, 0xbfa845a0, 0xc0003c74,
0xbf8f4b3e, 0xff8ee750, 0xbf765acc, 0xc0009547, 0xbf5d744e, 0xff5ca3d0, 0xbf4497c8, 0xc0011594,
0xbf2bc53d, 0xff2a60b4, 0xbf12fcb2, 0xc001bd5c, 0xbefa3e2a, 0xfef81e1d, 0xbee189a8, 0xc0028c9c,
0xbec8df32, 0xfec5dc28, 0xbeb03eca, 0xc0038356, 0xbe97a875, 0xfe939af5, 0xbe7f1c36, 0xc004a188,
0xbe669a10, 0xfe615aa3, 0xbe4e2209, 0xc005e731, 0xbe35b423, 0xfe2f1b50, 0xbe1d5062, 0xc0075452,
0xbe04f6cb, 0xfdfcdd1d, 0xbdeca760, 0xc008e8e8, 0xbdd46225, 0xfdcaa027, 0xbdbc2720, 0xc00aa4f3,
0xbda3f652, 0xfd98648d, 0xbd8bcfbf, 0xc00c8872, 0xbd73b36d, 0xfd662a70, 0xbd5ba15d, 0xc00e9364,
0xbd439995, 0xfd33f1ed, 0xbd2b9c17, 0xc010c5c7, 0xbd13a8e7, 0xfd01bb24, 0xbcfbc00a, 0xc0131f9b,
0xbce3e182, 0xfccf8634, 0xbccc0d53, 0xc015a0dd, 0xbcb44382, 0xfc9d533b, 0xbc9c8411, 0xc018498c,
0xbc84cf05, 0xfc6b2259, 0xbc6d2461, 0xc01b19a7, 0xbc558428, 0xfc38f3ac, 0xbc3dee5f, 0xc01e112b,
0xbc266309, 0xfc06c754, 0xbc0ee22a, 0xc0213018, 0xbbf76bc4, 0xfbd49d70, 0xbbdfffdd, 0xc024766a,
0xbbc89e77, 0xfba2761e, 0xbbb14796, 0xc027e421, 0xbb99fb3e, 0xfb70517d, 0xbb82b972, 0xc02b7939,
0xbb6b8235, 0xfb3e2fac, 0xbb54558d, 0xc02f35b1, 0xbb3d337b, 0xfb0c10cb, 0xbb261c04, 0xc0331986,
0xbb0f0f2b, 0xfad9f4f8, 0xbaf80cf4, 0xc03724b6, 0xbae11561, 0xfaa7dc52, 0xbaca2878, 0xc03b573f,
0xbab3463b, 0xfa75c6f8, 0xba9c6eae, 0xc03fb11d, 0xba85a1d4, 0xfa43b508, 0xba6edfb1, 0xc044324f,
0xba582849, 0xfa11a6a3, 0xba417b9e, 0xc048dad1, 0xba2ad9b5, 0xf9df9be6, 0xba144291, 0xc04daaa1,
0xb9fdb635, 0xf9ad94f0, 0xb9e734a4, 0xc052a1bb, 0xb9d0bde4, 0xf97b91e1, 0xb9ba51f6, 0xc057c01d,
0xb9a3f0de, 0xf94992d7, 0xb98d9aa0, 0xc05d05c3, 0xb9774f3f, 0xf91797f0, 0xb9610ebe, 0xc06272aa,
0xb94ad922, 0xf8e5a14d, 0xb934ae6d, 0xc06806ce, 0xb91e8ea3, 0xf8b3af0c, 0xb90879c7, 0xc06dc22e,
0xb8f26fdc, 0xf881c14b, 0xb8dc70e7, 0xc073a4c3, 0xb8c67cea, 0xf84fd829, 0xb8b093ea, 0xc079ae8c,
0xb89ab5e8, 0xf81df3c5, 0xb884e2e9, 0xc07fdf85, 0xb86f1af0, 0xf7ec143e, 0xb8595e00, 0xc08637a9,
0xb843ac1d, 0xf7ba39b3, 0xb82e0549, 0xc08cb6f5, 0xb818698a, 0xf7886442, 0xb802d8e0, 0xc0935d64,
0xb7ed5351, 0xf756940a, 0xb7d7d8df, 0xc09a2af3, 0xb7c2698e, 0xf724c92a, 0xb7ad0561, 0xc0a11f9d,
0xb797ac5b, 0xf6f303c0, 0xb7825e80, 0xc0a83b5e, 0xb76d1bd2, 0xf6c143ec, 0xb757e455, 0xc0af7e33,
0xb742b80d, 0xf68f89cb, 0xb72d96fd, 0xc0b6e815, 0xb7188127, 0xf65dd57d, 0xb7037690, 0xc0be7901,
0xb6ee773a, 0xf62c2721, 0xb6d98328, 0xc0c630f2, 0xb6c49a5e, 0xf5fa7ed4, 0xb6afbce0, 0xc0ce0fe3,
0xb69aeab0, 0xf5c8dcb6, 0xb68623d1, 0xc0d615cf, 0xb6716847, 0xf59740e5, 0xb65cb815, 0xc0de42b2,
0xb648133e, 0xf565ab80, 0xb63379c5, 0xc0e69686, 0xb61eebae, 0xf5341ca5, 0xb60a68fb, 0xc0ef1147,
0xb5f5f1b1, 0xf5029473, 0xb5e185d1, 0xc0f7b2ee, 0xb5cd255f, 0xf4d11308, 0xb5b8d05f, 0xc1007b77,
0xb5a486d2, 0xf49f9884, 0xb59048be, 0xc1096add, 0xb57c1624, 0xf46e2504, 0xb567ef08, 0xc1128119,
0xb553d36c, 0xf43cb8a7, 0xb53fc355, 0xc11bbe26, 0xb52bbec4, 0xf40b538b, 0xb517c5be, 0xc12521ff,
0xb503d845, 0xf3d9f5cf, 0xb4eff65c, 0xc12eac9d, 0xb4dc2007, 0xf3a89f92, 0xb4c85548, 0xc1385dfb,
0xb4b49622, 0xf37750f2, 0xb4a0e299, 0xc1423613, 0xb48d3ab0, 0xf3460a0d, 0xb4799e69, 0xc14c34df,
0xb4660dc8, 0xf314cb02, 0xb45288cf, 0xc1565a58, 0xb43f0f82, 0xf2e393ef, 0xb42ba1e4, 0xc160a678,
0xb4183ff7, 0xf2b264f2, 0xb404e9bf, 0xc16b193a, 0xb3f19f3e, 0xf2813e2a, 0xb3de6078, 0xc175b296,
0xb3cb2d70, 0xf2501fb5, 0xb3b80628, 0xc1807285, 0xb3a4eaa4, 0xf21f09b1, 0xb391dae6, 0xc18b5903,
0xb37ed6f1, 0xf1edfc3d, 0xb36bdec9, 0xc1966606, 0xb358f26f, 0xf1bcf777, 0xb34611e8, 0xc1a1998a,
0xb3333d36, 0xf18bfb7d, 0xb320745c, 0xc1acf386, 0xb30db75d, 0xf15b086d, 0xb2fb063b, 0xc1b873f5,
0xb2e860fa, 0xf12a1e66, 0xb2d5c79d, 0xc1c41ace, 0xb2c33a26, 0xf0f93d86, 0xb2b0b898, 0xc1cfe80a,
0xb29e42f6, 0xf0c865ea, 0xb28bd943, 0xc1dbdba3, 0xb2797b82, 0xf09797b2, 0xb26729b5, 0xc1e7f591,
0xb254e3e0, 0xf066d2fa, 0xb242aa05, 0xc1f435cc, 0xb2307c27, 0xf03617e2, 0xb21e5a49, 0xc2009c4e,
0xb20c446d, 0xf0056687, 0xb1fa3a97, 0xc20d290d, 0xb1e83cc9, 0xefd4bf08, 0xb1d64b06, 0xc219dc03,
0xb1c46551, 0xefa42181, 0xb1b28bad, 0xc226b528, 0xb1a0be1b, 0xef738e12, 0xb18efca0, 0xc233b473,
0xb17d473d, 0xef4304d8, 0xb16b9df6, 0xc240d9de, 0xb15a00cd, 0xef1285f2, 0xb1486fc5, 0xc24e255e,
0xb136eae1, 0xeee2117c, 0xb1257223, 0xc25b96ee, 0xb114058e, 0xeeb1a796, 0xb102a524, 0xc2692e83,
0xb0f150e9, 0xee81485c, 0xb0e008e0, 0xc276ec16, 0xb0cecd09, 0xee50f3ed, 0xb0bd9d6a, 0xc284cf9f,
0xb0ac7a03, 0xee20aa67, 0xb09b62d8, 0xc292d914, 0xb08a57eb, 0xedf06be6, 0xb079593f, 0xc2a1086d,
0xb06866d7, 0xedc0388a, 0xb05780b5, 0xc2af5da2, 0xb046a6db, 0xed901070, 0xb035d94e, 0xc2bdd8a9,
0xb025180e, 0xed5ff3b5, 0xb014631e, 0xc2cc7979, 0xb003ba82, 0xed2fe277, 0xaff31e3b, 0xc2db400a,
0xafe28e4d, 0xecffdcd4, 0xafd20ab9, 0xc2ea2c53, 0xafc19383, 0xeccfe2ea, 0xafb128ad, 0xc2f93e4a,
0xafa0ca39, 0xec9ff4d6, 0xaf90782a, 0xc30875e5, 0xaf803283, 0xec7012b5, 0xaf6ff945, 0xc317d31c,
0xaf5fcc74, 0xec403ca5, 0xaf4fac12, 0xc32755e5, 0xaf3f9822, 0xec1072c4, 0xaf2f90a5, 0xc336fe37,
0xaf1f959f, 0xebe0b52f, 0xaf0fa712, 0xc346cc07, 0xaeffc500, 0xebb10404, 0xaeefef6c, 0xc356bf4d,
0xaee02658, 0xeb815f60, 0xaed069c7, 0xc366d7fd, 0xaec0b9bb, 0xeb51c760, 0xaeb11636, 0xc377160f,
0xaea17f3b, 0xeb223c22, 0xae91f4cd, 0xc3877978, 0xae8276ed, 0xeaf2bdc3, 0xae73059f, 0xc398022f,
0xae63a0e3, 0xeac34c60, 0xae5448be, 0xc3a8b028, 0xae44fd31, 0xea93e817, 0xae35be3f, 0xc3b9835a,
0xae268be9, 0xea649105, 0xae176633, 0xc3ca7bba, 0xae084d1f, 0xea354746, 0xadf940ae, 0xc3db993e,
0xadea40e4, 0xea060af9, 0xaddb4dc2, 0xc3ecdbdc, 0xadcc674b, 0xe9d6dc3b, 0xadbd8d82, 0xc3fe4388,
0xadaec067, 0xe9a7bb28, 0xad9fffff, 0xc40fd037, 0xad914c4b, 0xe978a7dd, 0xad82a54c, 0xc42181e0,
0xad740b07, 0xe949a278, 0xad657d7c, 0xc4335877, 0xad56fcaf, 0xe91aab16, 0xad4888a0, 0xc44553f2,
0xad3a2153, 0xe8ebc1d3, 0xad2bc6ca, 0xc4577444, 0xad1d7907, 0xe8bce6cd, 0xad0f380c, 0xc469b963,
0xad0103db, 0xe88e1a20, 0xacf2dc77, 0xc47c2344, 0xace4c1e2, 0xe85f5be9, 0xacd6b41e, 0xc48eb1db,
0xacc8b32c, 0xe830ac45, 0xacbabf10, 0xc4a1651c, 0xacacd7cb, 0xe8020b52, 0xac9efd60, 0xc4b43cfd,
0xac912fd1, 0xe7d3792b, 0xac836f1f, 0xc4c73972, 0xac75bb4d, 0xe7a4f5ed, 0xac68145d, 0xc4da5a6f,
0xac5a7a52, 0xe77681b6, 0xac4ced2c, 0xc4ed9fe7, 0xac3f6cef, 0xe7481ca1, 0xac31f99d, 0xc50109d0,
0xac249336, 0xe719c6cb, 0xac1739bf, 0xc514981d, 0xac09ed38, 0xe6eb8052, 0xabfcada3, 0xc5284ac3,
0xabef7b04, 0xe6bd4951, 0xabe2555b, 0xc53c21b4, 0xabd53caa, 0xe68f21e5, 0xabc830f5, 0xc5501ce5,
0xabbb323c, 0xe6610a2a, 0xabae4082, 0xc5643c4a, 0xaba15bc9, 0xe633023e, 0xab948413, 0xc5787fd6,
0xab87b962, 0xe6050a3b, 0xab7afbb7, 0xc58ce77c, 0xab6e4b15, 0xe5d72240, 0xab61a77d, 0xc5a17330,
0xab5510f3, 0xe5a94a67, 0xab488776, 0xc5b622e6, 0xab3c0b0b, 0xe57b82cd, 0xab2f9bb1, 0xc5caf690,
0xab23396c, 0xe54dcb8f, 0xab16e43d, 0xc5dfee22, 0xab0a9c27, 0xe52024c9, 0xaafe612a, 0xc5f5098f,
0xaaf23349, 0xe4f28e96, 0xaae61286, 0xc60a48c9, 0xaad9fee3, 0xe4c50914, 0xaacdf861, 0xc61fabc4,
0xaac1ff03, 0xe497945d, 0xaab612ca, 0xc6353273, 0xaaaa33b8, 0xe46a308f, 0xaa9e61cf, 0xc64adcc7,
0xaa929d10, 0xe43cddc4, 0xaa86e57e, 0xc660aab5, 0xaa7b3b1b, 0xe40f9c1a, 0xaa6f9de7, 0xc6769c2e,
0xaa640de6, 0xe3e26bac, 0xaa588b18, 0xc68cb124, 0xaa4d157f, 0xe3b54c95, 0xaa41ad1e, 0xc6a2e98b,
0xaa3651f6, 0xe3883ef2, 0xaa2b0409, 0xc6b94554, 0xaa1fc358, 0xe35b42df, 0xaa148fe6, 0xc6cfc472,
0xaa0969b3, 0xe32e5876, 0xa9fe50c2, 0xc6e666d7, 0xa9f34515, 0xe3017fd5, 0xa9e846ad, 0xc6fd2c75,
0xa9dd558b, 0xe2d4b916, 0xa9d271b2, 0xc714153e, 0xa9c79b23, 0xe2a80456, 0xa9bcd1e0, 0xc72b2123,
0xa9b215ea, 0xe27b61af, 0xa9a76744, 0xc7425016, 0xa99cc5ee, 0xe24ed13d, 0xa99231eb, 0xc759a20a,
0xa987ab3c, 0xe222531c, 0xa97d31e3, 0xc77116f0, 0xa972c5e1, 0xe1f5e768, 0xa9686738, 0xc788aeb9,
0xa95e15e9, 0xe1c98e3b, 0xa953d1f7, 0xc7a06957, 0xa9499b62, 0xe19d47b1, 0xa93f722c, 0xc7b846ba,
0xa9355658, 0xe17113e5, 0xa92b47e5, 0xc7d046d6, 0xa92146d7, 0xe144f2f3, 0xa917532e, 0xc7e8699a,
0xa90d6cec, 0xe118e4f6, 0xa9039413, 0xc800aef7, 0xa8f9c8a4, 0xe0ecea09, 0xa8f00aa0, 0xc81916df,
0xa8e65a0a, 0xe0c10247, 0xa8dcb6e2, 0xc831a143, 0xa8d3212a, 0xe0952dcb, 0xa8c998e3, 0xc84a4e14,
0xa8c01e10, 0xe0696cb0, 0xa8b6b0b1, 0xc8631d42, 0xa8ad50c8, 0xe03dbf11, 0xa8a3fe57, 0xc87c0ebd,
0xa89ab95e, 0xe012250a, 0xa89181df, 0xc8952278, 0xa88857dc, 0xdfe69eb4, 0xa87f3b57, 0xc8ae5862,
0xa8762c4f, 0xdfbb2c2c, 0xa86d2ac8, 0xc8c7b06b, 0xa86436c2, 0xdf8fcd8b, 0xa85b503e, 0xc8e12a84,
0xa852773f, 0xdf6482ed, 0xa849abc4, 0xc8fac69e, 0xa840edd1, 0xdf394c6b, 0xa8383d66, 0xc91484a8,
0xa82f9a84, 0xdf0e2a22, 0xa827052d, 0xc92e6492, 0xa81e7d62, 0xdee31c2b, 0xa8160324, 0xc948664d,
0xa80d9675, 0xdeb822a1, 0xa8053756, 0xc96289c9, 0xa7fce5c9, 0xde8d3d9e, 0xa7f4a1ce, 0xc97ccef5,
0xa7ec6b66, 0xde626d3e, 0xa7e44294, 0xc99735c2, 0xa7dc2759, 0xde37b199, 0xa7d419b4, 0xc9b1be1e,
0xa7cc19a9, 0xde0d0acc, 0xa7c42738, 0xc9cc67fa, 0xa7bc4262, 0xdde278ef, 0xa7b46b29, 0xc9e73346,
0xa7aca18e, 0xddb7fc1e, 0xa7a4e591, 0xca021fef, 0xa79d3735, 0xdd8d9472, 0xa795967a, 0xca1d2de7,
0xa78e0361, 0xdd634206, 0xa7867dec, 0xca385d1d, 0xa77f061c, 0xdd3904f4, 0xa7779bf2, 0xca53ad7e,
0xa7703f70, 0xdd0edd55, 0xa768f095, 0xca6f1efc, 0xa761af64, 0xdce4cb44, 0xa75a7bdd, 0xca8ab184,
0xa7535602, 0xdcbacedb, 0xa74c3dd4, 0xcaa66506, 0xa7453353, 0xdc90e834, 0xa73e3681, 0xcac23971,
0xa7374760, 0xdc671768, 0xa73065ef, 0xcade2eb3, 0xa7299231, 0xdc3d5c91, 0xa722cc25, 0xcafa44bc,
0xa71c13ce, 0xdc13b7c9, 0xa715692c, 0xcb167b79, 0xa70ecc41, 0xdbea292b, 0xa7083d0d, 0xcb32d2da,
0xa701bb91, 0xdbc0b0ce, 0xa6fb47ce, 0xcb4f4acd, 0xa6f4e1c6, 0xdb974ece, 0xa6ee8979, 0xcb6be341,
0xa6e83ee8, 0xdb6e0342, 0xa6e20214, 0xcb889c23, 0xa6dbd2ff, 0xdb44ce46, 0xa6d5b1a9, 0xcba57563,
0xa6cf9e13, 0xdb1baff2, 0xa6c9983e, 0xcbc26eee, 0xa6c3a02b, 0xdaf2a860, 0xa6bdb5da, 0xcbdf88b3,
0xa6b7d94e, 0xdac9b7a9, 0xa6b20a86, 0xcbfcc29f, 0xa6ac4984, 0xdaa0dde7, 0xa6a69649, 0xcc1a1ca0,
0xa6a0f0d5, 0xda781b31, 0xa69b5929, 0xcc3796a5, 0xa695cf46, 0xda4f6fa3, 0xa690532d, 0xcc55309b,
0xa68ae4df, 0xda26db54, 0xa685845c, 0xcc72ea70, 0xa68031a6, 0xd9fe5e5e, 0xa67aecbd, 0xcc90c412,
0xa675b5a3, 0xd9d5f8d9, 0xa6708c57, 0xccaebd6e, 0xa66b70db, 0xd9adaadf, 0xa6666330, 0xccccd671,
0xa6616355, 0xd9857489, 0xa65c714d, 0xcceb0f0a, 0xa6578d18, 0xd95d55ef, 0xa652b6b6, 0xcd096725,
0xa64dee28, 0xd9354f2a, 0xa6493370, 0xcd27deb0, 0xa644868d, 0xd90d6053, 0xa63fe781, 0xcd467599,
0xa63b564c, 0xd8e58982, 0xa636d2ee, 0xcd652bcb, 0xa6325d6a, 0xd8bdcad0, 0xa62df5bf, 0xcd840134,
0xa6299bed, 0xd8962456, 0xa6254ff7, 0xcda2f5c2, 0xa62111db, 0xd86e962b, 0xa61ce19c, 0xcdc20960,
0xa618bf39, 0xd8472069, 0xa614aab3, 0xcde13bfd, 0xa610a40c, 0xd81fc328, 0xa60cab43, 0xce008d84,
0xa608c058, 0xd7f87e7f, 0xa604e34e, 0xce1ffde2, 0xa6011424, 0xd7d15288, 0xa5fd52db, 0xce3f8d05,
0xa5f99f73, 0xd7aa3f5a, 0xa5f5f9ed, 0xce5f3ad8, 0xa5f2624a, 0xd783450d, 0xa5eed88a, 0xce7f0748,
0xa5eb5cae, 0xd75c63ba, 0xa5e7eeb6, 0xce9ef241, 0xa5e48ea3, 0xd7359b78, 0xa5e13c75, 0xcebefbb0,
0xa5ddf82d, 0xd70eec60, 0xa5dac1cb, 0xcedf2380, 0xa5d79950, 0xd6e85689, 0xa5d47ebc, 0xceff699f,
0xa5d17210, 0xd6c1da0b, 0xa5ce734d, 0xcf1fcdf8, 0xa5cb8272, 0xd69b76fe, 0xa5c89f80, 0xcf405077,
0xa5c5ca77, 0xd6752d79, 0xa5c30359, 0xcf60f108, 0xa5c04a25, 0xd64efd94, 0xa5bd9edc, 0xcf81af97,
0xa5bb017f, 0xd628e767, 0xa5b8720d, 0xcfa28c10, 0xa5b5f087, 0xd602eb0a, 0xa5b37cee, 0xcfc3865e,
0xa5b11741, 0xd5dd0892, 0xa5aebf82, 0xcfe49e6d, 0xa5ac75b0, 0xd5b74019, 0xa5aa39cd, 0xd005d42a,
0xa5a80bd7, 0xd59191b5, 0xa5a5ebd0, 0xd027277e, 0xa5a3d9b8, 0xd56bfd7d, 0xa5a1d590, 0xd0489856,
0xa59fdf57, 0xd5468389, 0xa59df70e, 0xd06a269d, 0xa59c1cb5, 0xd52123f0, 0xa59a504c, 0xd08bd23f,
0xa59891d4, 0xd4fbdec9, 0xa596e14e, 0xd0ad9b26, 0xa5953eb8, 0xd4d6b42b, 0xa593aa14, 0xd0cf813e,
0xa5922362, 0xd4b1a42c, 0xa590aaa2, 0xd0f18472, 0xa58f3fd4, 0xd48caee4, 0xa58de2f8, 0xd113a4ad,
0xa58c940f, 0xd467d469, 0xa58b5319, 0xd135e1d9, 0xa58a2016, 0xd44314d3, 0xa588fb06, 0xd1583be2,
0xa587e3ea, 0xd41e7037, 0xa586dac1, 0xd17ab2b3, 0xa585df8c, 0xd3f9e6ad, 0xa584f24b, 0xd19d4636,
0xa58412fe, 0xd3d5784a, 0xa58341a5, 0xd1bff656, 0xa5827e40, 0xd3b12526, 0xa581c8d0, 0xd1e2c2fd,
0xa5812154, 0xd38ced57, 0xa58087cd, 0xd205ac17, 0xa57ffc3b, 0xd368d0f3, 0xa57f7e9d, 0xd228b18d,
0xa57f0ef5, 0xd344d011, 0xa57ead41, 0xd24bd34a, 0xa57e5982, 0xd320eac6, 0xa57e13b8, 0xd26f1138,
0xa57ddbe4, 0xd2fd2129, 0xa57db204, 0xd2926b41, 0xa57d961a, 0xd2d97350, 0xa57d8825, 0xd2b5e151,
};
/* PostMultiply() tables
* format = Q30
* reordered for sequential access
* decimate (skip by 16 instead of 2) for small transform (128)
*
* for (i = 0; i <= (512/2); i++) {
* angle = i * M_PI / 1024;
* x = (cos(angle) + sin(angle));
* x = sin(angle);
* }
*/
const int cos1sin1tab[514] = {
/* format = Q30 */
0x40000000, 0x00000000, 0x40323034, 0x003243f1, 0x406438cf, 0x006487c4, 0x409619b2, 0x0096cb58,
0x40c7d2bd, 0x00c90e90, 0x40f963d3, 0x00fb514b, 0x412accd4, 0x012d936c, 0x415c0da3, 0x015fd4d2,
0x418d2621, 0x0192155f, 0x41be162f, 0x01c454f5, 0x41eeddaf, 0x01f69373, 0x421f7c84, 0x0228d0bb,
0x424ff28f, 0x025b0caf, 0x42803fb2, 0x028d472e, 0x42b063d0, 0x02bf801a, 0x42e05ecb, 0x02f1b755,
0x43103085, 0x0323ecbe, 0x433fd8e1, 0x03562038, 0x436f57c1, 0x038851a2, 0x439ead09, 0x03ba80df,
0x43cdd89a, 0x03ecadcf, 0x43fcda59, 0x041ed854, 0x442bb227, 0x0451004d, 0x445a5fe8, 0x0483259d,
0x4488e37f, 0x04b54825, 0x44b73ccf, 0x04e767c5, 0x44e56bbd, 0x0519845e, 0x4513702a, 0x054b9dd3,
0x454149fc, 0x057db403, 0x456ef916, 0x05afc6d0, 0x459c7d5a, 0x05e1d61b, 0x45c9d6af, 0x0613e1c5,
0x45f704f7, 0x0645e9af, 0x46240816, 0x0677edbb, 0x4650dff1, 0x06a9edc9, 0x467d8c6d, 0x06dbe9bb,
0x46aa0d6d, 0x070de172, 0x46d662d6, 0x073fd4cf, 0x47028c8d, 0x0771c3b3, 0x472e8a76, 0x07a3adff,
0x475a5c77, 0x07d59396, 0x47860275, 0x08077457, 0x47b17c54, 0x08395024, 0x47dcc9f9, 0x086b26de,
0x4807eb4b, 0x089cf867, 0x4832e02d, 0x08cec4a0, 0x485da887, 0x09008b6a, 0x4888443d, 0x09324ca7,
0x48b2b335, 0x09640837, 0x48dcf556, 0x0995bdfd, 0x49070a84, 0x09c76dd8, 0x4930f2a6, 0x09f917ac,
0x495aada2, 0x0a2abb59, 0x49843b5f, 0x0a5c58c0, 0x49ad9bc2, 0x0a8defc3, 0x49d6ceb3, 0x0abf8043,
0x49ffd417, 0x0af10a22, 0x4a28abd6, 0x0b228d42, 0x4a5155d6, 0x0b540982, 0x4a79d1ff, 0x0b857ec7,
0x4aa22036, 0x0bb6ecef, 0x4aca4065, 0x0be853de, 0x4af23270, 0x0c19b374, 0x4b19f641, 0x0c4b0b94,
0x4b418bbe, 0x0c7c5c1e, 0x4b68f2cf, 0x0cada4f5, 0x4b902b5c, 0x0cdee5f9, 0x4bb7354d, 0x0d101f0e,
0x4bde1089, 0x0d415013, 0x4c04bcf8, 0x0d7278eb, 0x4c2b3a84, 0x0da39978, 0x4c518913, 0x0dd4b19a,
0x4c77a88e, 0x0e05c135, 0x4c9d98de, 0x0e36c82a, 0x4cc359ec, 0x0e67c65a, 0x4ce8eb9f, 0x0e98bba7,
0x4d0e4de2, 0x0ec9a7f3, 0x4d33809c, 0x0efa8b20, 0x4d5883b7, 0x0f2b650f, 0x4d7d571c, 0x0f5c35a3,
0x4da1fab5, 0x0f8cfcbe, 0x4dc66e6a, 0x0fbdba40, 0x4deab226, 0x0fee6e0d, 0x4e0ec5d1, 0x101f1807,
0x4e32a956, 0x104fb80e, 0x4e565c9f, 0x10804e06, 0x4e79df95, 0x10b0d9d0, 0x4e9d3222, 0x10e15b4e,
0x4ec05432, 0x1111d263, 0x4ee345ad, 0x11423ef0, 0x4f06067f, 0x1172a0d7, 0x4f289692, 0x11a2f7fc,
0x4f4af5d1, 0x11d3443f, 0x4f6d2427, 0x12038584, 0x4f8f217e, 0x1233bbac, 0x4fb0edc1, 0x1263e699,
0x4fd288dc, 0x1294062f, 0x4ff3f2bb, 0x12c41a4f, 0x50152b47, 0x12f422db, 0x5036326e, 0x13241fb6,
0x50570819, 0x135410c3, 0x5077ac37, 0x1383f5e3, 0x50981eb1, 0x13b3cefa, 0x50b85f74, 0x13e39be9,
0x50d86e6d, 0x14135c94, 0x50f84b87, 0x144310dd, 0x5117f6ae, 0x1472b8a5, 0x51376fd0, 0x14a253d1,
0x5156b6d9, 0x14d1e242, 0x5175cbb5, 0x150163dc, 0x5194ae52, 0x1530d881, 0x51b35e9b, 0x15604013,
0x51d1dc80, 0x158f9a76, 0x51f027eb, 0x15bee78c, 0x520e40cc, 0x15ee2738, 0x522c270f, 0x161d595d,
0x5249daa2, 0x164c7ddd, 0x52675b72, 0x167b949d, 0x5284a96e, 0x16aa9d7e, 0x52a1c482, 0x16d99864,
0x52beac9f, 0x17088531, 0x52db61b0, 0x173763c9, 0x52f7e3a6, 0x1766340f, 0x5314326d, 0x1794f5e6,
0x53304df6, 0x17c3a931, 0x534c362d, 0x17f24dd3, 0x5367eb03, 0x1820e3b0, 0x53836c66, 0x184f6aab,
0x539eba45, 0x187de2a7, 0x53b9d48f, 0x18ac4b87, 0x53d4bb34, 0x18daa52f, 0x53ef6e23, 0x1908ef82,
0x5409ed4b, 0x19372a64, 0x5424389d, 0x196555b8, 0x543e5007, 0x19937161, 0x5458337a, 0x19c17d44,
0x5471e2e6, 0x19ef7944, 0x548b5e3b, 0x1a1d6544, 0x54a4a56a, 0x1a4b4128, 0x54bdb862, 0x1a790cd4,
0x54d69714, 0x1aa6c82b, 0x54ef4171, 0x1ad47312, 0x5507b76a, 0x1b020d6c, 0x551ff8ef, 0x1b2f971e,
0x553805f2, 0x1b5d100a, 0x554fde64, 0x1b8a7815, 0x55678236, 0x1bb7cf23, 0x557ef15a, 0x1be51518,
0x55962bc0, 0x1c1249d8, 0x55ad315b, 0x1c3f6d47, 0x55c4021d, 0x1c6c7f4a, 0x55da9df7, 0x1c997fc4,
0x55f104dc, 0x1cc66e99, 0x560736bd, 0x1cf34baf, 0x561d338d, 0x1d2016e9, 0x5632fb3f, 0x1d4cd02c,
0x56488dc5, 0x1d79775c, 0x565deb11, 0x1da60c5d, 0x56731317, 0x1dd28f15, 0x568805c9, 0x1dfeff67,
0x569cc31b, 0x1e2b5d38, 0x56b14b00, 0x1e57a86d, 0x56c59d6a, 0x1e83e0eb, 0x56d9ba4e, 0x1eb00696,
0x56eda1a0, 0x1edc1953, 0x57015352, 0x1f081907, 0x5714cf59, 0x1f340596, 0x572815a8, 0x1f5fdee6,
0x573b2635, 0x1f8ba4dc, 0x574e00f2, 0x1fb7575c, 0x5760a5d5, 0x1fe2f64c, 0x577314d2, 0x200e8190,
0x57854ddd, 0x2039f90f, 0x579750ec, 0x20655cac, 0x57a91df2, 0x2090ac4d, 0x57bab4e6, 0x20bbe7d8,
0x57cc15bc, 0x20e70f32, 0x57dd406a, 0x21122240, 0x57ee34e5, 0x213d20e8, 0x57fef323, 0x21680b0f,
0x580f7b19, 0x2192e09b, 0x581fccbc, 0x21bda171, 0x582fe804, 0x21e84d76, 0x583fcce6, 0x2212e492,
0x584f7b58, 0x223d66a8, 0x585ef351, 0x2267d3a0, 0x586e34c7, 0x22922b5e, 0x587d3fb0, 0x22bc6dca,
0x588c1404, 0x22e69ac8, 0x589ab1b9, 0x2310b23e, 0x58a918c6, 0x233ab414, 0x58b74923, 0x2364a02e,
0x58c542c5, 0x238e7673, 0x58d305a6, 0x23b836ca, 0x58e091bd, 0x23e1e117, 0x58ede700, 0x240b7543,
0x58fb0568, 0x2434f332, 0x5907eced, 0x245e5acc, 0x59149d87, 0x2487abf7, 0x5921172e, 0x24b0e699,
0x592d59da, 0x24da0a9a, 0x59396584, 0x250317df, 0x59453a24, 0x252c0e4f, 0x5950d7b3, 0x2554edd1,
0x595c3e2a, 0x257db64c, 0x59676d82, 0x25a667a7, 0x597265b4, 0x25cf01c8, 0x597d26b8, 0x25f78497,
0x5987b08a, 0x261feffa, 0x59920321, 0x264843d9, 0x599c1e78, 0x2670801a, 0x59a60288, 0x2698a4a6,
0x59afaf4c, 0x26c0b162, 0x59b924bc, 0x26e8a637, 0x59c262d5, 0x2710830c, 0x59cb698f, 0x273847c8,
0x59d438e5, 0x275ff452, 0x59dcd0d3, 0x27878893, 0x59e53151, 0x27af0472, 0x59ed5a5c, 0x27d667d5,
0x59f54bee, 0x27fdb2a7, 0x59fd0603, 0x2824e4cc, 0x5a048895, 0x284bfe2f, 0x5a0bd3a1, 0x2872feb6,
0x5a12e720, 0x2899e64a, 0x5a19c310, 0x28c0b4d2, 0x5a20676c, 0x28e76a37, 0x5a26d42f, 0x290e0661,
0x5a2d0957, 0x29348937, 0x5a3306de, 0x295af2a3, 0x5a38ccc2, 0x2981428c, 0x5a3e5afe, 0x29a778db,
0x5a43b190, 0x29cd9578, 0x5a48d074, 0x29f3984c, 0x5a4db7a6, 0x2a19813f, 0x5a526725, 0x2a3f503a,
0x5a56deec, 0x2a650525, 0x5a5b1efa, 0x2a8a9fea, 0x5a5f274b, 0x2ab02071, 0x5a62f7dd, 0x2ad586a3,
0x5a6690ae, 0x2afad269, 0x5a69f1bb, 0x2b2003ac, 0x5a6d1b03, 0x2b451a55, 0x5a700c84, 0x2b6a164d,
0x5a72c63b, 0x2b8ef77d, 0x5a754827, 0x2bb3bdce, 0x5a779246, 0x2bd8692b, 0x5a79a498, 0x2bfcf97c,
0x5a7b7f1a, 0x2c216eaa, 0x5a7d21cc, 0x2c45c8a0, 0x5a7e8cac, 0x2c6a0746, 0x5a7fbfbb, 0x2c8e2a87,
0x5a80baf6, 0x2cb2324c, 0x5a817e5d, 0x2cd61e7f, 0x5a8209f1, 0x2cf9ef09, 0x5a825db0, 0x2d1da3d5,
0x5a82799a, 0x2d413ccd,
};
const int sinWindowOffset[NUM_IMDCT_SIZES] = {0, 128};
/* Synthesis window - SIN
* format = Q31 for nmdct = [128, 1024]
* reordered for sequential access
*
* for (i = 0; i < nmdct/2; i++) {
* angle = (i + 0.5) * M_PI / (2.0 * nmdct);
* x = sin(angle);
*
* angle = (nmdct - 1 - i + 0.5) * M_PI / (2.0 * nmdct);
* x = sin(angle);
* }
*/
const int sinWindow[128 + 1024] = {
/* 128 - format = Q31 * 2^0 */
0x00c90f88, 0x7fff6216, 0x025b26d7, 0x7ffa72d1, 0x03ed26e6, 0x7ff09478, 0x057f0035, 0x7fe1c76b,
0x0710a345, 0x7fce0c3e, 0x08a2009a, 0x7fb563b3, 0x0a3308bd, 0x7f97cebd, 0x0bc3ac35, 0x7f754e80,
0x0d53db92, 0x7f4de451, 0x0ee38766, 0x7f2191b4, 0x1072a048, 0x7ef05860, 0x120116d5, 0x7eba3a39,
0x138edbb1, 0x7e7f3957, 0x151bdf86, 0x7e3f57ff, 0x16a81305, 0x7dfa98a8, 0x183366e9, 0x7db0fdf8,
0x19bdcbf3, 0x7d628ac6, 0x1b4732ef, 0x7d0f4218, 0x1ccf8cb3, 0x7cb72724, 0x1e56ca1e, 0x7c5a3d50,
0x1fdcdc1b, 0x7bf88830, 0x2161b3a0, 0x7b920b89, 0x22e541af, 0x7b26cb4f, 0x24677758, 0x7ab6cba4,
0x25e845b6, 0x7a4210d8, 0x27679df4, 0x79c89f6e, 0x28e5714b, 0x794a7c12, 0x2a61b101, 0x78c7aba2,
0x2bdc4e6f, 0x78403329, 0x2d553afc, 0x77b417df, 0x2ecc681e, 0x77235f2d, 0x3041c761, 0x768e0ea6,
0x31b54a5e, 0x75f42c0b, 0x3326e2c3, 0x7555bd4c, 0x34968250, 0x74b2c884, 0x36041ad9, 0x740b53fb,
0x376f9e46, 0x735f6626, 0x38d8fe93, 0x72af05a7, 0x3a402dd2, 0x71fa3949, 0x3ba51e29, 0x71410805,
0x3d07c1d6, 0x708378ff, 0x3e680b2c, 0x6fc19385, 0x3fc5ec98, 0x6efb5f12, 0x4121589b, 0x6e30e34a,
0x427a41d0, 0x6d6227fa, 0x43d09aed, 0x6c8f351c, 0x452456bd, 0x6bb812d1, 0x46756828, 0x6adcc964,
0x47c3c22f, 0x69fd614a, 0x490f57ee, 0x6919e320, 0x4a581c9e, 0x683257ab, 0x4b9e0390, 0x6746c7d8,
0x4ce10034, 0x66573cbb, 0x4e210617, 0x6563bf92, 0x4f5e08e3, 0x646c59bf, 0x5097fc5e, 0x637114cc,
0x51ced46e, 0x6271fa69, 0x53028518, 0x616f146c, 0x5433027d, 0x60686ccf, 0x556040e2, 0x5f5e0db3,
0x568a34a9, 0x5e50015d, 0x57b0d256, 0x5d3e5237, 0x58d40e8c, 0x5c290acc, 0x59f3de12, 0x5b1035cf,
/* 1024 - format = Q31 * 2^0 */
0x001921fb, 0x7ffffd88, 0x004b65ee, 0x7fffe9cb, 0x007da9d4, 0x7fffc251, 0x00afeda8, 0x7fff8719,
0x00e23160, 0x7fff3824, 0x011474f6, 0x7ffed572, 0x0146b860, 0x7ffe5f03, 0x0178fb99, 0x7ffdd4d7,
0x01ab3e97, 0x7ffd36ee, 0x01dd8154, 0x7ffc8549, 0x020fc3c6, 0x7ffbbfe6, 0x024205e8, 0x7ffae6c7,
0x027447b0, 0x7ff9f9ec, 0x02a68917, 0x7ff8f954, 0x02d8ca16, 0x7ff7e500, 0x030b0aa4, 0x7ff6bcf0,
0x033d4abb, 0x7ff58125, 0x036f8a51, 0x7ff4319d, 0x03a1c960, 0x7ff2ce5b, 0x03d407df, 0x7ff1575d,
0x040645c7, 0x7fefcca4, 0x04388310, 0x7fee2e30, 0x046abfb3, 0x7fec7c02, 0x049cfba7, 0x7feab61a,
0x04cf36e5, 0x7fe8dc78, 0x05017165, 0x7fe6ef1c, 0x0533ab20, 0x7fe4ee06, 0x0565e40d, 0x7fe2d938,
0x05981c26, 0x7fe0b0b1, 0x05ca5361, 0x7fde7471, 0x05fc89b8, 0x7fdc247a, 0x062ebf22, 0x7fd9c0ca,
0x0660f398, 0x7fd74964, 0x06932713, 0x7fd4be46, 0x06c5598a, 0x7fd21f72, 0x06f78af6, 0x7fcf6ce8,
0x0729bb4e, 0x7fcca6a7, 0x075bea8c, 0x7fc9ccb2, 0x078e18a7, 0x7fc6df08, 0x07c04598, 0x7fc3dda9,
0x07f27157, 0x7fc0c896, 0x08249bdd, 0x7fbd9fd0, 0x0856c520, 0x7fba6357, 0x0888ed1b, 0x7fb7132b,
0x08bb13c5, 0x7fb3af4e, 0x08ed3916, 0x7fb037bf, 0x091f5d06, 0x7facac7f, 0x09517f8f, 0x7fa90d8e,
0x0983a0a7, 0x7fa55aee, 0x09b5c048, 0x7fa1949e, 0x09e7de6a, 0x7f9dbaa0, 0x0a19fb04, 0x7f99ccf4,
0x0a4c1610, 0x7f95cb9a, 0x0a7e2f85, 0x7f91b694, 0x0ab0475c, 0x7f8d8de1, 0x0ae25d8d, 0x7f895182,
0x0b147211, 0x7f850179, 0x0b4684df, 0x7f809dc5, 0x0b7895f0, 0x7f7c2668, 0x0baaa53b, 0x7f779b62,
0x0bdcb2bb, 0x7f72fcb4, 0x0c0ebe66, 0x7f6e4a5e, 0x0c40c835, 0x7f698461, 0x0c72d020, 0x7f64aabf,
0x0ca4d620, 0x7f5fbd77, 0x0cd6da2d, 0x7f5abc8a, 0x0d08dc3f, 0x7f55a7fa, 0x0d3adc4e, 0x7f507fc7,
0x0d6cda53, 0x7f4b43f2, 0x0d9ed646, 0x7f45f47b, 0x0dd0d01f, 0x7f409164, 0x0e02c7d7, 0x7f3b1aad,
0x0e34bd66, 0x7f359057, 0x0e66b0c3, 0x7f2ff263, 0x0e98a1e9, 0x7f2a40d2, 0x0eca90ce, 0x7f247ba5,
0x0efc7d6b, 0x7f1ea2dc, 0x0f2e67b8, 0x7f18b679, 0x0f604faf, 0x7f12b67c, 0x0f923546, 0x7f0ca2e7,
0x0fc41876, 0x7f067bba, 0x0ff5f938, 0x7f0040f6, 0x1027d784, 0x7ef9f29d, 0x1059b352, 0x7ef390ae,
0x108b8c9b, 0x7eed1b2c, 0x10bd6356, 0x7ee69217, 0x10ef377d, 0x7edff570, 0x11210907, 0x7ed94538,
0x1152d7ed, 0x7ed28171, 0x1184a427, 0x7ecbaa1a, 0x11b66dad, 0x7ec4bf36, 0x11e83478, 0x7ebdc0c6,
0x1219f880, 0x7eb6aeca, 0x124bb9be, 0x7eaf8943, 0x127d7829, 0x7ea85033, 0x12af33ba, 0x7ea1039b,
0x12e0ec6a, 0x7e99a37c, 0x1312a230, 0x7e922fd6, 0x13445505, 0x7e8aa8ac, 0x137604e2, 0x7e830dff,
0x13a7b1bf, 0x7e7b5fce, 0x13d95b93, 0x7e739e1d, 0x140b0258, 0x7e6bc8eb, 0x143ca605, 0x7e63e03b,
0x146e4694, 0x7e5be40c, 0x149fe3fc, 0x7e53d462, 0x14d17e36, 0x7e4bb13c, 0x1503153a, 0x7e437a9c,
0x1534a901, 0x7e3b3083, 0x15663982, 0x7e32d2f4, 0x1597c6b7, 0x7e2a61ed, 0x15c95097, 0x7e21dd73,
0x15fad71b, 0x7e194584, 0x162c5a3b, 0x7e109a24, 0x165dd9f0, 0x7e07db52, 0x168f5632, 0x7dff0911,
0x16c0cef9, 0x7df62362, 0x16f2443e, 0x7ded2a47, 0x1723b5f9, 0x7de41dc0, 0x17552422, 0x7ddafdce,
0x17868eb3, 0x7dd1ca75, 0x17b7f5a3, 0x7dc883b4, 0x17e958ea, 0x7dbf298d, 0x181ab881, 0x7db5bc02,
0x184c1461, 0x7dac3b15, 0x187d6c82, 0x7da2a6c6, 0x18aec0db, 0x7d98ff17, 0x18e01167, 0x7d8f4409,
0x19115e1c, 0x7d85759f, 0x1942a6f3, 0x7d7b93da, 0x1973ebe6, 0x7d719eba, 0x19a52ceb, 0x7d679642,
0x19d669fc, 0x7d5d7a74, 0x1a07a311, 0x7d534b50, 0x1a38d823, 0x7d4908d9, 0x1a6a0929, 0x7d3eb30f,
0x1a9b361d, 0x7d3449f5, 0x1acc5ef6, 0x7d29cd8c, 0x1afd83ad, 0x7d1f3dd6, 0x1b2ea43a, 0x7d149ad5,
0x1b5fc097, 0x7d09e489, 0x1b90d8bb, 0x7cff1af5, 0x1bc1ec9e, 0x7cf43e1a, 0x1bf2fc3a, 0x7ce94dfb,
0x1c240786, 0x7cde4a98, 0x1c550e7c, 0x7cd333f3, 0x1c861113, 0x7cc80a0f, 0x1cb70f43, 0x7cbcccec,
0x1ce80906, 0x7cb17c8d, 0x1d18fe54, 0x7ca618f3, 0x1d49ef26, 0x7c9aa221, 0x1d7adb73, 0x7c8f1817,
0x1dabc334, 0x7c837ad8, 0x1ddca662, 0x7c77ca65, 0x1e0d84f5, 0x7c6c06c0, 0x1e3e5ee5, 0x7c602fec,
0x1e6f342c, 0x7c5445e9, 0x1ea004c1, 0x7c4848ba, 0x1ed0d09d, 0x7c3c3860, 0x1f0197b8, 0x7c3014de,
0x1f325a0b, 0x7c23de35, 0x1f63178f, 0x7c179467, 0x1f93d03c, 0x7c0b3777, 0x1fc4840a, 0x7bfec765,
0x1ff532f2, 0x7bf24434, 0x2025dcec, 0x7be5ade6, 0x205681f1, 0x7bd9047c, 0x208721f9, 0x7bcc47fa,
0x20b7bcfe, 0x7bbf7860, 0x20e852f6, 0x7bb295b0, 0x2118e3dc, 0x7ba59fee, 0x21496fa7, 0x7b989719,
0x2179f64f, 0x7b8b7b36, 0x21aa77cf, 0x7b7e4c45, 0x21daf41d, 0x7b710a49, 0x220b6b32, 0x7b63b543,
0x223bdd08, 0x7b564d36, 0x226c4996, 0x7b48d225, 0x229cb0d5, 0x7b3b4410, 0x22cd12bd, 0x7b2da2fa,
0x22fd6f48, 0x7b1feee5, 0x232dc66d, 0x7b1227d3, 0x235e1826, 0x7b044dc7, 0x238e646a, 0x7af660c2,
0x23beab33, 0x7ae860c7, 0x23eeec78, 0x7ada4dd8, 0x241f2833, 0x7acc27f7, 0x244f5e5c, 0x7abdef25,
0x247f8eec, 0x7aafa367, 0x24afb9da, 0x7aa144bc, 0x24dfdf20, 0x7a92d329, 0x250ffeb7, 0x7a844eae,
0x25401896, 0x7a75b74f, 0x25702cb7, 0x7a670d0d, 0x25a03b11, 0x7a584feb, 0x25d0439f, 0x7a497feb,
0x26004657, 0x7a3a9d0f, 0x26304333, 0x7a2ba75a, 0x26603a2c, 0x7a1c9ece, 0x26902b39, 0x7a0d836d,
0x26c01655, 0x79fe5539, 0x26effb76, 0x79ef1436, 0x271fda96, 0x79dfc064, 0x274fb3ae, 0x79d059c8,
0x277f86b5, 0x79c0e062, 0x27af53a6, 0x79b15435, 0x27df1a77, 0x79a1b545, 0x280edb23, 0x79920392,
0x283e95a1, 0x79823f20, 0x286e49ea, 0x797267f2, 0x289df7f8, 0x79627e08, 0x28cd9fc1, 0x79528167,
0x28fd4140, 0x79427210, 0x292cdc6d, 0x79325006, 0x295c7140, 0x79221b4b, 0x298bffb2, 0x7911d3e2,
0x29bb87bc, 0x790179cd, 0x29eb0957, 0x78f10d0f, 0x2a1a847b, 0x78e08dab, 0x2a49f920, 0x78cffba3,
0x2a796740, 0x78bf56f9, 0x2aa8ced3, 0x78ae9fb0, 0x2ad82fd2, 0x789dd5cb, 0x2b078a36, 0x788cf94c,
0x2b36ddf7, 0x787c0a36, 0x2b662b0e, 0x786b088c, 0x2b957173, 0x7859f44f, 0x2bc4b120, 0x7848cd83,
0x2bf3ea0d, 0x7837942b, 0x2c231c33, 0x78264849, 0x2c52478a, 0x7814e9df, 0x2c816c0c, 0x780378f1,
0x2cb089b1, 0x77f1f581, 0x2cdfa071, 0x77e05f91, 0x2d0eb046, 0x77ceb725, 0x2d3db928, 0x77bcfc3f,
0x2d6cbb10, 0x77ab2ee2, 0x2d9bb5f6, 0x77994f11, 0x2dcaa9d5, 0x77875cce, 0x2df996a3, 0x7775581d,
0x2e287c5a, 0x776340ff, 0x2e575af3, 0x77511778, 0x2e863267, 0x773edb8b, 0x2eb502ae, 0x772c8d3a,
0x2ee3cbc1, 0x771a2c88, 0x2f128d99, 0x7707b979, 0x2f41482e, 0x76f5340e, 0x2f6ffb7a, 0x76e29c4b,
0x2f9ea775, 0x76cff232, 0x2fcd4c19, 0x76bd35c7, 0x2ffbe95d, 0x76aa670d, 0x302a7f3a, 0x76978605,
0x30590dab, 0x768492b4, 0x308794a6, 0x76718d1c, 0x30b61426, 0x765e7540, 0x30e48c22, 0x764b4b23,
0x3112fc95, 0x76380ec8, 0x31416576, 0x7624c031, 0x316fc6be, 0x76115f63, 0x319e2067, 0x75fdec60,
0x31cc7269, 0x75ea672a, 0x31fabcbd, 0x75d6cfc5, 0x3228ff5c, 0x75c32634, 0x32573a3f, 0x75af6a7b,
0x32856d5e, 0x759b9c9b, 0x32b398b3, 0x7587bc98, 0x32e1bc36, 0x7573ca75, 0x330fd7e1, 0x755fc635,
0x333debab, 0x754bafdc, 0x336bf78f, 0x7537876c, 0x3399fb85, 0x75234ce8, 0x33c7f785, 0x750f0054,
0x33f5eb89, 0x74faa1b3, 0x3423d78a, 0x74e63108, 0x3451bb81, 0x74d1ae55, 0x347f9766, 0x74bd199f,
0x34ad6b32, 0x74a872e8, 0x34db36df, 0x7493ba34, 0x3508fa66, 0x747eef85, 0x3536b5be, 0x746a12df,
0x356468e2, 0x74552446, 0x359213c9, 0x744023bc, 0x35bfb66e, 0x742b1144, 0x35ed50c9, 0x7415ece2,
0x361ae2d3, 0x7400b69a, 0x36486c86, 0x73eb6e6e, 0x3675edd9, 0x73d61461, 0x36a366c6, 0x73c0a878,
0x36d0d746, 0x73ab2ab4, 0x36fe3f52, 0x73959b1b, 0x372b9ee3, 0x737ff9ae, 0x3758f5f2, 0x736a4671,
0x37864477, 0x73548168, 0x37b38a6d, 0x733eaa96, 0x37e0c7cc, 0x7328c1ff, 0x380dfc8d, 0x7312c7a5,
0x383b28a9, 0x72fcbb8c, 0x38684c19, 0x72e69db7, 0x389566d6, 0x72d06e2b, 0x38c278d9, 0x72ba2cea,
0x38ef821c, 0x72a3d9f7, 0x391c8297, 0x728d7557, 0x39497a43, 0x7276ff0d, 0x39766919, 0x7260771b,
0x39a34f13, 0x7249dd86, 0x39d02c2a, 0x72333251, 0x39fd0056, 0x721c7580, 0x3a29cb91, 0x7205a716,
0x3a568dd4, 0x71eec716, 0x3a834717, 0x71d7d585, 0x3aaff755, 0x71c0d265, 0x3adc9e86, 0x71a9bdba,
0x3b093ca3, 0x71929789, 0x3b35d1a5, 0x717b5fd3, 0x3b625d86, 0x7164169d, 0x3b8ee03e, 0x714cbbeb,
0x3bbb59c7, 0x71354fc0, 0x3be7ca1a, 0x711dd220, 0x3c143130, 0x7106430e, 0x3c408f03, 0x70eea28e,
0x3c6ce38a, 0x70d6f0a4, 0x3c992ec0, 0x70bf2d53, 0x3cc5709e, 0x70a7589f, 0x3cf1a91c, 0x708f728b,
0x3d1dd835, 0x70777b1c, 0x3d49fde1, 0x705f7255, 0x3d761a19, 0x70475839, 0x3da22cd7, 0x702f2ccd,
0x3dce3614, 0x7016f014, 0x3dfa35c8, 0x6ffea212, 0x3e262bee, 0x6fe642ca, 0x3e52187f, 0x6fcdd241,
0x3e7dfb73, 0x6fb5507a, 0x3ea9d4c3, 0x6f9cbd79, 0x3ed5a46b, 0x6f841942, 0x3f016a61, 0x6f6b63d8,
0x3f2d26a0, 0x6f529d40, 0x3f58d921, 0x6f39c57d, 0x3f8481dd, 0x6f20dc92, 0x3fb020ce, 0x6f07e285,
0x3fdbb5ec, 0x6eeed758, 0x40074132, 0x6ed5bb10, 0x4032c297, 0x6ebc8db0, 0x405e3a16, 0x6ea34f3d,
0x4089a7a8, 0x6e89ffb9, 0x40b50b46, 0x6e709f2a, 0x40e064ea, 0x6e572d93, 0x410bb48c, 0x6e3daaf8,
0x4136fa27, 0x6e24175c, 0x416235b2, 0x6e0a72c5, 0x418d6729, 0x6df0bd35, 0x41b88e84, 0x6dd6f6b1,
0x41e3abbc, 0x6dbd1f3c, 0x420ebecb, 0x6da336dc, 0x4239c7aa, 0x6d893d93, 0x4264c653, 0x6d6f3365,
0x428fbabe, 0x6d551858, 0x42baa4e6, 0x6d3aec6e, 0x42e584c3, 0x6d20afac, 0x43105a50, 0x6d066215,
0x433b2585, 0x6cec03af, 0x4365e65b, 0x6cd1947c, 0x43909ccd, 0x6cb71482, 0x43bb48d4, 0x6c9c83c3,
0x43e5ea68, 0x6c81e245, 0x44108184, 0x6c67300b, 0x443b0e21, 0x6c4c6d1a, 0x44659039, 0x6c319975,
0x449007c4, 0x6c16b521, 0x44ba74bd, 0x6bfbc021, 0x44e4d71c, 0x6be0ba7b, 0x450f2edb, 0x6bc5a431,
0x45397bf4, 0x6baa7d49, 0x4563be60, 0x6b8f45c7, 0x458df619, 0x6b73fdae, 0x45b82318, 0x6b58a503,
0x45e24556, 0x6b3d3bcb, 0x460c5cce, 0x6b21c208, 0x46366978, 0x6b0637c1, 0x46606b4e, 0x6aea9cf8,
0x468a624a, 0x6acef1b2, 0x46b44e65, 0x6ab335f4, 0x46de2f99, 0x6a9769c1, 0x470805df, 0x6a7b8d1e,
0x4731d131, 0x6a5fa010, 0x475b9188, 0x6a43a29a, 0x478546de, 0x6a2794c1, 0x47aef12c, 0x6a0b7689,
0x47d8906d, 0x69ef47f6, 0x48022499, 0x69d3090e, 0x482badab, 0x69b6b9d3, 0x48552b9b, 0x699a5a4c,
0x487e9e64, 0x697dea7b, 0x48a805ff, 0x69616a65, 0x48d16265, 0x6944da10, 0x48fab391, 0x6928397e,
0x4923f97b, 0x690b88b5, 0x494d341e, 0x68eec7b9, 0x49766373, 0x68d1f68f, 0x499f8774, 0x68b5153a,
0x49c8a01b, 0x689823bf, 0x49f1ad61, 0x687b2224, 0x4a1aaf3f, 0x685e106c, 0x4a43a5b0, 0x6840ee9b,
0x4a6c90ad, 0x6823bcb7, 0x4a957030, 0x68067ac3, 0x4abe4433, 0x67e928c5, 0x4ae70caf, 0x67cbc6c0,
0x4b0fc99d, 0x67ae54ba, 0x4b387af9, 0x6790d2b6, 0x4b6120bb, 0x677340ba, 0x4b89badd, 0x67559eca,
0x4bb24958, 0x6737ecea, 0x4bdacc28, 0x671a2b20, 0x4c034345, 0x66fc596f, 0x4c2baea9, 0x66de77dc,
0x4c540e4e, 0x66c0866d, 0x4c7c622d, 0x66a28524, 0x4ca4aa41, 0x66847408, 0x4ccce684, 0x6666531d,
0x4cf516ee, 0x66482267, 0x4d1d3b7a, 0x6629e1ec, 0x4d455422, 0x660b91af, 0x4d6d60df, 0x65ed31b5,
0x4d9561ac, 0x65cec204, 0x4dbd5682, 0x65b0429f, 0x4de53f5a, 0x6591b38c, 0x4e0d1c30, 0x657314cf,
0x4e34ecfc, 0x6554666d, 0x4e5cb1b9, 0x6535a86b, 0x4e846a60, 0x6516dacd, 0x4eac16eb, 0x64f7fd98,
0x4ed3b755, 0x64d910d1, 0x4efb4b96, 0x64ba147d, 0x4f22d3aa, 0x649b08a0, 0x4f4a4f89, 0x647bed3f,
0x4f71bf2e, 0x645cc260, 0x4f992293, 0x643d8806, 0x4fc079b1, 0x641e3e38, 0x4fe7c483, 0x63fee4f8,
0x500f0302, 0x63df7c4d, 0x50363529, 0x63c0043b, 0x505d5af1, 0x63a07cc7, 0x50847454, 0x6380e5f6,
0x50ab814d, 0x63613fcd, 0x50d281d5, 0x63418a50, 0x50f975e6, 0x6321c585, 0x51205d7b, 0x6301f171,
0x5147388c, 0x62e20e17, 0x516e0715, 0x62c21b7e, 0x5194c910, 0x62a219aa, 0x51bb7e75, 0x628208a1,
0x51e22740, 0x6261e866, 0x5208c36a, 0x6241b8ff, 0x522f52ee, 0x62217a72, 0x5255d5c5, 0x62012cc2,
0x527c4bea, 0x61e0cff5, 0x52a2b556, 0x61c06410, 0x52c91204, 0x619fe918, 0x52ef61ee, 0x617f5f12,
0x5315a50e, 0x615ec603, 0x533bdb5d, 0x613e1df0, 0x536204d7, 0x611d66de, 0x53882175, 0x60fca0d2,
0x53ae3131, 0x60dbcbd1, 0x53d43406, 0x60bae7e1, 0x53fa29ed, 0x6099f505, 0x542012e1, 0x6078f344,
0x5445eedb, 0x6057e2a2, 0x546bbdd7, 0x6036c325, 0x54917fce, 0x601594d1, 0x54b734ba, 0x5ff457ad,
0x54dcdc96, 0x5fd30bbc, 0x5502775c, 0x5fb1b104, 0x55280505, 0x5f90478a, 0x554d858d, 0x5f6ecf53,
0x5572f8ed, 0x5f4d4865, 0x55985f20, 0x5f2bb2c5, 0x55bdb81f, 0x5f0a0e77, 0x55e303e6, 0x5ee85b82,
0x5608426e, 0x5ec699e9, 0x562d73b2, 0x5ea4c9b3, 0x565297ab, 0x5e82eae5, 0x5677ae54, 0x5e60fd84,
0x569cb7a8, 0x5e3f0194, 0x56c1b3a1, 0x5e1cf71c, 0x56e6a239, 0x5dfade20, 0x570b8369, 0x5dd8b6a7,
0x5730572e, 0x5db680b4, 0x57551d80, 0x5d943c4e, 0x5779d65b, 0x5d71e979, 0x579e81b8, 0x5d4f883b,
0x57c31f92, 0x5d2d189a, 0x57e7afe4, 0x5d0a9a9a, 0x580c32a7, 0x5ce80e41, 0x5830a7d6, 0x5cc57394,
0x58550f6c, 0x5ca2ca99, 0x58796962, 0x5c801354, 0x589db5b3, 0x5c5d4dcc, 0x58c1f45b, 0x5c3a7a05,
0x58e62552, 0x5c179806, 0x590a4893, 0x5bf4a7d2, 0x592e5e19, 0x5bd1a971, 0x595265df, 0x5bae9ce7,
0x59765fde, 0x5b8b8239, 0x599a4c12, 0x5b68596d, 0x59be2a74, 0x5b452288, 0x59e1faff, 0x5b21dd90,
0x5a05bdae, 0x5afe8a8b, 0x5a29727b, 0x5adb297d, 0x5a4d1960, 0x5ab7ba6c, 0x5a70b258, 0x5a943d5e,
};
const int kbdWindowOffset[NUM_IMDCT_SIZES] = {0, 128};
/* Synthesis window - KBD
* format = Q31 for nmdct = [128, 1024]
* reordered for sequential access
*
* aacScaleFact = -sqrt(1.0 / (2.0 * nmdct));
* for (i = 0; i < nmdct/2; i++) {
* x = kbdWindowRef[i] * aacScaleFact;
* x = kbdWindowRef[nmdct - 1 - i] * aacScaleFact;
* }
* Note: see below for code to generate kbdWindowRef[]
*/
const int kbdWindow[128 + 1024] = {
/* 128 - format = Q31 * 2^0 */
0x00016f63, 0x7ffffffe, 0x0003e382, 0x7ffffff1, 0x00078f64, 0x7fffffc7, 0x000cc323, 0x7fffff5d,
0x0013d9ed, 0x7ffffe76, 0x001d3a9d, 0x7ffffcaa, 0x0029581f, 0x7ffff953, 0x0038b1bd, 0x7ffff372,
0x004bd34d, 0x7fffe98b, 0x00635538, 0x7fffd975, 0x007fdc64, 0x7fffc024, 0x00a219f1, 0x7fff995b,
0x00cacad0, 0x7fff5f5b, 0x00fab72d, 0x7fff0a75, 0x0132b1af, 0x7ffe9091, 0x01739689, 0x7ffde49e,
0x01be4a63, 0x7ffcf5ef, 0x0213b910, 0x7ffbaf84, 0x0274d41e, 0x7ff9f73a, 0x02e2913a, 0x7ff7acf1,
0x035de86c, 0x7ff4a99a, 0x03e7d233, 0x7ff0be3d, 0x0481457c, 0x7febb2f1, 0x052b357c, 0x7fe545d4,
0x05e68f77, 0x7fdd2a02, 0x06b4386f, 0x7fd30695, 0x07950acb, 0x7fc675b4, 0x0889d3ef, 0x7fb703be,
0x099351e0, 0x7fa42e89, 0x0ab230e0, 0x7f8d64d8, 0x0be70923, 0x7f7205f8, 0x0d325c93, 0x7f516195,
0x0e9494ae, 0x7f2ab7d0, 0x100e0085, 0x7efd3997, 0x119ed2ef, 0x7ec8094a, 0x134720d8, 0x7e8a3ba7,
0x1506dfdc, 0x7e42d906, 0x16dde50b, 0x7df0dee4, 0x18cbe3f7, 0x7d9341b4, 0x1ad06e07, 0x7d28ef02,
0x1ceaf215, 0x7cb0cfcc, 0x1f1abc4f, 0x7c29cb20, 0x215ef677, 0x7b92c8eb, 0x23b6a867, 0x7aeab4ec,
0x2620b8ec, 0x7a3081d0, 0x289beef5, 0x79632c5a, 0x2b26f30b, 0x7881be95, 0x2dc0511f, 0x778b5304,
0x30667aa2, 0x767f17c0, 0x3317c8dd, 0x755c5178, 0x35d27f98, 0x74225e50, 0x3894cff3, 0x72d0b887,
0x3b5cdb7b, 0x7166f8e7, 0x3e28b770, 0x6fe4d8e8, 0x40f6702a, 0x6e4a3491, 0x43c40caa, 0x6c970bfc,
0x468f9231, 0x6acb8483, 0x495707f5, 0x68e7e994, 0x4c187ac7, 0x66ecad1c, 0x4ed200c5, 0x64da6797,
0x5181bcea, 0x62b1d7b7, 0x5425e28e, 0x6073e1ae, 0x56bcb8c2, 0x5e218e16, 0x59449d76, 0x5bbc0875,
/* 1024 - format = Q31 * 2^0 */
0x0009962f, 0x7fffffa4, 0x000e16fb, 0x7fffff39, 0x0011ea65, 0x7ffffebf, 0x0015750e, 0x7ffffe34,
0x0018dc74, 0x7ffffd96, 0x001c332e, 0x7ffffce5, 0x001f83f5, 0x7ffffc1f, 0x0022d59a, 0x7ffffb43,
0x00262cc2, 0x7ffffa4f, 0x00298cc4, 0x7ffff942, 0x002cf81f, 0x7ffff81a, 0x003070c4, 0x7ffff6d6,
0x0033f840, 0x7ffff573, 0x00378fd9, 0x7ffff3f1, 0x003b38a1, 0x7ffff24d, 0x003ef381, 0x7ffff085,
0x0042c147, 0x7fffee98, 0x0046a2a8, 0x7fffec83, 0x004a9847, 0x7fffea44, 0x004ea2b7, 0x7fffe7d8,
0x0052c283, 0x7fffe53f, 0x0056f829, 0x7fffe274, 0x005b4422, 0x7fffdf76, 0x005fa6dd, 0x7fffdc43,
0x006420c8, 0x7fffd8d6, 0x0068b249, 0x7fffd52f, 0x006d5bc4, 0x7fffd149, 0x00721d9a, 0x7fffcd22,
0x0076f828, 0x7fffc8b6, 0x007bebca, 0x7fffc404, 0x0080f8d9, 0x7fffbf06, 0x00861fae, 0x7fffb9bb,
0x008b609e, 0x7fffb41e, 0x0090bbff, 0x7fffae2c, 0x00963224, 0x7fffa7e1, 0x009bc362, 0x7fffa13a,
0x00a17009, 0x7fff9a32, 0x00a7386c, 0x7fff92c5, 0x00ad1cdc, 0x7fff8af0, 0x00b31da8, 0x7fff82ad,
0x00b93b21, 0x7fff79f9, 0x00bf7596, 0x7fff70cf, 0x00c5cd57, 0x7fff672a, 0x00cc42b1, 0x7fff5d05,
0x00d2d5f3, 0x7fff525c, 0x00d9876c, 0x7fff4729, 0x00e05769, 0x7fff3b66, 0x00e74638, 0x7fff2f10,
0x00ee5426, 0x7fff221f, 0x00f58182, 0x7fff148e, 0x00fcce97, 0x7fff0658, 0x01043bb3, 0x7ffef776,
0x010bc923, 0x7ffee7e2, 0x01137733, 0x7ffed795, 0x011b4631, 0x7ffec68a, 0x01233669, 0x7ffeb4ba,
0x012b4827, 0x7ffea21d, 0x01337bb8, 0x7ffe8eac, 0x013bd167, 0x7ffe7a61, 0x01444982, 0x7ffe6533,
0x014ce454, 0x7ffe4f1c, 0x0155a229, 0x7ffe3813, 0x015e834d, 0x7ffe2011, 0x0167880c, 0x7ffe070d,
0x0170b0b2, 0x7ffdecff, 0x0179fd8b, 0x7ffdd1df, 0x01836ee1, 0x7ffdb5a2, 0x018d0500, 0x7ffd9842,
0x0196c035, 0x7ffd79b3, 0x01a0a0ca, 0x7ffd59ee, 0x01aaa70a, 0x7ffd38e8, 0x01b4d341, 0x7ffd1697,
0x01bf25b9, 0x7ffcf2f2, 0x01c99ebd, 0x7ffccdee, 0x01d43e99, 0x7ffca780, 0x01df0597, 0x7ffc7f9e,
0x01e9f401, 0x7ffc563d, 0x01f50a22, 0x7ffc2b51, 0x02004844, 0x7ffbfecf, 0x020baeb1, 0x7ffbd0ab,
0x02173db4, 0x7ffba0da, 0x0222f596, 0x7ffb6f4f, 0x022ed6a1, 0x7ffb3bfd, 0x023ae11f, 0x7ffb06d8,
0x02471558, 0x7ffacfd3, 0x02537397, 0x7ffa96e0, 0x025ffc25, 0x7ffa5bf2, 0x026caf4a, 0x7ffa1efc,
0x02798d4f, 0x7ff9dfee, 0x0286967c, 0x7ff99ebb, 0x0293cb1b, 0x7ff95b55, 0x02a12b72, 0x7ff915ab,
0x02aeb7cb, 0x7ff8cdaf, 0x02bc706d, 0x7ff88351, 0x02ca559f, 0x7ff83682, 0x02d867a9, 0x7ff7e731,
0x02e6a6d2, 0x7ff7954e, 0x02f51361, 0x7ff740c8, 0x0303ad9c, 0x7ff6e98e, 0x031275ca, 0x7ff68f8f,
0x03216c30, 0x7ff632ba, 0x03309116, 0x7ff5d2fb, 0x033fe4bf, 0x7ff57042, 0x034f6773, 0x7ff50a7a,
0x035f1975, 0x7ff4a192, 0x036efb0a, 0x7ff43576, 0x037f0c78, 0x7ff3c612, 0x038f4e02, 0x7ff35353,
0x039fbfeb, 0x7ff2dd24, 0x03b06279, 0x7ff26370, 0x03c135ed, 0x7ff1e623, 0x03d23a8b, 0x7ff16527,
0x03e37095, 0x7ff0e067, 0x03f4d84e, 0x7ff057cc, 0x040671f7, 0x7fefcb40, 0x04183dd3, 0x7fef3aad,
0x042a3c22, 0x7feea5fa, 0x043c6d25, 0x7fee0d11, 0x044ed11d, 0x7fed6fda, 0x04616849, 0x7fecce3d,
0x047432eb, 0x7fec2821, 0x04873140, 0x7feb7d6c, 0x049a6388, 0x7feace07, 0x04adca01, 0x7fea19d6,
0x04c164ea, 0x7fe960c0, 0x04d53481, 0x7fe8a2aa, 0x04e93902, 0x7fe7df79, 0x04fd72aa, 0x7fe71712,
0x0511e1b6, 0x7fe6495a, 0x05268663, 0x7fe57634, 0x053b60eb, 0x7fe49d83, 0x05507189, 0x7fe3bf2b,
0x0565b879, 0x7fe2db0f, 0x057b35f4, 0x7fe1f110, 0x0590ea35, 0x7fe10111, 0x05a6d574, 0x7fe00af3,
0x05bcf7ea, 0x7fdf0e97, 0x05d351cf, 0x7fde0bdd, 0x05e9e35c, 0x7fdd02a6, 0x0600acc8, 0x7fdbf2d2,
0x0617ae48, 0x7fdadc40, 0x062ee814, 0x7fd9becf, 0x06465a62, 0x7fd89a5e, 0x065e0565, 0x7fd76eca,
0x0675e954, 0x7fd63bf1, 0x068e0662, 0x7fd501b0, 0x06a65cc3, 0x7fd3bfe4, 0x06beecaa, 0x7fd2766a,
0x06d7b648, 0x7fd1251e, 0x06f0b9d1, 0x7fcfcbda, 0x0709f775, 0x7fce6a7a, 0x07236f65, 0x7fcd00d8,
0x073d21d2, 0x7fcb8ecf, 0x07570eea, 0x7fca1439, 0x077136dd, 0x7fc890ed, 0x078b99da, 0x7fc704c7,
0x07a6380d, 0x7fc56f9d, 0x07c111a4, 0x7fc3d147, 0x07dc26cc, 0x7fc2299e, 0x07f777b1, 0x7fc07878,
0x0813047d, 0x7fbebdac, 0x082ecd5b, 0x7fbcf90f, 0x084ad276, 0x7fbb2a78, 0x086713f7, 0x7fb951bc,
0x08839206, 0x7fb76eaf, 0x08a04ccb, 0x7fb58126, 0x08bd446e, 0x7fb388f4, 0x08da7915, 0x7fb185ee,
0x08f7eae7, 0x7faf77e5, 0x09159a09, 0x7fad5ead, 0x0933869f, 0x7fab3a17, 0x0951b0cd, 0x7fa909f6,
0x097018b7, 0x7fa6ce1a, 0x098ebe7f, 0x7fa48653, 0x09ada248, 0x7fa23273, 0x09ccc431, 0x7f9fd249,
0x09ec245b, 0x7f9d65a4, 0x0a0bc2e7, 0x7f9aec53, 0x0a2b9ff3, 0x7f986625, 0x0a4bbb9e, 0x7f95d2e7,
0x0a6c1604, 0x7f933267, 0x0a8caf43, 0x7f908472, 0x0aad8776, 0x7f8dc8d5, 0x0ace9eb9, 0x7f8aff5c,
0x0aeff526, 0x7f8827d3, 0x0b118ad8, 0x7f854204, 0x0b335fe6, 0x7f824dbb, 0x0b557469, 0x7f7f4ac3,
0x0b77c879, 0x7f7c38e4, 0x0b9a5c2b, 0x7f7917e9, 0x0bbd2f97, 0x7f75e79b, 0x0be042d0, 0x7f72a7c3,
0x0c0395ec, 0x7f6f5828, 0x0c2728fd, 0x7f6bf892, 0x0c4afc16, 0x7f6888c9, 0x0c6f0f4a, 0x7f650894,
0x0c9362a8, 0x7f6177b9, 0x0cb7f642, 0x7f5dd5ff, 0x0cdcca26, 0x7f5a232a, 0x0d01de63, 0x7f565f00,
0x0d273307, 0x7f528947, 0x0d4cc81f, 0x7f4ea1c2, 0x0d729db7, 0x7f4aa835, 0x0d98b3da, 0x7f469c65,
0x0dbf0a92, 0x7f427e13, 0x0de5a1e9, 0x7f3e4d04, 0x0e0c79e7, 0x7f3a08f9, 0x0e339295, 0x7f35b1b4,
0x0e5aebfa, 0x7f3146f8, 0x0e82861a, 0x7f2cc884, 0x0eaa60fd, 0x7f28361b, 0x0ed27ca5, 0x7f238f7c,
0x0efad917, 0x7f1ed467, 0x0f237656, 0x7f1a049d, 0x0f4c5462, 0x7f151fdc, 0x0f75733d, 0x7f1025e3,
0x0f9ed2e6, 0x7f0b1672, 0x0fc8735e, 0x7f05f146, 0x0ff254a1, 0x7f00b61d, 0x101c76ae, 0x7efb64b4,
0x1046d981, 0x7ef5fcca, 0x10717d15, 0x7ef07e19, 0x109c6165, 0x7eeae860, 0x10c7866a, 0x7ee53b5b,
0x10f2ec1e, 0x7edf76c4, 0x111e9279, 0x7ed99a58, 0x114a7971, 0x7ed3a5d1, 0x1176a0fc, 0x7ecd98eb,
0x11a30910, 0x7ec77360, 0x11cfb1a1, 0x7ec134eb, 0x11fc9aa2, 0x7ebadd44, 0x1229c406, 0x7eb46c27,
0x12572dbf, 0x7eade14c, 0x1284d7bc, 0x7ea73c6c, 0x12b2c1ed, 0x7ea07d41, 0x12e0ec42, 0x7e99a382,
0x130f56a8, 0x7e92aee7, 0x133e010b, 0x7e8b9f2a, 0x136ceb59, 0x7e847402, 0x139c157b, 0x7e7d2d25,
0x13cb7f5d, 0x7e75ca4c, 0x13fb28e6, 0x7e6e4b2d, 0x142b1200, 0x7e66af7f, 0x145b3a92, 0x7e5ef6f8,
0x148ba281, 0x7e572150, 0x14bc49b4, 0x7e4f2e3b, 0x14ed300f, 0x7e471d70, 0x151e5575, 0x7e3eeea5,
0x154fb9c9, 0x7e36a18e, 0x15815ced, 0x7e2e35e2, 0x15b33ec1, 0x7e25ab56, 0x15e55f25, 0x7e1d019e,
0x1617bdf9, 0x7e14386e, 0x164a5b19, 0x7e0b4f7d, 0x167d3662, 0x7e02467e, 0x16b04fb2, 0x7df91d25,
0x16e3a6e2, 0x7defd327, 0x17173bce, 0x7de66837, 0x174b0e4d, 0x7ddcdc0a, 0x177f1e39, 0x7dd32e53,
0x17b36b69, 0x7dc95ec6, 0x17e7f5b3, 0x7dbf6d17, 0x181cbcec, 0x7db558f9, 0x1851c0e9, 0x7dab221f,
0x1887017d, 0x7da0c83c, 0x18bc7e7c, 0x7d964b05, 0x18f237b6, 0x7d8baa2b, 0x19282cfd, 0x7d80e563,
0x195e5e20, 0x7d75fc5e, 0x1994caee, 0x7d6aeed0, 0x19cb7335, 0x7d5fbc6d, 0x1a0256c2, 0x7d5464e6,
0x1a397561, 0x7d48e7ef, 0x1a70cede, 0x7d3d453b, 0x1aa86301, 0x7d317c7c, 0x1ae03195, 0x7d258d65,
0x1b183a63, 0x7d1977aa, 0x1b507d30, 0x7d0d3afc, 0x1b88f9c5, 0x7d00d710, 0x1bc1afe6, 0x7cf44b97,
0x1bfa9f58, 0x7ce79846, 0x1c33c7e0, 0x7cdabcce, 0x1c6d293f, 0x7ccdb8e4, 0x1ca6c337, 0x7cc08c39,
0x1ce0958a, 0x7cb33682, 0x1d1a9ff8, 0x7ca5b772, 0x1d54e240, 0x7c980ebd, 0x1d8f5c21, 0x7c8a3c14,
0x1dca0d56, 0x7c7c3f2e, 0x1e04f59f, 0x7c6e17bc, 0x1e4014b4, 0x7c5fc573, 0x1e7b6a53, 0x7c514807,
0x1eb6f633, 0x7c429f2c, 0x1ef2b80f, 0x7c33ca96, 0x1f2eaf9e, 0x7c24c9fa, 0x1f6adc98, 0x7c159d0d,
0x1fa73eb2, 0x7c064383, 0x1fe3d5a3, 0x7bf6bd11, 0x2020a11e, 0x7be7096c, 0x205da0d8, 0x7bd7284a,
0x209ad483, 0x7bc71960, 0x20d83bd1, 0x7bb6dc65, 0x2115d674, 0x7ba6710d, 0x2153a41b, 0x7b95d710,
0x2191a476, 0x7b850e24, 0x21cfd734, 0x7b7415ff, 0x220e3c02, 0x7b62ee59, 0x224cd28d, 0x7b5196e9,
0x228b9a82, 0x7b400f67, 0x22ca938a, 0x7b2e578a, 0x2309bd52, 0x7b1c6f0b, 0x23491783, 0x7b0a55a1,
0x2388a1c4, 0x7af80b07, 0x23c85bbf, 0x7ae58ef5, 0x2408451a, 0x7ad2e124, 0x24485d7c, 0x7ac0014e,
0x2488a48a, 0x7aacef2e, 0x24c919e9, 0x7a99aa7e, 0x2509bd3d, 0x7a8632f8, 0x254a8e29, 0x7a728858,
0x258b8c50, 0x7a5eaa5a, 0x25ccb753, 0x7a4a98b9, 0x260e0ed3, 0x7a365333, 0x264f9271, 0x7a21d983,
0x269141cb, 0x7a0d2b68, 0x26d31c80, 0x79f8489e, 0x2715222f, 0x79e330e4, 0x27575273, 0x79cde3f8,
0x2799acea, 0x79b8619a, 0x27dc3130, 0x79a2a989, 0x281ededf, 0x798cbb85, 0x2861b591, 0x7976974e,
0x28a4b4e0, 0x79603ca5, 0x28e7dc65, 0x7949ab4c, 0x292b2bb8, 0x7932e304, 0x296ea270, 0x791be390,
0x29b24024, 0x7904acb3, 0x29f6046b, 0x78ed3e30, 0x2a39eed8, 0x78d597cc, 0x2a7dff02, 0x78bdb94a,
0x2ac2347c, 0x78a5a270, 0x2b068eda, 0x788d5304, 0x2b4b0dae, 0x7874cacb, 0x2b8fb08a, 0x785c098d,
0x2bd47700, 0x78430f11, 0x2c1960a1, 0x7829db1f, 0x2c5e6cfd, 0x78106d7f, 0x2ca39ba3, 0x77f6c5fb,
0x2ce8ec23, 0x77dce45c, 0x2d2e5e0b, 0x77c2c86e, 0x2d73f0e8, 0x77a871fa, 0x2db9a449, 0x778de0cd,
0x2dff77b8, 0x777314b2, 0x2e456ac4, 0x77580d78, 0x2e8b7cf6, 0x773ccaeb, 0x2ed1addb, 0x77214cdb,
0x2f17fcfb, 0x77059315, 0x2f5e69e2, 0x76e99d69, 0x2fa4f419, 0x76cd6ba9, 0x2feb9b27, 0x76b0fda4,
0x30325e96, 0x7694532e, 0x30793dee, 0x76776c17, 0x30c038b5, 0x765a4834, 0x31074e72, 0x763ce759,
0x314e7eab, 0x761f4959, 0x3195c8e6, 0x76016e0b, 0x31dd2ca9, 0x75e35545, 0x3224a979, 0x75c4fedc,
0x326c3ed8, 0x75a66aab, 0x32b3ec4d, 0x75879887, 0x32fbb159, 0x7568884b, 0x33438d81, 0x754939d1,
0x338b8045, 0x7529acf4, 0x33d3892a, 0x7509e18e, 0x341ba7b1, 0x74e9d77d, 0x3463db5a, 0x74c98e9e,
0x34ac23a7, 0x74a906cd, 0x34f48019, 0x74883fec, 0x353cf02f, 0x746739d8, 0x3585736a, 0x7445f472,
0x35ce0949, 0x74246f9c, 0x3616b14c, 0x7402ab37, 0x365f6af0, 0x73e0a727, 0x36a835b5, 0x73be6350,
0x36f11118, 0x739bdf95, 0x3739fc98, 0x73791bdd, 0x3782f7b2, 0x7356180e, 0x37cc01e3, 0x7332d410,
0x38151aa8, 0x730f4fc9, 0x385e417e, 0x72eb8b24, 0x38a775e1, 0x72c7860a, 0x38f0b74d, 0x72a34066,
0x393a053e, 0x727eba24, 0x39835f30, 0x7259f331, 0x39ccc49e, 0x7234eb79, 0x3a163503, 0x720fa2eb,
0x3a5fafda, 0x71ea1977, 0x3aa9349e, 0x71c44f0c, 0x3af2c2ca, 0x719e439d, 0x3b3c59d7, 0x7177f71a,
0x3b85f940, 0x71516978, 0x3bcfa07e, 0x712a9aaa, 0x3c194f0d, 0x71038aa4, 0x3c630464, 0x70dc395e,
0x3cacbfff, 0x70b4a6cd, 0x3cf68155, 0x708cd2e9, 0x3d4047e1, 0x7064bdab, 0x3d8a131c, 0x703c670d,
0x3dd3e27e, 0x7013cf0a, 0x3e1db580, 0x6feaf59c, 0x3e678b9b, 0x6fc1dac1, 0x3eb16449, 0x6f987e76,
0x3efb3f01, 0x6f6ee0b9, 0x3f451b3d, 0x6f45018b, 0x3f8ef874, 0x6f1ae0eb, 0x3fd8d620, 0x6ef07edb,
0x4022b3b9, 0x6ec5db5d, 0x406c90b7, 0x6e9af675, 0x40b66c93, 0x6e6fd027, 0x410046c5, 0x6e446879,
0x414a1ec6, 0x6e18bf71, 0x4193f40d, 0x6decd517, 0x41ddc615, 0x6dc0a972, 0x42279455, 0x6d943c8d,
0x42715e45, 0x6d678e71, 0x42bb235f, 0x6d3a9f2a, 0x4304e31a, 0x6d0d6ec5, 0x434e9cf1, 0x6cdffd4f,
0x4398505b, 0x6cb24ad6, 0x43e1fcd1, 0x6c84576b, 0x442ba1cd, 0x6c56231c, 0x44753ec7, 0x6c27adfd,
0x44bed33a, 0x6bf8f81e, 0x45085e9d, 0x6bca0195, 0x4551e06b, 0x6b9aca75, 0x459b581e, 0x6b6b52d5,
0x45e4c52f, 0x6b3b9ac9, 0x462e2717, 0x6b0ba26b, 0x46777d52, 0x6adb69d3, 0x46c0c75a, 0x6aaaf11b,
0x470a04a9, 0x6a7a385c, 0x475334b9, 0x6a493fb3, 0x479c5707, 0x6a18073d, 0x47e56b0c, 0x69e68f17,
0x482e7045, 0x69b4d761, 0x4877662c, 0x6982e039, 0x48c04c3f, 0x6950a9c0, 0x490921f8, 0x691e341a,
0x4951e6d5, 0x68eb7f67, 0x499a9a51, 0x68b88bcd, 0x49e33beb, 0x68855970, 0x4a2bcb1f, 0x6851e875,
0x4a74476b, 0x681e3905, 0x4abcb04c, 0x67ea4b47, 0x4b050541, 0x67b61f63, 0x4b4d45c9, 0x6781b585,
0x4b957162, 0x674d0dd6, 0x4bdd878c, 0x67182883, 0x4c2587c6, 0x66e305b8, 0x4c6d7190, 0x66ada5a5,
0x4cb5446a, 0x66780878, 0x4cfcffd5, 0x66422e60, 0x4d44a353, 0x660c1790, 0x4d8c2e64, 0x65d5c439,
0x4dd3a08c, 0x659f348e, 0x4e1af94b, 0x656868c3, 0x4e623825, 0x6531610d, 0x4ea95c9d, 0x64fa1da3,
0x4ef06637, 0x64c29ebb, 0x4f375477, 0x648ae48d, 0x4f7e26e1, 0x6452ef53, 0x4fc4dcfb, 0x641abf46,
0x500b7649, 0x63e254a2, 0x5051f253, 0x63a9afa2, 0x5098509f, 0x6370d083, 0x50de90b3, 0x6337b784,
0x5124b218, 0x62fe64e3, 0x516ab455, 0x62c4d8e0, 0x51b096f3, 0x628b13bc, 0x51f6597b, 0x625115b8,
0x523bfb78, 0x6216df18, 0x52817c72, 0x61dc701f, 0x52c6dbf5, 0x61a1c912, 0x530c198d, 0x6166ea36,
0x535134c5, 0x612bd3d2, 0x53962d2a, 0x60f0862d, 0x53db024a, 0x60b50190, 0x541fb3b1, 0x60794644,
0x546440ef, 0x603d5494, 0x54a8a992, 0x60012cca, 0x54eced2b, 0x5fc4cf33, 0x55310b48, 0x5f883c1c,
0x5575037c, 0x5f4b73d2, 0x55b8d558, 0x5f0e76a5, 0x55fc806f, 0x5ed144e5, 0x56400452, 0x5e93dee1,
0x56836096, 0x5e5644ec, 0x56c694cf, 0x5e187757, 0x5709a092, 0x5dda7677, 0x574c8374, 0x5d9c429f,
0x578f3d0d, 0x5d5ddc24, 0x57d1ccf2, 0x5d1f435d, 0x581432bd, 0x5ce078a0, 0x58566e04, 0x5ca17c45,
0x58987e63, 0x5c624ea4, 0x58da6372, 0x5c22f016, 0x591c1ccc, 0x5be360f6, 0x595daa0d, 0x5ba3a19f,
0x599f0ad1, 0x5b63b26c, 0x59e03eb6, 0x5b2393ba, 0x5a214558, 0x5ae345e7, 0x5a621e56, 0x5aa2c951,
};
/* bit reverse tables for FFT */
const int bitrevtabOffset[NUM_IMDCT_SIZES] = {0, 17};
const unsigned char bitrevtab[17 + 129] = {
/* nfft = 64 */
0x01, 0x08, 0x02, 0x04, 0x03, 0x0c, 0x05, 0x0a, 0x07, 0x0e, 0x0b, 0x0d, 0x00, 0x06, 0x09, 0x0f,
0x00,
/* nfft = 512 */
0x01, 0x40, 0x02, 0x20, 0x03, 0x60, 0x04, 0x10, 0x05, 0x50, 0x06, 0x30, 0x07, 0x70, 0x09, 0x48,
0x0a, 0x28, 0x0b, 0x68, 0x0c, 0x18, 0x0d, 0x58, 0x0e, 0x38, 0x0f, 0x78, 0x11, 0x44, 0x12, 0x24,
0x13, 0x64, 0x15, 0x54, 0x16, 0x34, 0x17, 0x74, 0x19, 0x4c, 0x1a, 0x2c, 0x1b, 0x6c, 0x1d, 0x5c,
0x1e, 0x3c, 0x1f, 0x7c, 0x21, 0x42, 0x23, 0x62, 0x25, 0x52, 0x26, 0x32, 0x27, 0x72, 0x29, 0x4a,
0x2b, 0x6a, 0x2d, 0x5a, 0x2e, 0x3a, 0x2f, 0x7a, 0x31, 0x46, 0x33, 0x66, 0x35, 0x56, 0x37, 0x76,
0x39, 0x4e, 0x3b, 0x6e, 0x3d, 0x5e, 0x3f, 0x7e, 0x43, 0x61, 0x45, 0x51, 0x47, 0x71, 0x4b, 0x69,
0x4d, 0x59, 0x4f, 0x79, 0x53, 0x65, 0x57, 0x75, 0x5b, 0x6d, 0x5f, 0x7d, 0x67, 0x73, 0x6f, 0x7b,
0x00, 0x08, 0x14, 0x1c, 0x22, 0x2a, 0x36, 0x3e, 0x41, 0x49, 0x55, 0x5d, 0x63, 0x6b, 0x77, 0x7f,
0x00,
};
const unsigned char uniqueIDTab[8] = {0x5f, 0x4b, 0x43, 0x5f, 0x5f, 0x4a, 0x52, 0x5f};
/* Twiddle tables for FFT
* format = Q30
*
* for (k = 4; k <= N/4; k <<= 1) {
* for (j = 0; j < k; j++) {
* double wr1, wi1, wr2, wi2, wr3, wi3;
*
* wr1 = cos(1.0 * M_PI * j / (2*k));
* wi1 = sin(1.0 * M_PI * j / (2*k));
* wr1 = (wr1 + wi1);
* wi1 = -wi1;
*
* wr2 = cos(2.0 * M_PI * j / (2*k));
* wi2 = sin(2.0 * M_PI * j / (2*k));
* wr2 = (wr2 + wi2);
* wi2 = -wi2;
*
* wr3 = cos(3.0 * M_PI * j / (2*k));
* wi3 = sin(3.0 * M_PI * j / (2*k));
* wr3 = (wr3 + wi3);
* wi3 = -wi3;
*
* if (k & 0xaaaaaaaa) {
* w_odd[iodd++] = (float)wr2;
* w_odd[iodd++] = (float)wi2;
* w_odd[iodd++] = (float)wr1;
* w_odd[iodd++] = (float)wi1;
* w_odd[iodd++] = (float)wr3;
* w_odd[iodd++] = (float)wi3;
* } else {
* w_even[ieven++] = (float)wr2;
* w_even[ieven++] = (float)wi2;
* w_even[ieven++] = (float)wr1;
* w_even[ieven++] = (float)wi1;
* w_even[ieven++] = (float)wr3;
* w_even[ieven++] = (float)wi3;
* }
* }
* }
*/
const int twidTabOdd[8*6 + 32*6 + 128*6] = {
0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x539eba45, 0xe7821d59,
0x4b418bbe, 0xf383a3e2, 0x58c542c5, 0xdc71898d, 0x5a82799a, 0xd2bec333, 0x539eba45, 0xe7821d59,
0x539eba45, 0xc4df2862, 0x539eba45, 0xc4df2862, 0x58c542c5, 0xdc71898d, 0x3248d382, 0xc13ad060,
0x40000000, 0xc0000000, 0x5a82799a, 0xd2bec333, 0x00000000, 0xd2bec333, 0x22a2f4f8, 0xc4df2862,
0x58c542c5, 0xcac933ae, 0xcdb72c7e, 0xf383a3e2, 0x00000000, 0xd2bec333, 0x539eba45, 0xc4df2862,
0xac6145bb, 0x187de2a7, 0xdd5d0b08, 0xe7821d59, 0x4b418bbe, 0xc13ad060, 0xa73abd3b, 0x3536cc52,
0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x45f704f7, 0xf9ba1651,
0x43103085, 0xfcdc1342, 0x48b2b335, 0xf69bf7c9, 0x4b418bbe, 0xf383a3e2, 0x45f704f7, 0xf9ba1651,
0x4fd288dc, 0xed6bf9d1, 0x4fd288dc, 0xed6bf9d1, 0x48b2b335, 0xf69bf7c9, 0x553805f2, 0xe4a2eff6,
0x539eba45, 0xe7821d59, 0x4b418bbe, 0xf383a3e2, 0x58c542c5, 0xdc71898d, 0x569cc31b, 0xe1d4a2c8,
0x4da1fab5, 0xf0730342, 0x5a6690ae, 0xd5052d97, 0x58c542c5, 0xdc71898d, 0x4fd288dc, 0xed6bf9d1,
0x5a12e720, 0xce86ff2a, 0x5a12e720, 0xd76619b6, 0x51d1dc80, 0xea70658a, 0x57cc15bc, 0xc91af976,
0x5a82799a, 0xd2bec333, 0x539eba45, 0xe7821d59, 0x539eba45, 0xc4df2862, 0x5a12e720, 0xce86ff2a,
0x553805f2, 0xe4a2eff6, 0x4da1fab5, 0xc1eb0209, 0x58c542c5, 0xcac933ae, 0x569cc31b, 0xe1d4a2c8,
0x45f704f7, 0xc04ee4b8, 0x569cc31b, 0xc78e9a1d, 0x57cc15bc, 0xdf18f0ce, 0x3cc85709, 0xc013bc39,
0x539eba45, 0xc4df2862, 0x58c542c5, 0xdc71898d, 0x3248d382, 0xc13ad060, 0x4fd288dc, 0xc2c17d52,
0x5987b08a, 0xd9e01006, 0x26b2a794, 0xc3bdbdf6, 0x4b418bbe, 0xc13ad060, 0x5a12e720, 0xd76619b6,
0x1a4608ab, 0xc78e9a1d, 0x45f704f7, 0xc04ee4b8, 0x5a6690ae, 0xd5052d97, 0x0d47d096, 0xcc983f70,
0x40000000, 0xc0000000, 0x5a82799a, 0xd2bec333, 0x00000000, 0xd2bec333, 0x396b3199, 0xc04ee4b8,
0x5a6690ae, 0xd09441bb, 0xf2b82f6a, 0xd9e01006, 0x3248d382, 0xc13ad060, 0x5a12e720, 0xce86ff2a,
0xe5b9f755, 0xe1d4a2c8, 0x2aaa7c7f, 0xc2c17d52, 0x5987b08a, 0xcc983f70, 0xd94d586c, 0xea70658a,
0x22a2f4f8, 0xc4df2862, 0x58c542c5, 0xcac933ae, 0xcdb72c7e, 0xf383a3e2, 0x1a4608ab, 0xc78e9a1d,
0x57cc15bc, 0xc91af976, 0xc337a8f7, 0xfcdc1342, 0x11a855df, 0xcac933ae, 0x569cc31b, 0xc78e9a1d,
0xba08fb09, 0x0645e9af, 0x08df1a8c, 0xce86ff2a, 0x553805f2, 0xc6250a18, 0xb25e054b, 0x0f8cfcbe,
0x00000000, 0xd2bec333, 0x539eba45, 0xc4df2862, 0xac6145bb, 0x187de2a7, 0xf720e574, 0xd76619b6,
0x51d1dc80, 0xc3bdbdf6, 0xa833ea44, 0x20e70f32, 0xee57aa21, 0xdc71898d, 0x4fd288dc, 0xc2c17d52,
0xa5ed18e0, 0x2899e64a, 0xe5b9f755, 0xe1d4a2c8, 0x4da1fab5, 0xc1eb0209, 0xa5996f52, 0x2f6bbe45,
0xdd5d0b08, 0xe7821d59, 0x4b418bbe, 0xc13ad060, 0xa73abd3b, 0x3536cc52, 0xd5558381, 0xed6bf9d1,
0x48b2b335, 0xc0b15502, 0xaac7fa0e, 0x39daf5e8, 0xcdb72c7e, 0xf383a3e2, 0x45f704f7, 0xc04ee4b8,
0xb02d7724, 0x3d3e82ae, 0xc694ce67, 0xf9ba1651, 0x43103085, 0xc013bc39, 0xb74d4ccb, 0x3f4eaafe,
0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x418d2621, 0xfe6deaa1,
0x40c7d2bd, 0xff36f170, 0x424ff28f, 0xfda4f351, 0x43103085, 0xfcdc1342, 0x418d2621, 0xfe6deaa1,
0x4488e37f, 0xfb4ab7db, 0x4488e37f, 0xfb4ab7db, 0x424ff28f, 0xfda4f351, 0x46aa0d6d, 0xf8f21e8e,
0x45f704f7, 0xf9ba1651, 0x43103085, 0xfcdc1342, 0x48b2b335, 0xf69bf7c9, 0x475a5c77, 0xf82a6c6a,
0x43cdd89a, 0xfc135231, 0x4aa22036, 0xf4491311, 0x48b2b335, 0xf69bf7c9, 0x4488e37f, 0xfb4ab7db,
0x4c77a88e, 0xf1fa3ecb, 0x49ffd417, 0xf50ef5de, 0x454149fc, 0xfa824bfd, 0x4e32a956, 0xefb047f2,
0x4b418bbe, 0xf383a3e2, 0x45f704f7, 0xf9ba1651, 0x4fd288dc, 0xed6bf9d1, 0x4c77a88e, 0xf1fa3ecb,
0x46aa0d6d, 0xf8f21e8e, 0x5156b6d9, 0xeb2e1dbe, 0x4da1fab5, 0xf0730342, 0x475a5c77, 0xf82a6c6a,
0x52beac9f, 0xe8f77acf, 0x4ec05432, 0xeeee2d9d, 0x4807eb4b, 0xf7630799, 0x5409ed4b, 0xe6c8d59c,
0x4fd288dc, 0xed6bf9d1, 0x48b2b335, 0xf69bf7c9, 0x553805f2, 0xe4a2eff6, 0x50d86e6d, 0xebeca36c,
0x495aada2, 0xf5d544a7, 0x56488dc5, 0xe28688a4, 0x51d1dc80, 0xea70658a, 0x49ffd417, 0xf50ef5de,
0x573b2635, 0xe0745b24, 0x52beac9f, 0xe8f77acf, 0x4aa22036, 0xf4491311, 0x580f7b19, 0xde6d1f65,
0x539eba45, 0xe7821d59, 0x4b418bbe, 0xf383a3e2, 0x58c542c5, 0xdc71898d, 0x5471e2e6, 0xe61086bc,
0x4bde1089, 0xf2beafed, 0x595c3e2a, 0xda8249b4, 0x553805f2, 0xe4a2eff6, 0x4c77a88e, 0xf1fa3ecb,
0x59d438e5, 0xd8a00bae, 0x55f104dc, 0xe3399167, 0x4d0e4de2, 0xf136580d, 0x5a2d0957, 0xd6cb76c9,
0x569cc31b, 0xe1d4a2c8, 0x4da1fab5, 0xf0730342, 0x5a6690ae, 0xd5052d97, 0x573b2635, 0xe0745b24,
0x4e32a956, 0xefb047f2, 0x5a80baf6, 0xd34dcdb4, 0x57cc15bc, 0xdf18f0ce, 0x4ec05432, 0xeeee2d9d,
0x5a7b7f1a, 0xd1a5ef90, 0x584f7b58, 0xddc29958, 0x4f4af5d1, 0xee2cbbc1, 0x5a56deec, 0xd00e2639,
0x58c542c5, 0xdc71898d, 0x4fd288dc, 0xed6bf9d1, 0x5a12e720, 0xce86ff2a, 0x592d59da, 0xdb25f566,
0x50570819, 0xecabef3d, 0x59afaf4c, 0xcd110216, 0x5987b08a, 0xd9e01006, 0x50d86e6d, 0xebeca36c,
0x592d59da, 0xcbacb0bf, 0x59d438e5, 0xd8a00bae, 0x5156b6d9, 0xeb2e1dbe, 0x588c1404, 0xca5a86c4,
0x5a12e720, 0xd76619b6, 0x51d1dc80, 0xea70658a, 0x57cc15bc, 0xc91af976, 0x5a43b190, 0xd6326a88,
0x5249daa2, 0xe9b38223, 0x56eda1a0, 0xc7ee77b3, 0x5a6690ae, 0xd5052d97, 0x52beac9f, 0xe8f77acf,
0x55f104dc, 0xc6d569be, 0x5a7b7f1a, 0xd3de9156, 0x53304df6, 0xe83c56cf, 0x54d69714, 0xc5d03118,
0x5a82799a, 0xd2bec333, 0x539eba45, 0xe7821d59, 0x539eba45, 0xc4df2862, 0x5a7b7f1a, 0xd1a5ef90,
0x5409ed4b, 0xe6c8d59c, 0x5249daa2, 0xc402a33c, 0x5a6690ae, 0xd09441bb, 0x5471e2e6, 0xe61086bc,
0x50d86e6d, 0xc33aee27, 0x5a43b190, 0xcf89e3e8, 0x54d69714, 0xe55937d5, 0x4f4af5d1, 0xc2884e6e,
0x5a12e720, 0xce86ff2a, 0x553805f2, 0xe4a2eff6, 0x4da1fab5, 0xc1eb0209, 0x59d438e5, 0xcd8bbb6d,
0x55962bc0, 0xe3edb628, 0x4bde1089, 0xc1633f8a, 0x5987b08a, 0xcc983f70, 0x55f104dc, 0xe3399167,
0x49ffd417, 0xc0f1360b, 0x592d59da, 0xcbacb0bf, 0x56488dc5, 0xe28688a4, 0x4807eb4b, 0xc0950d1d,
0x58c542c5, 0xcac933ae, 0x569cc31b, 0xe1d4a2c8, 0x45f704f7, 0xc04ee4b8, 0x584f7b58, 0xc9edeb50,
0x56eda1a0, 0xe123e6ad, 0x43cdd89a, 0xc01ed535, 0x57cc15bc, 0xc91af976, 0x573b2635, 0xe0745b24,
0x418d2621, 0xc004ef3f, 0x573b2635, 0xc8507ea7, 0x57854ddd, 0xdfc606f1, 0x3f35b59d, 0xc0013bd3,
0x569cc31b, 0xc78e9a1d, 0x57cc15bc, 0xdf18f0ce, 0x3cc85709, 0xc013bc39, 0x55f104dc, 0xc6d569be,
0x580f7b19, 0xde6d1f65, 0x3a45e1f7, 0xc03c6a07, 0x553805f2, 0xc6250a18, 0x584f7b58, 0xddc29958,
0x37af354c, 0xc07b371e, 0x5471e2e6, 0xc57d965d, 0x588c1404, 0xdd196538, 0x350536f1, 0xc0d00db6,
0x539eba45, 0xc4df2862, 0x58c542c5, 0xdc71898d, 0x3248d382, 0xc13ad060, 0x52beac9f, 0xc449d892,
0x58fb0568, 0xdbcb0cce, 0x2f7afdfc, 0xc1bb5a11, 0x51d1dc80, 0xc3bdbdf6, 0x592d59da, 0xdb25f566,
0x2c9caf6c, 0xc2517e31, 0x50d86e6d, 0xc33aee27, 0x595c3e2a, 0xda8249b4, 0x29aee694, 0xc2fd08a9,
0x4fd288dc, 0xc2c17d52, 0x5987b08a, 0xd9e01006, 0x26b2a794, 0xc3bdbdf6, 0x4ec05432, 0xc2517e31,
0x59afaf4c, 0xd93f4e9e, 0x23a8fb93, 0xc4935b3c, 0x4da1fab5, 0xc1eb0209, 0x59d438e5, 0xd8a00bae,
0x2092f05f, 0xc57d965d, 0x4c77a88e, 0xc18e18a7, 0x59f54bee, 0xd8024d59, 0x1d719810, 0xc67c1e18,
0x4b418bbe, 0xc13ad060, 0x5a12e720, 0xd76619b6, 0x1a4608ab, 0xc78e9a1d, 0x49ffd417, 0xc0f1360b,
0x5a2d0957, 0xd6cb76c9, 0x17115bc0, 0xc8b4ab32, 0x48b2b335, 0xc0b15502, 0x5a43b190, 0xd6326a88,
0x13d4ae08, 0xc9edeb50, 0x475a5c77, 0xc07b371e, 0x5a56deec, 0xd59afadb, 0x10911f04, 0xcb39edca,
0x45f704f7, 0xc04ee4b8, 0x5a6690ae, 0xd5052d97, 0x0d47d096, 0xcc983f70, 0x4488e37f, 0xc02c64a6,
0x5a72c63b, 0xd4710883, 0x09f9e6a1, 0xce0866b8, 0x43103085, 0xc013bc39, 0x5a7b7f1a, 0xd3de9156,
0x06a886a0, 0xcf89e3e8, 0x418d2621, 0xc004ef3f, 0x5a80baf6, 0xd34dcdb4, 0x0354d741, 0xd11c3142,
0x40000000, 0xc0000000, 0x5a82799a, 0xd2bec333, 0x00000000, 0xd2bec333, 0x3e68fb62, 0xc004ef3f,
0x5a80baf6, 0xd2317756, 0xfcab28bf, 0xd4710883, 0x3cc85709, 0xc013bc39, 0x5a7b7f1a, 0xd1a5ef90,
0xf9577960, 0xd6326a88, 0x3b1e5335, 0xc02c64a6, 0x5a72c63b, 0xd11c3142, 0xf606195f, 0xd8024d59,
0x396b3199, 0xc04ee4b8, 0x5a6690ae, 0xd09441bb, 0xf2b82f6a, 0xd9e01006, 0x37af354c, 0xc07b371e,
0x5a56deec, 0xd00e2639, 0xef6ee0fc, 0xdbcb0cce, 0x35eaa2c7, 0xc0b15502, 0x5a43b190, 0xcf89e3e8,
0xec2b51f8, 0xddc29958, 0x341dbfd3, 0xc0f1360b, 0x5a2d0957, 0xcf077fe1, 0xe8eea440, 0xdfc606f1,
0x3248d382, 0xc13ad060, 0x5a12e720, 0xce86ff2a, 0xe5b9f755, 0xe1d4a2c8, 0x306c2624, 0xc18e18a7,
0x59f54bee, 0xce0866b8, 0xe28e67f0, 0xe3edb628, 0x2e88013a, 0xc1eb0209, 0x59d438e5, 0xcd8bbb6d,
0xdf6d0fa1, 0xe61086bc, 0x2c9caf6c, 0xc2517e31, 0x59afaf4c, 0xcd110216, 0xdc57046d, 0xe83c56cf,
0x2aaa7c7f, 0xc2c17d52, 0x5987b08a, 0xcc983f70, 0xd94d586c, 0xea70658a, 0x28b1b544, 0xc33aee27,
0x595c3e2a, 0xcc217822, 0xd651196c, 0xecabef3d, 0x26b2a794, 0xc3bdbdf6, 0x592d59da, 0xcbacb0bf,
0xd3635094, 0xeeee2d9d, 0x24ada23d, 0xc449d892, 0x58fb0568, 0xcb39edca, 0xd0850204, 0xf136580d,
0x22a2f4f8, 0xc4df2862, 0x58c542c5, 0xcac933ae, 0xcdb72c7e, 0xf383a3e2, 0x2092f05f, 0xc57d965d,
0x588c1404, 0xca5a86c4, 0xcafac90f, 0xf5d544a7, 0x1e7de5df, 0xc6250a18, 0x584f7b58, 0xc9edeb50,
0xc850cab4, 0xf82a6c6a, 0x1c6427a9, 0xc6d569be, 0x580f7b19, 0xc9836582, 0xc5ba1e09, 0xfa824bfd,
0x1a4608ab, 0xc78e9a1d, 0x57cc15bc, 0xc91af976, 0xc337a8f7, 0xfcdc1342, 0x1823dc7d, 0xc8507ea7,
0x57854ddd, 0xc8b4ab32, 0xc0ca4a63, 0xff36f170, 0x15fdf758, 0xc91af976, 0x573b2635, 0xc8507ea7,
0xbe72d9df, 0x0192155f, 0x13d4ae08, 0xc9edeb50, 0x56eda1a0, 0xc7ee77b3, 0xbc322766, 0x03ecadcf,
0x11a855df, 0xcac933ae, 0x569cc31b, 0xc78e9a1d, 0xba08fb09, 0x0645e9af, 0x0f7944a7, 0xcbacb0bf,
0x56488dc5, 0xc730e997, 0xb7f814b5, 0x089cf867, 0x0d47d096, 0xcc983f70, 0x55f104dc, 0xc6d569be,
0xb6002be9, 0x0af10a22, 0x0b145041, 0xcd8bbb6d, 0x55962bc0, 0xc67c1e18, 0xb421ef77, 0x0d415013,
0x08df1a8c, 0xce86ff2a, 0x553805f2, 0xc6250a18, 0xb25e054b, 0x0f8cfcbe, 0x06a886a0, 0xcf89e3e8,
0x54d69714, 0xc5d03118, 0xb0b50a2f, 0x11d3443f, 0x0470ebdc, 0xd09441bb, 0x5471e2e6, 0xc57d965d,
0xaf279193, 0x14135c94, 0x0238a1c6, 0xd1a5ef90, 0x5409ed4b, 0xc52d3d18, 0xadb6255e, 0x164c7ddd,
0x00000000, 0xd2bec333, 0x539eba45, 0xc4df2862, 0xac6145bb, 0x187de2a7, 0xfdc75e3a, 0xd3de9156,
0x53304df6, 0xc4935b3c, 0xab2968ec, 0x1aa6c82b, 0xfb8f1424, 0xd5052d97, 0x52beac9f, 0xc449d892,
0xaa0efb24, 0x1cc66e99, 0xf9577960, 0xd6326a88, 0x5249daa2, 0xc402a33c, 0xa9125e60, 0x1edc1953,
0xf720e574, 0xd76619b6, 0x51d1dc80, 0xc3bdbdf6, 0xa833ea44, 0x20e70f32, 0xf4ebafbf, 0xd8a00bae,
0x5156b6d9, 0xc37b2b6a, 0xa773ebfc, 0x22e69ac8, 0xf2b82f6a, 0xd9e01006, 0x50d86e6d, 0xc33aee27,
0xa6d2a626, 0x24da0a9a, 0xf086bb59, 0xdb25f566, 0x50570819, 0xc2fd08a9, 0xa65050b4, 0x26c0b162,
0xee57aa21, 0xdc71898d, 0x4fd288dc, 0xc2c17d52, 0xa5ed18e0, 0x2899e64a, 0xec2b51f8, 0xddc29958,
0x4f4af5d1, 0xc2884e6e, 0xa5a92114, 0x2a650525, 0xea0208a8, 0xdf18f0ce, 0x4ec05432, 0xc2517e31,
0xa58480e6, 0x2c216eaa, 0xe7dc2383, 0xe0745b24, 0x4e32a956, 0xc21d0eb8, 0xa57f450a, 0x2dce88aa,
0xe5b9f755, 0xe1d4a2c8, 0x4da1fab5, 0xc1eb0209, 0xa5996f52, 0x2f6bbe45, 0xe39bd857, 0xe3399167,
0x4d0e4de2, 0xc1bb5a11, 0xa5d2f6a9, 0x30f8801f, 0xe1821a21, 0xe4a2eff6, 0x4c77a88e, 0xc18e18a7,
0xa62bc71b, 0x32744493, 0xdf6d0fa1, 0xe61086bc, 0x4bde1089, 0xc1633f8a, 0xa6a3c1d6, 0x33de87de,
0xdd5d0b08, 0xe7821d59, 0x4b418bbe, 0xc13ad060, 0xa73abd3b, 0x3536cc52, 0xdb525dc3, 0xe8f77acf,
0x4aa22036, 0xc114ccb9, 0xa7f084e7, 0x367c9a7e, 0xd94d586c, 0xea70658a, 0x49ffd417, 0xc0f1360b,
0xa8c4d9cb, 0x37af8159, 0xd74e4abc, 0xebeca36c, 0x495aada2, 0xc0d00db6, 0xa9b7723b, 0x38cf1669,
0xd5558381, 0xed6bf9d1, 0x48b2b335, 0xc0b15502, 0xaac7fa0e, 0x39daf5e8, 0xd3635094, 0xeeee2d9d,
0x4807eb4b, 0xc0950d1d, 0xabf612b5, 0x3ad2c2e8, 0xd177fec6, 0xf0730342, 0x475a5c77, 0xc07b371e,
0xad415361, 0x3bb6276e, 0xcf93d9dc, 0xf1fa3ecb, 0x46aa0d6d, 0xc063d405, 0xaea94927, 0x3c84d496,
0xcdb72c7e, 0xf383a3e2, 0x45f704f7, 0xc04ee4b8, 0xb02d7724, 0x3d3e82ae, 0xcbe2402d, 0xf50ef5de,
0x454149fc, 0xc03c6a07, 0xb1cd56aa, 0x3de2f148, 0xca155d39, 0xf69bf7c9, 0x4488e37f, 0xc02c64a6,
0xb3885772, 0x3e71e759, 0xc850cab4, 0xf82a6c6a, 0x43cdd89a, 0xc01ed535, 0xb55ddfca, 0x3eeb3347,
0xc694ce67, 0xf9ba1651, 0x43103085, 0xc013bc39, 0xb74d4ccb, 0x3f4eaafe, 0xc4e1accb, 0xfb4ab7db,
0x424ff28f, 0xc00b1a20, 0xb955f293, 0x3f9c2bfb, 0xc337a8f7, 0xfcdc1342, 0x418d2621, 0xc004ef3f,
0xbb771c81, 0x3fd39b5a, 0xc197049e, 0xfe6deaa1, 0x40c7d2bd, 0xc0013bd3, 0xbdb00d71, 0x3ff4e5e0,
};
const int twidTabEven[4*6 + 16*6 + 64*6] = {
0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x5a82799a, 0xd2bec333,
0x539eba45, 0xe7821d59, 0x539eba45, 0xc4df2862, 0x40000000, 0xc0000000, 0x5a82799a, 0xd2bec333,
0x00000000, 0xd2bec333, 0x00000000, 0xd2bec333, 0x539eba45, 0xc4df2862, 0xac6145bb, 0x187de2a7,
0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x4b418bbe, 0xf383a3e2,
0x45f704f7, 0xf9ba1651, 0x4fd288dc, 0xed6bf9d1, 0x539eba45, 0xe7821d59, 0x4b418bbe, 0xf383a3e2,
0x58c542c5, 0xdc71898d, 0x58c542c5, 0xdc71898d, 0x4fd288dc, 0xed6bf9d1, 0x5a12e720, 0xce86ff2a,
0x5a82799a, 0xd2bec333, 0x539eba45, 0xe7821d59, 0x539eba45, 0xc4df2862, 0x58c542c5, 0xcac933ae,
0x569cc31b, 0xe1d4a2c8, 0x45f704f7, 0xc04ee4b8, 0x539eba45, 0xc4df2862, 0x58c542c5, 0xdc71898d,
0x3248d382, 0xc13ad060, 0x4b418bbe, 0xc13ad060, 0x5a12e720, 0xd76619b6, 0x1a4608ab, 0xc78e9a1d,
0x40000000, 0xc0000000, 0x5a82799a, 0xd2bec333, 0x00000000, 0xd2bec333, 0x3248d382, 0xc13ad060,
0x5a12e720, 0xce86ff2a, 0xe5b9f755, 0xe1d4a2c8, 0x22a2f4f8, 0xc4df2862, 0x58c542c5, 0xcac933ae,
0xcdb72c7e, 0xf383a3e2, 0x11a855df, 0xcac933ae, 0x569cc31b, 0xc78e9a1d, 0xba08fb09, 0x0645e9af,
0x00000000, 0xd2bec333, 0x539eba45, 0xc4df2862, 0xac6145bb, 0x187de2a7, 0xee57aa21, 0xdc71898d,
0x4fd288dc, 0xc2c17d52, 0xa5ed18e0, 0x2899e64a, 0xdd5d0b08, 0xe7821d59, 0x4b418bbe, 0xc13ad060,
0xa73abd3b, 0x3536cc52, 0xcdb72c7e, 0xf383a3e2, 0x45f704f7, 0xc04ee4b8, 0xb02d7724, 0x3d3e82ae,
0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x43103085, 0xfcdc1342,
0x418d2621, 0xfe6deaa1, 0x4488e37f, 0xfb4ab7db, 0x45f704f7, 0xf9ba1651, 0x43103085, 0xfcdc1342,
0x48b2b335, 0xf69bf7c9, 0x48b2b335, 0xf69bf7c9, 0x4488e37f, 0xfb4ab7db, 0x4c77a88e, 0xf1fa3ecb,
0x4b418bbe, 0xf383a3e2, 0x45f704f7, 0xf9ba1651, 0x4fd288dc, 0xed6bf9d1, 0x4da1fab5, 0xf0730342,
0x475a5c77, 0xf82a6c6a, 0x52beac9f, 0xe8f77acf, 0x4fd288dc, 0xed6bf9d1, 0x48b2b335, 0xf69bf7c9,
0x553805f2, 0xe4a2eff6, 0x51d1dc80, 0xea70658a, 0x49ffd417, 0xf50ef5de, 0x573b2635, 0xe0745b24,
0x539eba45, 0xe7821d59, 0x4b418bbe, 0xf383a3e2, 0x58c542c5, 0xdc71898d, 0x553805f2, 0xe4a2eff6,
0x4c77a88e, 0xf1fa3ecb, 0x59d438e5, 0xd8a00bae, 0x569cc31b, 0xe1d4a2c8, 0x4da1fab5, 0xf0730342,
0x5a6690ae, 0xd5052d97, 0x57cc15bc, 0xdf18f0ce, 0x4ec05432, 0xeeee2d9d, 0x5a7b7f1a, 0xd1a5ef90,
0x58c542c5, 0xdc71898d, 0x4fd288dc, 0xed6bf9d1, 0x5a12e720, 0xce86ff2a, 0x5987b08a, 0xd9e01006,
0x50d86e6d, 0xebeca36c, 0x592d59da, 0xcbacb0bf, 0x5a12e720, 0xd76619b6, 0x51d1dc80, 0xea70658a,
0x57cc15bc, 0xc91af976, 0x5a6690ae, 0xd5052d97, 0x52beac9f, 0xe8f77acf, 0x55f104dc, 0xc6d569be,
0x5a82799a, 0xd2bec333, 0x539eba45, 0xe7821d59, 0x539eba45, 0xc4df2862, 0x5a6690ae, 0xd09441bb,
0x5471e2e6, 0xe61086bc, 0x50d86e6d, 0xc33aee27, 0x5a12e720, 0xce86ff2a, 0x553805f2, 0xe4a2eff6,
0x4da1fab5, 0xc1eb0209, 0x5987b08a, 0xcc983f70, 0x55f104dc, 0xe3399167, 0x49ffd417, 0xc0f1360b,
0x58c542c5, 0xcac933ae, 0x569cc31b, 0xe1d4a2c8, 0x45f704f7, 0xc04ee4b8, 0x57cc15bc, 0xc91af976,
0x573b2635, 0xe0745b24, 0x418d2621, 0xc004ef3f, 0x569cc31b, 0xc78e9a1d, 0x57cc15bc, 0xdf18f0ce,
0x3cc85709, 0xc013bc39, 0x553805f2, 0xc6250a18, 0x584f7b58, 0xddc29958, 0x37af354c, 0xc07b371e,
0x539eba45, 0xc4df2862, 0x58c542c5, 0xdc71898d, 0x3248d382, 0xc13ad060, 0x51d1dc80, 0xc3bdbdf6,
0x592d59da, 0xdb25f566, 0x2c9caf6c, 0xc2517e31, 0x4fd288dc, 0xc2c17d52, 0x5987b08a, 0xd9e01006,
0x26b2a794, 0xc3bdbdf6, 0x4da1fab5, 0xc1eb0209, 0x59d438e5, 0xd8a00bae, 0x2092f05f, 0xc57d965d,
0x4b418bbe, 0xc13ad060, 0x5a12e720, 0xd76619b6, 0x1a4608ab, 0xc78e9a1d, 0x48b2b335, 0xc0b15502,
0x5a43b190, 0xd6326a88, 0x13d4ae08, 0xc9edeb50, 0x45f704f7, 0xc04ee4b8, 0x5a6690ae, 0xd5052d97,
0x0d47d096, 0xcc983f70, 0x43103085, 0xc013bc39, 0x5a7b7f1a, 0xd3de9156, 0x06a886a0, 0xcf89e3e8,
0x40000000, 0xc0000000, 0x5a82799a, 0xd2bec333, 0x00000000, 0xd2bec333, 0x3cc85709, 0xc013bc39,
0x5a7b7f1a, 0xd1a5ef90, 0xf9577960, 0xd6326a88, 0x396b3199, 0xc04ee4b8, 0x5a6690ae, 0xd09441bb,
0xf2b82f6a, 0xd9e01006, 0x35eaa2c7, 0xc0b15502, 0x5a43b190, 0xcf89e3e8, 0xec2b51f8, 0xddc29958,
0x3248d382, 0xc13ad060, 0x5a12e720, 0xce86ff2a, 0xe5b9f755, 0xe1d4a2c8, 0x2e88013a, 0xc1eb0209,
0x59d438e5, 0xcd8bbb6d, 0xdf6d0fa1, 0xe61086bc, 0x2aaa7c7f, 0xc2c17d52, 0x5987b08a, 0xcc983f70,
0xd94d586c, 0xea70658a, 0x26b2a794, 0xc3bdbdf6, 0x592d59da, 0xcbacb0bf, 0xd3635094, 0xeeee2d9d,
0x22a2f4f8, 0xc4df2862, 0x58c542c5, 0xcac933ae, 0xcdb72c7e, 0xf383a3e2, 0x1e7de5df, 0xc6250a18,
0x584f7b58, 0xc9edeb50, 0xc850cab4, 0xf82a6c6a, 0x1a4608ab, 0xc78e9a1d, 0x57cc15bc, 0xc91af976,
0xc337a8f7, 0xfcdc1342, 0x15fdf758, 0xc91af976, 0x573b2635, 0xc8507ea7, 0xbe72d9df, 0x0192155f,
0x11a855df, 0xcac933ae, 0x569cc31b, 0xc78e9a1d, 0xba08fb09, 0x0645e9af, 0x0d47d096, 0xcc983f70,
0x55f104dc, 0xc6d569be, 0xb6002be9, 0x0af10a22, 0x08df1a8c, 0xce86ff2a, 0x553805f2, 0xc6250a18,
0xb25e054b, 0x0f8cfcbe, 0x0470ebdc, 0xd09441bb, 0x5471e2e6, 0xc57d965d, 0xaf279193, 0x14135c94,
0x00000000, 0xd2bec333, 0x539eba45, 0xc4df2862, 0xac6145bb, 0x187de2a7, 0xfb8f1424, 0xd5052d97,
0x52beac9f, 0xc449d892, 0xaa0efb24, 0x1cc66e99, 0xf720e574, 0xd76619b6, 0x51d1dc80, 0xc3bdbdf6,
0xa833ea44, 0x20e70f32, 0xf2b82f6a, 0xd9e01006, 0x50d86e6d, 0xc33aee27, 0xa6d2a626, 0x24da0a9a,
0xee57aa21, 0xdc71898d, 0x4fd288dc, 0xc2c17d52, 0xa5ed18e0, 0x2899e64a, 0xea0208a8, 0xdf18f0ce,
0x4ec05432, 0xc2517e31, 0xa58480e6, 0x2c216eaa, 0xe5b9f755, 0xe1d4a2c8, 0x4da1fab5, 0xc1eb0209,
0xa5996f52, 0x2f6bbe45, 0xe1821a21, 0xe4a2eff6, 0x4c77a88e, 0xc18e18a7, 0xa62bc71b, 0x32744493,
0xdd5d0b08, 0xe7821d59, 0x4b418bbe, 0xc13ad060, 0xa73abd3b, 0x3536cc52, 0xd94d586c, 0xea70658a,
0x49ffd417, 0xc0f1360b, 0xa8c4d9cb, 0x37af8159, 0xd5558381, 0xed6bf9d1, 0x48b2b335, 0xc0b15502,
0xaac7fa0e, 0x39daf5e8, 0xd177fec6, 0xf0730342, 0x475a5c77, 0xc07b371e, 0xad415361, 0x3bb6276e,
0xcdb72c7e, 0xf383a3e2, 0x45f704f7, 0xc04ee4b8, 0xb02d7724, 0x3d3e82ae, 0xca155d39, 0xf69bf7c9,
0x4488e37f, 0xc02c64a6, 0xb3885772, 0x3e71e759, 0xc694ce67, 0xf9ba1651, 0x43103085, 0xc013bc39,
0xb74d4ccb, 0x3f4eaafe, 0xc337a8f7, 0xfcdc1342, 0x418d2621, 0xc004ef3f, 0xbb771c81, 0x3fd39b5a,
};
/* for reference, here's the code to generate the bitreverse tables
short blocks: nbits = 4 (nfft = 64)
long blocks: nbits = 7 (nfft = 512)
static int bitrev(int n, int nbits)
{
int r, i;
r = 0;
for (i = 0; i < nbits; i++) {
r <<= 1;
r |= (n & 1);
n >>= 1;
}
return r;
}
static void InitBitrevTable(unsigned char *out, int nbits)
{
int i, t;
for (i = 0; i < (1<<nbits); i++) {
/ *** do not register the same transposition twice *** /
t = bitrev(i,nbits);
if (i < t) {
*out++ = (unsigned char)i;
*out++ = (unsigned char)t;
}
}
/ *** no need to write a sentinel (or rather, the first entry in the
* table for symetric codes will be 0, which serves as the sentinel)
*** /
for (i = 0; i < (1<<nbits); i++) {
t = bitrev(i,nbits);
if (i == t) / *** symmetric codes get special treatment *** /
*out++ = (unsigned char)t;
}
*out++ = 0; / *** second sentinel is 0, again *** /
}
*/
/* code to generate KBD window:
static double CalcI0(double x)
{
int k;
double i0, iTmp, iLast, x2, xPow, kFact;
x2 = x / 2.0;
i0 = 0.0;
k = 0;
kFact = 1;
xPow = 1;
do {
iLast = i0;
iTmp = xPow / kFact;
i0 += (iTmp*iTmp);
k++;
kFact *= k;
xPow *= x2;
} while (fabs(i0 - iLast) > KBD_THRESH);
return i0;
}
static double CalcW(double nRef, double n, double a)
{
double i0Base, i0Curr, nTemp;
i0Base = CalcI0(M_PI * a);
nTemp = (n - nRef/4) / (nRef/4);
i0Curr = CalcI0( M_PI * a * sqrt(1.0 - nTemp*nTemp) );
return i0Curr / i0Base;
}
void InitKBDWindow(int nmdct)
{
int n, nRef;
double a, wBase, wCurr;
nRef = nmdct * 2;
/ *** kbd window *** /
if (nmdct == 128)
a = 6.0;
else
a = 4.0;
wBase = 0;
for (n = 0; n <= nRef/2; n++)
wBase += CalcW(nRef, n, a);
/ *** left *** /
wCurr = 0;
for (n = 0; n < nRef/2; n++) {
wCurr += CalcW(nRef, n, a);
kbdWindowRef[n] = sqrt(wCurr / wBase);
}
/ ***
* symmetry:
* kbd_right(n) = kbd_ldef(N_REF - 1 - n), n = [N_REF/2, N_REF - 1]
*
* wCurr = 0;
* for (n = N_REF-1; n >= N_REF/2; n--) {
* wCurr += CalcW(N_REF-n-1, a);
* kbdWindowRef[n] = sqrt(wCurr / wBase);
* }
*
*** /
return;
}
*/
|
1137519-player
|
aac/trigtabs.c
|
C
|
lgpl
| 75,186
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbrfft.c,v 1.1 2005/02/26 01:47:35 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com), Ken Cooke (kenc@real.com)
* February 2005
*
* sbrfft.c - optimized FFT for SBR QMF filters
**************************************************************************************/
#include "sbr.h"
#include "assembly.h"
#define SQRT1_2 0x5a82799a
/* swap RE{p0} with RE{p1} and IM{P0} with IM{P1} */
#define swapcplx(p0,p1) \
t = p0; t1 = *(&(p0)+1); p0 = p1; *(&(p0)+1) = *(&(p1)+1); p1 = t; *(&(p1)+1) = t1
/* nfft = 32, hard coded since small, fixed size FFT
static const unsigned char bitrevtab32[9] = {
0x01, 0x04, 0x03, 0x06, 0x00, 0x02, 0x05, 0x07, 0x00,
};
*/
/* twiddle table for radix 4 pass, format = Q31 */
static const int twidTabOdd32[8*6] = {
0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x539eba45, 0xe7821d59,
0x4b418bbe, 0xf383a3e2, 0x58c542c5, 0xdc71898d, 0x5a82799a, 0xd2bec333, 0x539eba45, 0xe7821d59,
0x539eba45, 0xc4df2862, 0x539eba45, 0xc4df2862, 0x58c542c5, 0xdc71898d, 0x3248d382, 0xc13ad060,
0x40000000, 0xc0000000, 0x5a82799a, 0xd2bec333, 0x00000000, 0xd2bec333, 0x22a2f4f8, 0xc4df2862,
0x58c542c5, 0xcac933ae, 0xcdb72c7e, 0xf383a3e2, 0x00000000, 0xd2bec333, 0x539eba45, 0xc4df2862,
0xac6145bb, 0x187de2a7, 0xdd5d0b08, 0xe7821d59, 0x4b418bbe, 0xc13ad060, 0xa73abd3b, 0x3536cc52,
};
/**************************************************************************************
* Function: BitReverse32
*
* Description: Ken's fast in-place bit reverse
*
* Inputs: buffer of 32 complex samples
*
* Outputs: bit-reversed samples in same buffer
*
* Return: none
**************************************************************************************/
static void BitReverse32(int *inout)
{
int t, t1;
swapcplx(inout[2], inout[32]);
swapcplx(inout[4], inout[16]);
swapcplx(inout[6], inout[48]);
swapcplx(inout[10], inout[40]);
swapcplx(inout[12], inout[24]);
swapcplx(inout[14], inout[56]);
swapcplx(inout[18], inout[36]);
swapcplx(inout[22], inout[52]);
swapcplx(inout[26], inout[44]);
swapcplx(inout[30], inout[60]);
swapcplx(inout[38], inout[50]);
swapcplx(inout[46], inout[58]);
}
/**************************************************************************************
* Function: R8FirstPass32
*
* Description: radix-8 trivial pass for decimation-in-time FFT (log2(N) = 5)
*
* Inputs: buffer of (bit-reversed) samples
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: assumes 3 guard bits, gains 1 integer bit
* guard bits out = guard bits in - 3 (if inputs are full scale)
* or guard bits in - 2 (if inputs bounded to +/- sqrt(2)/2)
* see scaling comments in fft.c for base AAC
* should compile with no stack spills on ARM (verify compiled output)
* current instruction count (per pass): 16 LDR, 16 STR, 4 SMULL, 61 ALU
**************************************************************************************/
static void R8FirstPass32(int *r0)
{
int r1, r2, r3, r4, r5, r6, r7;
int r8, r9, r10, r11, r12, r14;
/* number of passes = fft size / 8 = 32 / 8 = 4 */
r1 = (32 >> 3);
do {
r2 = r0[8];
r3 = r0[9];
r4 = r0[10];
r5 = r0[11];
r6 = r0[12];
r7 = r0[13];
r8 = r0[14];
r9 = r0[15];
r10 = r2 + r4;
r11 = r3 + r5;
r12 = r6 + r8;
r14 = r7 + r9;
r2 -= r4;
r3 -= r5;
r6 -= r8;
r7 -= r9;
r4 = r2 - r7;
r5 = r2 + r7;
r8 = r3 - r6;
r9 = r3 + r6;
r2 = r4 - r9;
r3 = r4 + r9;
r6 = r5 - r8;
r7 = r5 + r8;
r2 = MULSHIFT32(SQRT1_2, r2); /* can use r4, r5, r8, or r9 for constant and lo32 scratch reg */
r3 = MULSHIFT32(SQRT1_2, r3);
r6 = MULSHIFT32(SQRT1_2, r6);
r7 = MULSHIFT32(SQRT1_2, r7);
r4 = r10 + r12;
r5 = r10 - r12;
r8 = r11 + r14;
r9 = r11 - r14;
r10 = r0[0];
r11 = r0[2];
r12 = r0[4];
r14 = r0[6];
r10 += r11;
r12 += r14;
r4 >>= 1;
r10 += r12;
r4 += (r10 >> 1);
r0[ 0] = r4;
r4 -= (r10 >> 1);
r4 = (r10 >> 1) - r4;
r0[ 8] = r4;
r9 >>= 1;
r10 -= 2*r12;
r4 = (r10 >> 1) + r9;
r0[ 4] = r4;
r4 = (r10 >> 1) - r9;
r0[12] = r4;
r10 += r12;
r10 -= 2*r11;
r12 -= 2*r14;
r4 = r0[1];
r9 = r0[3];
r11 = r0[5];
r14 = r0[7];
r4 += r9;
r11 += r14;
r8 >>= 1;
r4 += r11;
r8 += (r4 >> 1);
r0[ 1] = r8;
r8 -= (r4 >> 1);
r8 = (r4 >> 1) - r8;
r0[ 9] = r8;
r5 >>= 1;
r4 -= 2*r11;
r8 = (r4 >> 1) - r5;
r0[ 5] = r8;
r8 = (r4 >> 1) + r5;
r0[13] = r8;
r4 += r11;
r4 -= 2*r9;
r11 -= 2*r14;
r9 = r10 - r11;
r10 += r11;
r14 = r4 + r12;
r4 -= r12;
r5 = (r10 >> 1) + r7;
r8 = (r4 >> 1) - r6;
r0[ 2] = r5;
r0[ 3] = r8;
r5 = (r9 >> 1) - r2;
r8 = (r14 >> 1) - r3;
r0[ 6] = r5;
r0[ 7] = r8;
r5 = (r10 >> 1) - r7;
r8 = (r4 >> 1) + r6;
r0[10] = r5;
r0[11] = r8;
r5 = (r9 >> 1) + r2;
r8 = (r14 >> 1) + r3;
r0[14] = r5;
r0[15] = r8;
r0 += 16;
r1--;
} while (r1 != 0);
}
/**************************************************************************************
* Function: R4Core32
*
* Description: radix-4 pass for 32-point decimation-in-time FFT
*
* Inputs: buffer of samples
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: gain 2 integer bits
* guard bits out = guard bits in - 1 (if inputs are full scale)
* see scaling comments in fft.c for base AAC
* uses 3-mul, 3-add butterflies instead of 4-mul, 2-add
* should compile with no stack spills on ARM (verify compiled output)
* current instruction count (per pass): 16 LDR, 16 STR, 4 SMULL, 61 ALU
**************************************************************************************/
static void R4Core32(int *r0)
{
int r2, r3, r4, r5, r6, r7;
int r8, r9, r10, r12, r14;
int *r1;
r1 = (int *)twidTabOdd32;
r10 = 8;
do {
/* can use r14 for lo32 scratch register in all MULSHIFT32 */
r2 = r1[0];
r3 = r1[1];
r4 = r0[16];
r5 = r0[17];
r12 = r4 + r5;
r12 = MULSHIFT32(r3, r12);
r5 = MULSHIFT32(r2, r5) + r12;
r2 += 2*r3;
r4 = MULSHIFT32(r2, r4) - r12;
r2 = r1[2];
r3 = r1[3];
r6 = r0[32];
r7 = r0[33];
r12 = r6 + r7;
r12 = MULSHIFT32(r3, r12);
r7 = MULSHIFT32(r2, r7) + r12;
r2 += 2*r3;
r6 = MULSHIFT32(r2, r6) - r12;
r2 = r1[4];
r3 = r1[5];
r8 = r0[48];
r9 = r0[49];
r12 = r8 + r9;
r12 = MULSHIFT32(r3, r12);
r9 = MULSHIFT32(r2, r9) + r12;
r2 += 2*r3;
r8 = MULSHIFT32(r2, r8) - r12;
r2 = r0[0];
r3 = r0[1];
r12 = r6 + r8;
r8 = r6 - r8;
r14 = r9 - r7;
r9 = r9 + r7;
r6 = (r2 >> 2) - r4;
r7 = (r3 >> 2) - r5;
r4 += (r2 >> 2);
r5 += (r3 >> 2);
r2 = r4 + r12;
r3 = r5 + r9;
r0[0] = r2;
r0[1] = r3;
r2 = r6 - r14;
r3 = r7 - r8;
r0[16] = r2;
r0[17] = r3;
r2 = r4 - r12;
r3 = r5 - r9;
r0[32] = r2;
r0[33] = r3;
r2 = r6 + r14;
r3 = r7 + r8;
r0[48] = r2;
r0[49] = r3;
r0 += 2;
r1 += 6;
r10--;
} while (r10 != 0);
}
/**************************************************************************************
* Function: FFT32C
*
* Description: Ken's very fast in-place radix-4 decimation-in-time FFT
*
* Inputs: buffer of 32 complex samples (before bit-reversal)
*
* Outputs: processed samples in same buffer
*
* Return: none
*
* Notes: assumes 3 guard bits in, gains 3 integer bits
* guard bits out = guard bits in - 2
* (guard bit analysis includes assumptions about steps immediately
* before and after, i.e. PreMul and PostMul for DCT)
**************************************************************************************/
void FFT32C(int *x)
{
/* decimation in time */
BitReverse32(x);
/* 32-point complex FFT */
R8FirstPass32(x); /* gain 1 int bit, lose 2 GB (making assumptions about input) */
R4Core32(x); /* gain 2 int bits, lose 0 GB (making assumptions about input) */
}
|
1137519-player
|
aac/sbrfft.c
|
C
|
lgpl
| 9,825
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: aaccommon.h,v 1.1 2005/02/26 01:47:34 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* aaccommon.h - implementation-independent API's, datatypes, and definitions
**************************************************************************************/
#ifndef _AACCOMMON_H
#define _AACCOMMON_H
#include "aacdec.h"
#include "statname.h"
/* 12-bit syncword */
#define SYNCWORDH 0xff
#define SYNCWORDL 0xf0
#define MAX_NCHANS_ELEM 2 /* max number of channels in any single bitstream element (SCE,CPE,CCE,LFE) */
#define ADTS_HEADER_BYTES 7
#define NUM_SAMPLE_RATES 12
#define NUM_DEF_CHAN_MAPS 8
#define NUM_ELEMENTS 8
#define MAX_NUM_PCE_ADIF 16
#define MAX_WIN_GROUPS 8
#define MAX_SFB_SHORT 15
#define MAX_SF_BANDS (MAX_SFB_SHORT*MAX_WIN_GROUPS) /* worst case = 15 sfb's * 8 windows for short block */
#define MAX_MS_MASK_BYTES ((MAX_SF_BANDS + 7) >> 3)
#define MAX_PRED_SFB 41
#define MAX_TNS_FILTERS 8
#define MAX_TNS_COEFS 60
#define MAX_TNS_ORDER 20
#define MAX_PULSES 4
#define MAX_GAIN_BANDS 3
#define MAX_GAIN_WIN 8
#define MAX_GAIN_ADJUST 7
#define NSAMPS_LONG 1024
#define NSAMPS_SHORT 128
#define NUM_SYN_ID_BITS 3
#define NUM_INST_TAG_BITS 4
#define EXT_SBR_DATA 0x0d
#define EXT_SBR_DATA_CRC 0x0e
#define IS_ADIF(p) ((p)[0] == 'A' && (p)[1] == 'D' && (p)[2] == 'I' && (p)[3] == 'F')
#define GET_ELE_ID(p) ((AACElementID)(*(p) >> (8-NUM_SYN_ID_BITS)))
/* AAC file format */
enum {
AAC_FF_Unknown = 0, /* should be 0 on init */
AAC_FF_ADTS = 1,
AAC_FF_ADIF = 2,
AAC_FF_RAW = 3
};
/* syntactic element type */
enum {
AAC_ID_INVALID = -1,
AAC_ID_SCE = 0,
AAC_ID_CPE = 1,
AAC_ID_CCE = 2,
AAC_ID_LFE = 3,
AAC_ID_DSE = 4,
AAC_ID_PCE = 5,
AAC_ID_FIL = 6,
AAC_ID_END = 7
};
typedef struct _AACDecInfo {
/* pointers to platform-specific state information */
void *psInfoBase; /* baseline MPEG-4 LC decoding */
void *psInfoSBR; /* MPEG-4 SBR decoding */
/* raw decoded data, before rounding to 16-bit PCM (for postprocessing such as SBR) */
void *rawSampleBuf[AAC_MAX_NCHANS];
int rawSampleBytes;
int rawSampleFBits;
/* fill data (can be used for processing SBR or other extensions) */
unsigned char *fillBuf;
int fillCount;
int fillExtType;
/* block information */
int prevBlockID;
int currBlockID;
int currInstTag;
int sbDeinterleaveReqd[MAX_NCHANS_ELEM];
int adtsBlocksLeft;
/* user-accessible info */
int bitRate;
int nChans;
int sampRate;
int profile;
int format;
int sbrEnabled;
int tnsUsed;
int pnsUsed;
int frameCount;
} AACDecInfo;
/* decoder functions which must be implemented for each platform */
AACDecInfo *AllocateBuffers(void);
void FreeBuffers(AACDecInfo *aacDecInfo);
void ClearBuffer(void *buf, int nBytes);
int UnpackADTSHeader(AACDecInfo *aacDecInfo, unsigned char **buf, int *bitOffset, int *bitsAvail);
int GetADTSChannelMapping(AACDecInfo *aacDecInfo, unsigned char *buf, int bitOffset, int bitsAvail);
int UnpackADIFHeader(AACDecInfo *aacDecInfo, unsigned char **buf, int *bitOffset, int *bitsAvail);
int SetRawBlockParams(AACDecInfo *aacDecInfo, int copyLast, int nChans, int sampRate, int profile);
int PrepareRawBlock(AACDecInfo *aacDecInfo);
int FlushCodec(AACDecInfo *aacDecInfo);
int DecodeNextElement(AACDecInfo *aacDecInfo, unsigned char **buf, int *bitOffset, int *bitsAvail);
int DecodeNoiselessData(AACDecInfo *aacDecInfo, unsigned char **buf, int *bitOffset, int *bitsAvail, int ch);
int Dequantize(AACDecInfo *aacDecInfo, int ch);
int StereoProcess(AACDecInfo *aacDecInfo);
int DeinterleaveShortBlocks(AACDecInfo *aacDecInfo, int ch);
int PNS(AACDecInfo *aacDecInfo, int ch);
int TNSFilter(AACDecInfo *aacDecInfo, int ch);
int IMDCT(AACDecInfo *aacDecInfo, int ch, int chBase, short *outbuf);
/* SBR specific functions */
int InitSBR(AACDecInfo *aacDecInfo);
void FreeSBR(AACDecInfo *aacDecInfo);
int DecodeSBRBitstream(AACDecInfo *aacDecInfo, int chBase);
int DecodeSBRData(AACDecInfo *aacDecInfo, int chBase, short *outbuf);
int FlushCodecSBR(AACDecInfo *aacDecInfo);
/* aactabs.c - global ROM tables */
extern const int sampRateTab[NUM_SAMPLE_RATES];
extern const int predSFBMax[NUM_SAMPLE_RATES];
extern const int channelMapTab[NUM_DEF_CHAN_MAPS];
extern const int elementNumChans[NUM_ELEMENTS];
extern const unsigned char sfBandTotalShort[NUM_SAMPLE_RATES];
extern const unsigned char sfBandTotalLong[NUM_SAMPLE_RATES];
extern const int sfBandTabShortOffset[NUM_SAMPLE_RATES];
extern const short sfBandTabShort[76];
extern const int sfBandTabLongOffset[NUM_SAMPLE_RATES];
extern const short sfBandTabLong[325];
extern const int tnsMaxBandsShortOffset[AAC_NUM_PROFILES];
extern const unsigned char tnsMaxBandsShort[2*NUM_SAMPLE_RATES];
extern const unsigned char tnsMaxOrderShort[AAC_NUM_PROFILES];
extern const int tnsMaxBandsLongOffset[AAC_NUM_PROFILES];
extern const unsigned char tnsMaxBandsLong[2*NUM_SAMPLE_RATES];
extern const unsigned char tnsMaxOrderLong[AAC_NUM_PROFILES];
#endif /* _AACCOMMON_H */
|
1137519-player
|
aac/aaccommon.h
|
C
|
lgpl
| 6,801
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: aacdec.h,v 1.10 2008/06/05 13:00:25 vkathuria Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* aacdec.h - public C API for AAC decoder
**************************************************************************************/
#ifndef _AACDEC_H
#define _AACDEC_H
#if defined(_WIN32) && !defined(_WIN32_WCE)
#
#elif defined(_WIN32) && defined(_WIN32_WCE) && defined(ARM)
#
#elif defined(_WIN32) && defined(WINCE_EMULATOR)
#
#elif defined (__arm) && defined (__ARMCC_VERSION)
#
#elif defined(HELIX_CONFIG_SYMBIAN_GENERATE_MMP)
#
#elif defined(_SYMBIAN) && defined(__WINS__)
#
#elif defined(__GNUC__) && defined(__arm__)
#
#elif defined(__GNUC__) && defined(__i386__)
#
#elif defined(__GNUC__) && defined(__amd64__)
#
#elif defined(__GNUC__) && (defined(__powerpc__) || defined(__POWERPC__))
#
#elif defined(_OPENWAVE_SIMULATOR) || defined(_OPENWAVE_ARMULATOR)
#
#elif defined(_SOLARIS) && !defined(__GNUC__)
#
#else
#error No platform defined. See valid options in aacdec.h
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* according to spec (13818-7 section 8.2.2, 14496-3 section 4.5.3)
* max size of input buffer =
* 6144 bits = 768 bytes per SCE or CCE-I
* 12288 bits = 1536 bytes per CPE
* 0 bits = 0 bytes per CCE-D (uses bits from the SCE/CPE/CCE-I it is coupled to)
*/
#ifndef AAC_MAX_NCHANS /* if max channels isn't set in makefile, */
#define AAC_MAX_NCHANS 2 /* set to default max number of channels */
#endif
#define AAC_MAX_NSAMPS 1024
#define AAC_MAINBUF_SIZE (768 * AAC_MAX_NCHANS)
#define AAC_NUM_PROFILES 3
#define AAC_PROFILE_MP 0
#define AAC_PROFILE_LC 1
#define AAC_PROFILE_SSR 2
/* define these to enable decoder features */
#if defined(HELIX_FEATURE_AUDIO_CODEC_AAC_SBR)
#define AAC_ENABLE_SBR
#endif // HELIX_FEATURE_AUDIO_CODEC_AAC_SBR.
#define AAC_ENABLE_MPEG4
enum {
ERR_AAC_NONE = 0,
ERR_AAC_INDATA_UNDERFLOW = -1,
ERR_AAC_NULL_POINTER = -2,
ERR_AAC_INVALID_ADTS_HEADER = -3,
ERR_AAC_INVALID_ADIF_HEADER = -4,
ERR_AAC_INVALID_FRAME = -5,
ERR_AAC_MPEG4_UNSUPPORTED = -6,
ERR_AAC_CHANNEL_MAP = -7,
ERR_AAC_SYNTAX_ELEMENT = -8,
ERR_AAC_DEQUANT = -9,
ERR_AAC_STEREO_PROCESS = -10,
ERR_AAC_PNS = -11,
ERR_AAC_SHORT_BLOCK_DEINT = -12,
ERR_AAC_TNS = -13,
ERR_AAC_IMDCT = -14,
ERR_AAC_NCHANS_TOO_HIGH = -15,
ERR_AAC_SBR_INIT = -16,
ERR_AAC_SBR_BITSTREAM = -17,
ERR_AAC_SBR_DATA = -18,
ERR_AAC_SBR_PCM_FORMAT = -19,
ERR_AAC_SBR_NCHANS_TOO_HIGH = -20,
ERR_AAC_SBR_SINGLERATE_UNSUPPORTED = -21,
ERR_AAC_RAWBLOCK_PARAMS = -22,
ERR_UNKNOWN = -9999
};
typedef struct _AACFrameInfo {
int bitRate;
int nChans;
int sampRateCore;
int sampRateOut;
int bitsPerSample;
int outputSamps;
int profile;
int tnsUsed;
int pnsUsed;
} AACFrameInfo;
typedef void *HAACDecoder;
/* public C API */
HAACDecoder AACInitDecoder(void);
void AACFreeDecoder(HAACDecoder hAACDecoder);
int AACDecode(HAACDecoder hAACDecoder, unsigned char **inbuf, int *bytesLeft, short *outbuf);
int AACFindSyncWord(unsigned char *buf, int nBytes);
void AACGetLastFrameInfo(HAACDecoder hAACDecoder, AACFrameInfo *aacFrameInfo);
int AACSetRawBlockParams(HAACDecoder hAACDecoder, int copyLast, AACFrameInfo *aacFrameInfo);
int AACFlushCodec(HAACDecoder hAACDecoder);
#ifdef HELIX_CONFIG_AAC_GENERATE_TRIGTABS_FLOAT
int AACInitTrigtabsFloat(void);
void AACFreeTrigtabsFloat(void);
#endif
#ifdef __cplusplus
}
#endif
#endif /* _AACDEC_H */
|
1137519-player
|
aac/aacdec.h
|
C
|
lgpl
| 5,884
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbrfreq.c,v 1.2 2005/05/20 18:05:41 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbrfreq.c - frequency band table calculation for SBR
**************************************************************************************/
#include "sbr.h"
#include "assembly.h"
/**************************************************************************************
* Function: BubbleSort
*
* Description: in-place sort of unsigned chars
*
* Inputs: buffer of elements to sort
* number of elements to sort
*
* Outputs: sorted buffer
*
* Return: none
**************************************************************************************/
static void BubbleSort(unsigned char *v, int nItems)
{
int i;
unsigned char t;
while (nItems >= 2) {
for (i = 0; i < nItems-1; i++) {
if (v[i+1] < v[i]) {
t = v[i+1];
v[i+1] = v[i];
v[i] = t;
}
}
nItems--;
}
}
/**************************************************************************************
* Function: VMin
*
* Description: find smallest element in a buffer of unsigned chars
*
* Inputs: buffer of elements to search
* number of elements to search
*
* Outputs: none
*
* Return: smallest element in buffer
**************************************************************************************/
static unsigned char VMin(unsigned char *v, int nItems)
{
int i;
unsigned char vMin;
vMin = v[0];
for (i = 1; i < nItems; i++) {
if (v[i] < vMin)
vMin = v[i];
}
return vMin;
}
/**************************************************************************************
* Function: VMax
*
* Description: find largest element in a buffer of unsigned chars
*
* Inputs: buffer of elements to search
* number of elements to search
*
* Outputs: none
*
* Return: largest element in buffer
**************************************************************************************/
static unsigned char VMax(unsigned char *v, int nItems)
{
int i;
unsigned char vMax;
vMax = v[0];
for (i = 1; i < nItems; i++) {
if (v[i] > vMax)
vMax = v[i];
}
return vMax;
}
/**************************************************************************************
* Function: CalcFreqMasterScaleZero
*
* Description: calculate master frequency table when freqScale == 0
* (4.6.18.3.2.1, figure 4.39)
*
* Inputs: alterScale flag
* index of first QMF subband in master freq table (k0)
* index of last QMF subband (k2)
*
* Outputs: master frequency table
*
* Return: number of bands in master frequency table
*
* Notes: assumes k2 - k0 <= 48 and k2 >= k0 (4.6.18.3.6)
**************************************************************************************/
static int CalcFreqMasterScaleZero(unsigned char *freqMaster, int alterScale, int k0, int k2)
{
int nMaster, k, nBands, k2Achieved, dk, vDk[64], k2Diff;
if (alterScale) {
dk = 2;
nBands = 2 * ((k2 - k0 + 2) >> 2);
} else {
dk = 1;
nBands = 2 * ((k2 - k0) >> 1);
}
if (nBands <= 0)
return 0;
k2Achieved = k0 + nBands * dk;
k2Diff = k2 - k2Achieved;
for (k = 0; k < nBands; k++)
vDk[k] = dk;
if (k2Diff > 0) {
k = nBands - 1;
while (k2Diff) {
vDk[k]++;
k--;
k2Diff--;
}
} else if (k2Diff < 0) {
k = 0;
while (k2Diff) {
vDk[k]--;
k++;
k2Diff++;
}
}
nMaster = nBands;
freqMaster[0] = k0;
for (k = 1; k <= nBands; k++)
freqMaster[k] = freqMaster[k-1] + vDk[k-1];
return nMaster;
}
/* mBandTab[i] = temp1[i] / 2 */
static const int mBandTab[3] = {6, 5, 4};
/* invWarpTab[i] = 1.0 / temp2[i], Q30 (see 4.6.18.3.2.1) */
static const int invWarpTab[2] = {0x40000000, 0x313b13b1};
/**************************************************************************************
* Function: CalcFreqMasterScale
*
* Description: calculate master frequency table when freqScale > 0
* (4.6.18.3.2.1, figure 4.39)
*
* Inputs: alterScale flag
* freqScale flag
* index of first QMF subband in master freq table (k0)
* index of last QMF subband (k2)
*
* Outputs: master frequency table
*
* Return: number of bands in master frequency table
*
* Notes: assumes k2 - k0 <= 48 and k2 >= k0 (4.6.18.3.6)
**************************************************************************************/
static int CalcFreqMaster(unsigned char *freqMaster, int freqScale, int alterScale, int k0, int k2)
{
int bands, twoRegions, k, k1, t, vLast, vCurr, pCurr;
int invWarp, nBands0, nBands1, change;
unsigned char vDk1Min, vDk0Max;
unsigned char *vDelta;
if (freqScale < 1 || freqScale > 3)
return -1;
bands = mBandTab[freqScale - 1];
invWarp = invWarpTab[alterScale];
/* tested for all k0 = [5, 64], k2 = [k0, 64] */
if (k2*10000 > 22449*k0) {
twoRegions = 1;
k1 = 2*k0;
} else {
twoRegions = 0;
k1 = k2;
}
/* tested for all k0 = [5, 64], k1 = [k0, 64], freqScale = [1,3] */
t = (log2Tab[k1] - log2Tab[k0]) >> 3; /* log2(k1/k0), Q28 to Q25 */
nBands0 = 2 * (((bands * t) + (1 << 24)) >> 25); /* multiply by bands/2, round to nearest int (mBandTab has factor of 1/2 rolled in) */
/* tested for all valid combinations of k0, k1, nBands (from sampRate, freqScale, alterScale)
* roundoff error can be a problem with fixpt (e.g. pCurr = 12.499999 instead of 12.50003)
* because successive multiplication always undershoots a little bit, but this
* doesn't occur in any of the ratios we encounter from the valid k0/k1 bands in the spec
*/
t = RatioPowInv(k1, k0, nBands0);
pCurr = k0 << 24;
vLast = k0;
vDelta = freqMaster + 1; /* operate in-place */
for (k = 0; k < nBands0; k++) {
pCurr = MULSHIFT32(pCurr, t) << 8; /* keep in Q24 */
vCurr = (pCurr + (1 << 23)) >> 24;
vDelta[k] = (vCurr - vLast);
vLast = vCurr;
}
/* sort the deltas and find max delta for first region */
BubbleSort(vDelta, nBands0);
vDk0Max = VMax(vDelta, nBands0);
/* fill master frequency table with bands from first region */
freqMaster[0] = k0;
for (k = 1; k <= nBands0; k++)
freqMaster[k] += freqMaster[k-1];
/* if only one region, then the table is complete */
if (!twoRegions)
return nBands0;
/* tested for all k1 = [10, 64], k2 = [k0, 64], freqScale = [1,3] */
t = (log2Tab[k2] - log2Tab[k1]) >> 3; /* log2(k1/k0), Q28 to Q25 */
t = MULSHIFT32(bands * t, invWarp) << 2; /* multiply by bands/2, divide by warp factor, keep Q25 */
nBands1 = 2 * ((t + (1 << 24)) >> 25); /* round to nearest int */
/* see comments above for calculations in first region */
t = RatioPowInv(k2, k1, nBands1);
pCurr = k1 << 24;
vLast = k1;
vDelta = freqMaster + nBands0 + 1; /* operate in-place */
for (k = 0; k < nBands1; k++) {
pCurr = MULSHIFT32(pCurr, t) << 8; /* keep in Q24 */
vCurr = (pCurr + (1 << 23)) >> 24;
vDelta[k] = (vCurr - vLast);
vLast = vCurr;
}
/* sort the deltas, adjusting first and last if the second region has smaller deltas than the first */
vDk1Min = VMin(vDelta, nBands1);
if (vDk1Min < vDk0Max) {
BubbleSort(vDelta, nBands1);
change = vDk0Max - vDelta[0];
if (change > ((vDelta[nBands1 - 1] - vDelta[0]) >> 1))
change = ((vDelta[nBands1 - 1] - vDelta[0]) >> 1);
vDelta[0] += change;
vDelta[nBands1-1] -= change;
}
BubbleSort(vDelta, nBands1);
/* fill master frequency table with bands from second region
* Note: freqMaster[nBands0] = k1
*/
for (k = 1; k <= nBands1; k++)
freqMaster[k + nBands0] += freqMaster[k + nBands0 - 1];
return (nBands0 + nBands1);
}
/**************************************************************************************
* Function: CalcFreqHigh
*
* Description: calculate high resolution frequency table (4.6.18.3.2.2)
*
* Inputs: master frequency table
* number of bands in master frequency table
* crossover band from header
*
* Outputs: high resolution frequency table
*
* Return: number of bands in high resolution frequency table
**************************************************************************************/
static int CalcFreqHigh(unsigned char *freqHigh, unsigned char *freqMaster, int nMaster, int crossOverBand)
{
int k, nHigh;
nHigh = nMaster - crossOverBand;
for (k = 0; k <= nHigh; k++)
freqHigh[k] = freqMaster[k + crossOverBand];
return nHigh;
}
/**************************************************************************************
* Function: CalcFreqLow
*
* Description: calculate low resolution frequency table (4.6.18.3.2.2)
*
* Inputs: high resolution frequency table
* number of bands in high resolution frequency table
*
* Outputs: low resolution frequency table
*
* Return: number of bands in low resolution frequency table
**************************************************************************************/
static int CalcFreqLow(unsigned char *freqLow, unsigned char *freqHigh, int nHigh)
{
int k, nLow, oddFlag;
nLow = nHigh - (nHigh >> 1);
freqLow[0] = freqHigh[0];
oddFlag = nHigh & 0x01;
for (k = 1; k <= nLow; k++)
freqLow[k] = freqHigh[2*k - oddFlag];
return nLow;
}
/**************************************************************************************
* Function: CalcFreqNoise
*
* Description: calculate noise floor frequency table (4.6.18.3.2.2)
*
* Inputs: low resolution frequency table
* number of bands in low resolution frequency table
* index of starting QMF subband for SBR (kStart)
* index of last QMF subband (k2)
* number of noise bands
*
* Outputs: noise floor frequency table
*
* Return: number of bands in noise floor frequency table
**************************************************************************************/
static int CalcFreqNoise(unsigned char *freqNoise, unsigned char *freqLow, int nLow, int kStart, int k2, int noiseBands)
{
int i, iLast, k, nQ, lTop, lBottom;
lTop = log2Tab[k2];
lBottom = log2Tab[kStart];
nQ = noiseBands*((lTop - lBottom) >> 2); /* Q28 to Q26, noiseBands = [0,3] */
nQ = (nQ + (1 << 25)) >> 26;
if (nQ < 1)
nQ = 1;
ASSERT(nQ <= MAX_NUM_NOISE_FLOOR_BANDS); /* required from 4.6.18.3.6 */
iLast = 0;
freqNoise[0] = freqLow[0];
for (k = 1; k <= nQ; k++) {
i = iLast + (nLow - iLast) / (nQ + 1 - k); /* truncating division */
freqNoise[k] = freqLow[i];
iLast = i;
}
return nQ;
}
/**************************************************************************************
* Function: BuildPatches
*
* Description: build high frequency patches (4.6.18.6.3)
*
* Inputs: master frequency table
* number of bands in low resolution frequency table
* index of first QMF subband in master freq table (k0)
* index of starting QMF subband for SBR (kStart)
* number of QMF bands in high resolution frequency table
* sample rate index
*
* Outputs: starting subband for each patch
* number of subbands in each patch
*
* Return: number of patches
**************************************************************************************/
static int BuildPatches(unsigned char *patchNumSubbands, unsigned char *patchStartSubband, unsigned char *freqMaster,
int nMaster, int k0, int kStart, int numQMFBands, int sampRateIdx)
{
int i, j, k;
int msb, sb, usb, numPatches, goalSB, oddFlag;
msb = k0;
usb = kStart;
numPatches = 0;
goalSB = goalSBTab[sampRateIdx];
if (nMaster == 0) {
patchNumSubbands[0] = 0;
patchStartSubband[0] = 0;
return 0;
}
if (goalSB < kStart + numQMFBands) {
k = 0;
for (i = 0; freqMaster[i] < goalSB; i++)
k = i+1;
} else {
k = nMaster;
}
do {
j = k+1;
do {
j--;
sb = freqMaster[j];
oddFlag = (sb - 2 + k0) & 0x01;
} while (sb > k0 - 1 + msb - oddFlag);
patchNumSubbands[numPatches] = MAX(sb - usb, 0);
patchStartSubband[numPatches] = k0 - oddFlag - patchNumSubbands[numPatches];
/* from MPEG reference code - slightly different from spec */
if ((patchNumSubbands[numPatches] < 3) && (numPatches > 0))
break;
if (patchNumSubbands[numPatches] > 0) {
usb = sb;
msb = sb;
numPatches++;
} else {
msb = kStart;
}
if (freqMaster[k] - sb < 3)
k = nMaster;
} while (sb != (kStart + numQMFBands) && numPatches <= MAX_NUM_PATCHES);
return numPatches;
}
/**************************************************************************************
* Function: FindFreq
*
* Description: search buffer of unsigned chars for a specific value
*
* Inputs: buffer of elements to search
* number of elements to search
* value to search for
*
* Outputs: none
*
* Return: non-zero if the value is found anywhere in the buffer, zero otherwise
**************************************************************************************/
static int FindFreq(unsigned char *freq, int nFreq, unsigned char val)
{
int k;
for (k = 0; k < nFreq; k++) {
if (freq[k] == val)
return 1;
}
return 0;
}
/**************************************************************************************
* Function: RemoveFreq
*
* Description: remove one element from a buffer of unsigned chars
*
* Inputs: buffer of elements
* number of elements
* index of element to remove
*
* Outputs: new buffer of length nFreq-1
*
* Return: none
**************************************************************************************/
static void RemoveFreq(unsigned char *freq, int nFreq, int removeIdx)
{
int k;
if (removeIdx >= nFreq)
return;
for (k = removeIdx; k < nFreq - 1; k++)
freq[k] = freq[k+1];
}
/**************************************************************************************
* Function: CalcFreqLimiter
*
* Description: calculate limiter frequency table (4.6.18.3.2.3)
*
* Inputs: number of subbands in each patch
* low resolution frequency table
* number of bands in low resolution frequency table
* index of starting QMF subband for SBR (kStart)
* number of limiter bands
* number of patches
*
* Outputs: limiter frequency table
*
* Return: number of bands in limiter frequency table
**************************************************************************************/
static int CalcFreqLimiter(unsigned char *freqLimiter, unsigned char *patchNumSubbands, unsigned char *freqLow,
int nLow, int kStart, int limiterBands, int numPatches)
{
int k, bands, nLimiter, nOctaves;
int limBandsPerOctave[3] = {120, 200, 300}; /* [1.2, 2.0, 3.0] * 100 */
unsigned char patchBorders[MAX_NUM_PATCHES + 1];
/* simple case */
if (limiterBands == 0) {
freqLimiter[0] = freqLow[0] - kStart;
freqLimiter[1] = freqLow[nLow] - kStart;
return 1;
}
bands = limBandsPerOctave[limiterBands - 1];
patchBorders[0] = kStart;
/* from MPEG reference code - slightly different from spec (top border) */
for (k = 1; k < numPatches; k++)
patchBorders[k] = patchBorders[k-1] + patchNumSubbands[k-1];
patchBorders[k] = freqLow[nLow];
for (k = 0; k <= nLow; k++)
freqLimiter[k] = freqLow[k];
for (k = 1; k < numPatches; k++)
freqLimiter[k+nLow] = patchBorders[k];
k = 1;
nLimiter = nLow + numPatches - 1;
BubbleSort(freqLimiter, nLimiter + 1);
while (k <= nLimiter) {
nOctaves = log2Tab[freqLimiter[k]] - log2Tab[freqLimiter[k-1]]; /* Q28 */
nOctaves = (nOctaves >> 9) * bands; /* Q19, max bands = 300 < 2^9 */
if (nOctaves < (49 << 19)) { /* compare with 0.49*100, in Q19 */
if (freqLimiter[k] == freqLimiter[k-1] || FindFreq(patchBorders, numPatches + 1, freqLimiter[k]) == 0) {
RemoveFreq(freqLimiter, nLimiter + 1, k);
nLimiter--;
} else if (FindFreq(patchBorders, numPatches + 1, freqLimiter[k-1]) == 0) {
RemoveFreq(freqLimiter, nLimiter + 1, k-1);
nLimiter--;
} else {
k++;
}
} else {
k++;
}
}
/* store limiter boundaries as offsets from kStart */
for (k = 0; k <= nLimiter; k++)
freqLimiter[k] -= kStart;
return nLimiter;
}
/**************************************************************************************
* Function: CalcFreqTables
*
* Description: calulate master and derived frequency tables, and patches
*
* Inputs: initialized SBRHeader struct for this SCE/CPE block
* initialized SBRFreq struct for this SCE/CPE block
* sample rate index of output sample rate (after SBR)
*
* Outputs: master and derived frequency tables, and patches
*
* Return: non-zero if error, zero otherwise
**************************************************************************************/
int CalcFreqTables(SBRHeader *sbrHdr, SBRFreq *sbrFreq, int sampRateIdx)
{
int k0, k2;
k0 = k0Tab[sampRateIdx][sbrHdr->startFreq];
if (sbrHdr->stopFreq == 14)
k2 = 2*k0;
else if (sbrHdr->stopFreq == 15)
k2 = 3*k0;
else
k2 = k2Tab[sampRateIdx][sbrHdr->stopFreq];
if (k2 > 64)
k2 = 64;
/* calculate master frequency table */
if (sbrHdr->freqScale == 0)
sbrFreq->nMaster = CalcFreqMasterScaleZero(sbrFreq->freqMaster, sbrHdr->alterScale, k0, k2);
else
sbrFreq->nMaster = CalcFreqMaster(sbrFreq->freqMaster, sbrHdr->freqScale, sbrHdr->alterScale, k0, k2);
/* calculate high frequency table and related parameters */
sbrFreq->nHigh = CalcFreqHigh(sbrFreq->freqHigh, sbrFreq->freqMaster, sbrFreq->nMaster, sbrHdr->crossOverBand);
sbrFreq->numQMFBands = sbrFreq->freqHigh[sbrFreq->nHigh] - sbrFreq->freqHigh[0];
sbrFreq->kStart = sbrFreq->freqHigh[0];
/* calculate low frequency table */
sbrFreq->nLow = CalcFreqLow(sbrFreq->freqLow, sbrFreq->freqHigh, sbrFreq->nHigh);
/* calculate noise floor frequency table */
sbrFreq->numNoiseFloorBands = CalcFreqNoise(sbrFreq->freqNoise, sbrFreq->freqLow, sbrFreq->nLow, sbrFreq->kStart, k2, sbrHdr->noiseBands);
/* calculate limiter table */
sbrFreq->numPatches = BuildPatches(sbrFreq->patchNumSubbands, sbrFreq->patchStartSubband, sbrFreq->freqMaster,
sbrFreq->nMaster, k0, sbrFreq->kStart, sbrFreq->numQMFBands, sampRateIdx);
sbrFreq->nLimiter = CalcFreqLimiter(sbrFreq->freqLimiter, sbrFreq->patchNumSubbands, sbrFreq->freqLow, sbrFreq->nLow, sbrFreq->kStart,
sbrHdr->limiterBands, sbrFreq->numPatches);
return 0;
}
|
1137519-player
|
aac/sbrfreq.c
|
C
|
lgpl
| 20,243
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbrhfadj.c,v 1.3 2005/05/24 16:01:55 albertofloyd Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbrhfadj.c - high frequency adjustment for SBR
**************************************************************************************/
#include "sbr.h"
#include "assembly.h"
/* invBandTab[i] = 1.0 / (i + 1), Q31 */
static const int invBandTab[64] = {
0x7fffffff, 0x40000000, 0x2aaaaaab, 0x20000000, 0x1999999a, 0x15555555, 0x12492492, 0x10000000,
0x0e38e38e, 0x0ccccccd, 0x0ba2e8ba, 0x0aaaaaab, 0x09d89d8a, 0x09249249, 0x08888889, 0x08000000,
0x07878788, 0x071c71c7, 0x06bca1af, 0x06666666, 0x06186186, 0x05d1745d, 0x0590b216, 0x05555555,
0x051eb852, 0x04ec4ec5, 0x04bda12f, 0x04924925, 0x0469ee58, 0x04444444, 0x04210842, 0x04000000,
0x03e0f83e, 0x03c3c3c4, 0x03a83a84, 0x038e38e4, 0x03759f23, 0x035e50d8, 0x03483483, 0x03333333,
0x031f3832, 0x030c30c3, 0x02fa0be8, 0x02e8ba2f, 0x02d82d83, 0x02c8590b, 0x02b93105, 0x02aaaaab,
0x029cbc15, 0x028f5c29, 0x02828283, 0x02762762, 0x026a439f, 0x025ed098, 0x0253c825, 0x02492492,
0x023ee090, 0x0234f72c, 0x022b63cc, 0x02222222, 0x02192e2a, 0x02108421, 0x02082082, 0x02000000,
};
/**************************************************************************************
* Function: EstimateEnvelope
*
* Description: estimate power of generated HF QMF bands in one time-domain envelope
* (4.6.18.7.3)
*
* Inputs: initialized PSInfoSBR struct
* initialized SBRHeader struct for this SCE/CPE block
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* index of current envelope
*
* Outputs: power of each QMF subband, stored as integer (Q0) * 2^N, N >= 0
*
* Return: none
**************************************************************************************/
static void EstimateEnvelope(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, int env)
{
int i, m, iStart, iEnd, xre, xim, nScale, expMax;
int p, n, mStart, mEnd, invFact, t;
int *XBuf;
U64 eCurr;
unsigned char *freqBandTab;
/* estimate current envelope */
iStart = sbrGrid->envTimeBorder[env] + HF_ADJ;
iEnd = sbrGrid->envTimeBorder[env+1] + HF_ADJ;
if (sbrGrid->freqRes[env]) {
n = sbrFreq->nHigh;
freqBandTab = sbrFreq->freqHigh;
} else {
n = sbrFreq->nLow;
freqBandTab = sbrFreq->freqLow;
}
/* ADS should inline MADD64 (smlal) properly, but check to make sure */
expMax = 0;
if (sbrHdr->interpFreq) {
for (m = 0; m < sbrFreq->numQMFBands; m++) {
eCurr.w64 = 0;
XBuf = psi->XBuf[iStart][sbrFreq->kStart + m];
for (i = iStart; i < iEnd; i++) {
/* scale to int before calculating power (precision not critical, and avoids overflow) */
xre = (*XBuf) >> FBITS_OUT_QMFA; XBuf += 1;
xim = (*XBuf) >> FBITS_OUT_QMFA; XBuf += (2*64 - 1);
eCurr.w64 = MADD64(eCurr.w64, xre, xre);
eCurr.w64 = MADD64(eCurr.w64, xim, xim);
}
/* eCurr.w64 is now Q(64 - 2*FBITS_OUT_QMFA) (64-bit word)
* if energy is too big to fit in 32-bit word (> 2^31) scale down by power of 2
*/
nScale = 0;
if (eCurr.r.hi32) {
nScale = (32 - CLZ(eCurr.r.hi32)) + 1;
t = (int)(eCurr.r.lo32 >> nScale); /* logical (unsigned) >> */
t |= eCurr.r.hi32 << (32 - nScale);
} else if (eCurr.r.lo32 >> 31) {
nScale = 1;
t = (int)(eCurr.r.lo32 >> nScale); /* logical (unsigned) >> */
} else {
t = (int)eCurr.r.lo32;
}
invFact = invBandTab[(iEnd - iStart)-1];
psi->eCurr[m] = MULSHIFT32(t, invFact);
psi->eCurrExp[m] = nScale + 1; /* +1 for invFact = Q31 */
if (psi->eCurrExp[m] > expMax)
expMax = psi->eCurrExp[m];
}
} else {
for (p = 0; p < n; p++) {
mStart = freqBandTab[p];
mEnd = freqBandTab[p+1];
eCurr.w64 = 0;
for (i = iStart; i < iEnd; i++) {
XBuf = psi->XBuf[i][mStart];
for (m = mStart; m < mEnd; m++) {
xre = (*XBuf++) >> FBITS_OUT_QMFA;
xim = (*XBuf++) >> FBITS_OUT_QMFA;
eCurr.w64 = MADD64(eCurr.w64, xre, xre);
eCurr.w64 = MADD64(eCurr.w64, xim, xim);
}
}
nScale = 0;
if (eCurr.r.hi32) {
nScale = (32 - CLZ(eCurr.r.hi32)) + 1;
t = (int)(eCurr.r.lo32 >> nScale); /* logical (unsigned) >> */
t |= eCurr.r.hi32 << (32 - nScale);
} else if (eCurr.r.lo32 >> 31) {
nScale = 1;
t = (int)(eCurr.r.lo32 >> nScale); /* logical (unsigned) >> */
} else {
t = (int)eCurr.r.lo32;
}
invFact = invBandTab[(iEnd - iStart)-1];
invFact = MULSHIFT32(invBandTab[(mEnd - mStart)-1], invFact) << 1;
t = MULSHIFT32(t, invFact);
for (m = mStart; m < mEnd; m++) {
psi->eCurr[m - sbrFreq->kStart] = t;
psi->eCurrExp[m - sbrFreq->kStart] = nScale + 1; /* +1 for invFact = Q31 */
}
if (psi->eCurrExp[mStart - sbrFreq->kStart] > expMax)
expMax = psi->eCurrExp[mStart - sbrFreq->kStart];
}
}
psi->eCurrExpMax = expMax;
}
/**************************************************************************************
* Function: GetSMapped
*
* Description: calculate SMapped (4.6.18.7.2)
*
* Inputs: initialized PSInfoSBR struct
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* initialized SBRChan struct for this channel
* index of current envelope
* index of current QMF band
* la flag for this envelope
*
* Outputs: none
*
* Return: 1 if a sinusoid is present in this band, 0 if not
**************************************************************************************/
static int GetSMapped(SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int env, int band, int la)
{
int bandStart, bandEnd, oddFlag, r;
if (sbrGrid->freqRes[env]) {
/* high resolution */
bandStart = band;
bandEnd = band+1;
} else {
/* low resolution (see CalcFreqLow() for mapping) */
oddFlag = sbrFreq->nHigh & 0x01;
bandStart = (band > 0 ? 2*band - oddFlag : 0); /* starting index for freqLow[band] */
bandEnd = 2*(band+1) - oddFlag; /* ending index for freqLow[band+1] */
}
/* sMapped = 1 if sIndexMapped == 1 for any frequency in this band */
for (band = bandStart; band < bandEnd; band++) {
if (sbrChan->addHarmonic[1][band]) {
r = ((sbrFreq->freqHigh[band+1] + sbrFreq->freqHigh[band]) >> 1);
if (env >= la || sbrChan->addHarmonic[0][r] == 1)
return 1;
}
}
return 0;
}
#define GBOOST_MAX 0x2830afd3 /* Q28, 1.584893192 squared */
#define ACC_SCALE 6
/* squared version of table in 4.6.18.7.5 */
static const int limGainTab[4] = {0x20138ca7, 0x40000000, 0x7fb27dce, 0x80000000}; /* Q30 (0x80000000 = sentinel for GMAX) */
/**************************************************************************************
* Function: CalcMaxGain
*
* Description: calculate max gain in one limiter band (4.6.18.7.5)
*
* Inputs: initialized PSInfoSBR struct
* initialized SBRHeader struct for this SCE/CPE block
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* index of current channel (0 for SCE, 0 or 1 for CPE)
* index of current envelope
* index of current limiter band
* number of fraction bits in dequantized envelope
* (max = Q(FBITS_OUT_DQ_ENV - 6) = Q23, can go negative)
*
* Outputs: updated gainMax, gainMaxFBits, and sumEOrigMapped in PSInfoSBR struct
*
* Return: none
**************************************************************************************/
static void CalcMaxGain(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, int ch, int env, int lim, int fbitsDQ)
{
int m, mStart, mEnd, q, z, r;
int sumEOrigMapped, sumECurr, gainMax, eOMGainMax, envBand;
unsigned char eCurrExpMax;
unsigned char *freqBandTab;
mStart = sbrFreq->freqLimiter[lim]; /* these are offsets from kStart */
mEnd = sbrFreq->freqLimiter[lim + 1];
freqBandTab = (sbrGrid->freqRes[env] ? sbrFreq->freqHigh : sbrFreq->freqLow);
/* calculate max gain to apply to signal in this limiter band */
sumECurr = 0;
sumEOrigMapped = 0;
eCurrExpMax = psi->eCurrExpMax;
eOMGainMax = psi->eOMGainMax;
envBand = psi->envBand;
for (m = mStart; m < mEnd; m++) {
/* map current QMF band to appropriate envelope band */
if (m == freqBandTab[envBand + 1] - sbrFreq->kStart) {
envBand++;
eOMGainMax = psi->envDataDequant[ch][env][envBand] >> ACC_SCALE; /* summing max 48 bands */
}
sumEOrigMapped += eOMGainMax;
/* easy test for overflow on ARM */
sumECurr += (psi->eCurr[m] >> (eCurrExpMax - psi->eCurrExp[m]));
if (sumECurr >> 30) {
sumECurr >>= 1;
eCurrExpMax++;
}
}
psi->eOMGainMax = eOMGainMax;
psi->envBand = envBand;
psi->gainMaxFBits = 30; /* Q30 tables */
if (sumECurr == 0) {
/* any non-zero numerator * 1/EPS_0 is > G_MAX */
gainMax = (sumEOrigMapped == 0 ? limGainTab[sbrHdr->limiterGains] : 0x80000000);
} else if (sumEOrigMapped == 0) {
/* 1/(any non-zero denominator) * EPS_0 * limGainTab[x] is appx. 0 */
gainMax = 0;
} else {
/* sumEOrigMapped = Q(fbitsDQ - ACC_SCALE), sumECurr = Q(-eCurrExpMax) */
gainMax = limGainTab[sbrHdr->limiterGains];
if (sbrHdr->limiterGains != 3) {
q = MULSHIFT32(sumEOrigMapped, gainMax); /* Q(fbitsDQ - ACC_SCALE - 2), gainMax = Q30 */
z = CLZ(sumECurr) - 1;
r = InvRNormalized(sumECurr << z); /* in = Q(z - eCurrExpMax), out = Q(29 + 31 - z + eCurrExpMax) */
gainMax = MULSHIFT32(q, r); /* Q(29 + 31 - z + eCurrExpMax + fbitsDQ - ACC_SCALE - 2 - 32) */
psi->gainMaxFBits = 26 - z + eCurrExpMax + fbitsDQ - ACC_SCALE;
}
}
psi->sumEOrigMapped = sumEOrigMapped;
psi->gainMax = gainMax;
}
/**************************************************************************************
* Function: CalcNoiseDivFactors
*
* Description: calculate 1/(1+Q) and Q/(1+Q) (4.6.18.7.4; 4.6.18.7.5)
*
* Inputs: dequantized noise floor scalefactor
*
* Outputs: 1/(1+Q) and Q/(1+Q), format = Q31
*
* Return: none
**************************************************************************************/
static void CalcNoiseDivFactors(int q, int *qp1Inv, int *qqp1Inv)
{
int z, qp1, t, s;
/* 1 + Q_orig */
qp1 = (q >> 1);
qp1 += (1 << (FBITS_OUT_DQ_NOISE - 1)); /* >> 1 to avoid overflow when adding 1.0 */
z = CLZ(qp1) - 1; /* z <= 31 - FBITS_OUT_DQ_NOISE */
qp1 <<= z; /* Q(FBITS_OUT_DQ_NOISE + z) = Q31 * 2^-(31 - (FBITS_OUT_DQ_NOISE + z)) */
t = InvRNormalized(qp1) << 1; /* Q30 * 2^(31 - (FBITS_OUT_DQ_NOISE + z)), guaranteed not to overflow */
/* normalize to Q31 */
s = (31 - (FBITS_OUT_DQ_NOISE - 1) - z - 1); /* clearly z >= 0, z <= (30 - (FBITS_OUT_DQ_NOISE - 1)) */
*qp1Inv = (t >> s); /* s = [0, 31 - FBITS_OUT_DQ_NOISE] */
*qqp1Inv = MULSHIFT32(t, q) << (32 - FBITS_OUT_DQ_NOISE - s);
}
/**************************************************************************************
* Function: CalcComponentGains
*
* Description: calculate gain of envelope, sinusoids, and noise in one limiter band
* (4.6.18.7.5)
*
* Inputs: initialized PSInfoSBR struct
* initialized SBRHeader struct for this SCE/CPE block
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* initialized SBRChan struct for this channel
* index of current channel (0 for SCE, 0 or 1 for CPE)
* index of current envelope
* index of current limiter band
* number of fraction bits in dequantized envelope
*
* Outputs: gains for envelope, sinusoids and noise
* number of fraction bits for envelope gain
* sum of the total gain for each component in this band
* other updated state variables
*
* Return: none
**************************************************************************************/
static void CalcComponentGains(PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch, int env, int lim, int fbitsDQ)
{
int d, m, mStart, mEnd, q, qm, noiseFloor, sIndexMapped;
int shift, eCurr, maxFlag, gainMax, gainMaxFBits;
int gain, sm, z, r, fbitsGain, gainScale;
unsigned char *freqBandTab;
mStart = sbrFreq->freqLimiter[lim]; /* these are offsets from kStart */
mEnd = sbrFreq->freqLimiter[lim + 1];
gainMax = psi->gainMax;
gainMaxFBits = psi->gainMaxFBits;
d = (env == psi->la || env == sbrChan->laPrev ? 0 : 1);
freqBandTab = (sbrGrid->freqRes[env] ? sbrFreq->freqHigh : sbrFreq->freqLow);
/* figure out which noise floor this envelope is in (only 1 or 2 noise floors allowed) */
noiseFloor = 0;
if (sbrGrid->numNoiseFloors == 2 && sbrGrid->noiseTimeBorder[1] <= sbrGrid->envTimeBorder[env])
noiseFloor++;
psi->sumECurrGLim = 0;
psi->sumSM = 0;
psi->sumQM = 0;
/* calculate energy of noise to add in this limiter band */
for (m = mStart; m < mEnd; m++) {
if (m == sbrFreq->freqNoise[psi->noiseFloorBand + 1] - sbrFreq->kStart) {
/* map current QMF band to appropriate noise floor band (NOTE: freqLimiter[0] == freqLow[0] = freqHigh[0]) */
psi->noiseFloorBand++;
CalcNoiseDivFactors(psi->noiseDataDequant[ch][noiseFloor][psi->noiseFloorBand], &(psi->qp1Inv), &(psi->qqp1Inv));
}
if (m == sbrFreq->freqHigh[psi->highBand + 1] - sbrFreq->kStart)
psi->highBand++;
if (m == freqBandTab[psi->sBand + 1] - sbrFreq->kStart) {
psi->sBand++;
psi->sMapped = GetSMapped(sbrGrid, sbrFreq, sbrChan, env, psi->sBand, psi->la);
}
/* get sIndexMapped for this QMF subband */
sIndexMapped = 0;
r = ((sbrFreq->freqHigh[psi->highBand+1] + sbrFreq->freqHigh[psi->highBand]) >> 1);
if (m + sbrFreq->kStart == r) {
/* r = center frequency, deltaStep = (env >= la || sIndexMapped'(r, numEnv'-1) == 1) */
if (env >= psi->la || sbrChan->addHarmonic[0][r] == 1)
sIndexMapped = sbrChan->addHarmonic[1][psi->highBand];
}
/* save sine flags from last envelope in this frame:
* addHarmonic[0][0...63] = saved sine present flag from previous frame, for each QMF subband
* addHarmonic[1][0...nHigh-1] = addHarmonic bit from current frame, for each high-res frequency band
* from MPEG reference code - slightly different from spec
* (sIndexMapped'(m,LE'-1) can still be 0 when numEnv == psi->la)
*/
if (env == sbrGrid->numEnv - 1) {
if (m + sbrFreq->kStart == r)
sbrChan->addHarmonic[0][m + sbrFreq->kStart] = sbrChan->addHarmonic[1][psi->highBand];
else
sbrChan->addHarmonic[0][m + sbrFreq->kStart] = 0;
}
gain = psi->envDataDequant[ch][env][psi->sBand];
qm = MULSHIFT32(gain, psi->qqp1Inv) << 1;
sm = (sIndexMapped ? MULSHIFT32(gain, psi->qp1Inv) << 1 : 0);
/* three cases: (sMapped == 0 && delta == 1), (sMapped == 0 && delta == 0), (sMapped == 1) */
if (d == 1 && psi->sMapped == 0)
gain = MULSHIFT32(psi->qp1Inv, gain) << 1;
else if (psi->sMapped != 0)
gain = MULSHIFT32(psi->qqp1Inv, gain) << 1;
/* gain, qm, sm = Q(fbitsDQ), gainMax = Q(fbitsGainMax) */
eCurr = psi->eCurr[m];
if (eCurr) {
z = CLZ(eCurr) - 1;
r = InvRNormalized(eCurr << z); /* in = Q(z - eCurrExp), out = Q(29 + 31 - z + eCurrExp) */
gainScale = MULSHIFT32(gain, r); /* out = Q(29 + 31 - z + eCurrExp + fbitsDQ - 32) */
fbitsGain = 29 + 31 - z + psi->eCurrExp[m] + fbitsDQ - 32;
} else {
/* if eCurr == 0, then gain is unchanged (divide by EPS = 1) */
gainScale = gain;
fbitsGain = fbitsDQ;
}
/* see if gain for this band exceeds max gain */
maxFlag = 0;
if (gainMax != (int)0x80000000) {
if (fbitsGain >= gainMaxFBits) {
shift = MIN(fbitsGain - gainMaxFBits, 31);
maxFlag = ((gainScale >> shift) > gainMax ? 1 : 0);
} else {
shift = MIN(gainMaxFBits - fbitsGain, 31);
maxFlag = (gainScale > (gainMax >> shift) ? 1 : 0);
}
}
if (maxFlag) {
/* gainScale > gainMax, calculate ratio with 32/16 division */
q = 0;
r = gainScale; /* guaranteed > 0, else maxFlag could not have been set */
z = CLZ(r);
if (z < 16) {
q = 16 - z;
r >>= q; /* out = Q(fbitsGain - q) */
}
z = CLZ(gainMax) - 1;
r = (gainMax << z) / r; /* out = Q((fbitsGainMax + z) - (fbitsGain - q)) */
q = (gainMaxFBits + z) - (fbitsGain - q); /* r = Q(q) */
if (q > 30) {
r >>= MIN(q - 30, 31);
} else {
z = MIN(30 - q, 30);
CLIP_2N_SHIFT30(r, z); /* let r = Q30 since range = [0.0, 1.0) (clip to 0x3fffffff = 0.99999) */
}
qm = MULSHIFT32(qm, r) << 2;
gain = MULSHIFT32(gain, r) << 2;
psi->gLimBuf[m] = gainMax;
psi->gLimFbits[m] = gainMaxFBits;
} else {
psi->gLimBuf[m] = gainScale;
psi->gLimFbits[m] = fbitsGain;
}
/* sumSM, sumQM, sumECurrGLim = Q(fbitsDQ - ACC_SCALE) */
psi->smBuf[m] = sm;
psi->sumSM += (sm >> ACC_SCALE);
psi->qmLimBuf[m] = qm;
if (env != psi->la && env != sbrChan->laPrev && sm == 0)
psi->sumQM += (qm >> ACC_SCALE);
/* eCurr * gain^2 same as gain^2, before division by eCurr
* (but note that gain != 0 even if eCurr == 0, since it's divided by eps)
*/
if (eCurr)
psi->sumECurrGLim += (gain >> ACC_SCALE);
}
}
/**************************************************************************************
* Function: ApplyBoost
*
* Description: calculate and apply boost factor for envelope, sinusoids, and noise
* in this limiter band (4.6.18.7.5)
*
* Inputs: initialized PSInfoSBR struct
* initialized SBRFreq struct for this SCE/CPE block
* index of current limiter band
* number of fraction bits in dequantized envelope
*
* Outputs: envelope gain, sinusoids and noise after scaling by gBoost
* format = Q(FBITS_GLIM_BOOST) for envelope gain,
* = Q(FBITS_QLIM_BOOST) for noise
* = Q(FBITS_OUT_QMFA) for sinusoids
*
* Return: none
*
* Notes: after scaling, each component has at least 1 GB
**************************************************************************************/
static void ApplyBoost(PSInfoSBR *psi, SBRFreq *sbrFreq, int lim, int fbitsDQ)
{
int m, mStart, mEnd, q, z, r;
int sumEOrigMapped, gBoost;
mStart = sbrFreq->freqLimiter[lim]; /* these are offsets from kStart */
mEnd = sbrFreq->freqLimiter[lim + 1];
sumEOrigMapped = psi->sumEOrigMapped >> 1;
r = (psi->sumECurrGLim >> 1) + (psi->sumSM >> 1) + (psi->sumQM >> 1); /* 1 GB fine (sm and qm are mutually exclusive in acc) */
if (r < (1 << (31-28))) {
/* any non-zero numerator * 1/EPS_0 is > GBOOST_MAX
* round very small r to zero to avoid scaling problems
*/
gBoost = (sumEOrigMapped == 0 ? (1 << 28) : GBOOST_MAX);
z = 0;
} else if (sumEOrigMapped == 0) {
/* 1/(any non-zero denominator) * EPS_0 is appx. 0 */
gBoost = 0;
z = 0;
} else {
/* numerator (sumEOrigMapped) and denominator (r) have same Q format (before << z) */
z = CLZ(r) - 1; /* z = [0, 27] */
r = InvRNormalized(r << z);
gBoost = MULSHIFT32(sumEOrigMapped, r);
}
/* gBoost = Q(28 - z) */
if (gBoost > (GBOOST_MAX >> z)) {
gBoost = GBOOST_MAX;
z = 0;
}
gBoost <<= z; /* gBoost = Q28, minimum 1 GB */
/* convert gain, noise, sinusoids to fixed Q format, clipping if necessary
* (rare, usually only happens at very low bitrates, introduces slight
* distortion into final HF mapping, but should be inaudible)
*/
for (m = mStart; m < mEnd; m++) {
/* let gLimBoost = Q24, since in practice the max values are usually 16 to 20
* unless limiterGains == 3 (limiter off) and eCurr ~= 0 (i.e. huge gain, but only
* because the envelope has 0 power anyway)
*/
q = MULSHIFT32(psi->gLimBuf[m], gBoost) << 2; /* Q(gLimFbits) * Q(28) --> Q(gLimFbits[m]-2) */
r = SqrtFix(q, psi->gLimFbits[m] - 2, &z);
z -= FBITS_GLIM_BOOST;
if (z >= 0) {
psi->gLimBoost[m] = r >> MIN(z, 31);
} else {
z = MIN(30, -z);
CLIP_2N_SHIFT30(r, z);
psi->gLimBoost[m] = r;
}
q = MULSHIFT32(psi->qmLimBuf[m], gBoost) << 2; /* Q(fbitsDQ) * Q(28) --> Q(fbitsDQ-2) */
r = SqrtFix(q, fbitsDQ - 2, &z);
z -= FBITS_QLIM_BOOST; /* << by 14, since integer sqrt of x < 2^16, and we want to leave 1 GB */
if (z >= 0) {
psi->qmLimBoost[m] = r >> MIN(31, z);
} else {
z = MIN(30, -z);
CLIP_2N_SHIFT30(r, z);
psi->qmLimBoost[m] = r;
}
q = MULSHIFT32(psi->smBuf[m], gBoost) << 2; /* Q(fbitsDQ) * Q(28) --> Q(fbitsDQ-2) */
r = SqrtFix(q, fbitsDQ - 2, &z);
z -= FBITS_OUT_QMFA; /* justify for adding to signal (xBuf) later */
if (z >= 0) {
psi->smBoost[m] = r >> MIN(31, z);
} else {
z = MIN(30, -z);
CLIP_2N_SHIFT30(r, z);
psi->smBoost[m] = r;
}
}
}
/**************************************************************************************
* Function: CalcGain
*
* Description: calculate and apply proper gain to HF components in one envelope
* (4.6.18.7.5)
*
* Inputs: initialized PSInfoSBR struct
* initialized SBRHeader struct for this SCE/CPE block
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* initialized SBRChan struct for this channel
* index of current channel (0 for SCE, 0 or 1 for CPE)
* index of current envelope
*
* Outputs: envelope gain, sinusoids and noise after scaling
*
* Return: none
**************************************************************************************/
static void CalcGain(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch, int env)
{
int lim, fbitsDQ;
/* initialize to -1 so that mapping limiter bands to env/noise bands works right on first pass */
psi->envBand = -1;
psi->noiseFloorBand = -1;
psi->sBand = -1;
psi->highBand = -1;
fbitsDQ = (FBITS_OUT_DQ_ENV - psi->envDataDequantScale[ch][env]); /* Q(29 - optional scalefactor) */
for (lim = 0; lim < sbrFreq->nLimiter; lim++) {
/* the QMF bands are divided into lim regions (consecutive, non-overlapping) */
CalcMaxGain(psi, sbrHdr, sbrGrid, sbrFreq, ch, env, lim, fbitsDQ);
CalcComponentGains(psi, sbrGrid, sbrFreq, sbrChan, ch, env, lim, fbitsDQ);
ApplyBoost(psi, sbrFreq, lim, fbitsDQ);
}
}
/* hSmooth table from 4.7.18.7.6, format = Q31 */
static const int hSmoothCoef[MAX_NUM_SMOOTH_COEFS] = {
0x2aaaaaab, 0x2697a512, 0x1becfa68, 0x0ebdb043, 0x04130598,
};
/**************************************************************************************
* Function: MapHF
*
* Description: map HF components to proper QMF bands, with optional gain smoothing
* filter (4.6.18.7.6)
*
* Inputs: initialized PSInfoSBR struct
* initialized SBRHeader struct for this SCE/CPE block
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* initialized SBRChan struct for this channel
* index of current envelope
* reset flag (can be non-zero for first envelope only)
*
* Outputs: complete reconstructed subband QMF samples for this envelope
*
* Return: none
*
* Notes: ensures that output has >= MIN_GBITS_IN_QMFS guard bits,
* so it's not necessary to check anything in the synth QMF
**************************************************************************************/
static void MapHF(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int env, int hfReset)
{
int noiseTabIndex, sinIndex, gainNoiseIndex, hSL;
int i, iStart, iEnd, m, idx, j, s, n, smre, smim;
int gFilt, qFilt, xre, xim, gbMask, gbIdx;
int *XBuf;
noiseTabIndex = sbrChan->noiseTabIndex;
sinIndex = sbrChan->sinIndex;
gainNoiseIndex = sbrChan->gainNoiseIndex; /* oldest entries in filter delay buffer */
if (hfReset)
noiseTabIndex = 2; /* starts at 1, double since complex */
hSL = (sbrHdr->smoothMode ? 0 : 4);
if (hfReset) {
for (i = 0; i < hSL; i++) {
for (m = 0; m < sbrFreq->numQMFBands; m++) {
sbrChan->gTemp[gainNoiseIndex][m] = psi->gLimBoost[m];
sbrChan->qTemp[gainNoiseIndex][m] = psi->qmLimBoost[m];
}
gainNoiseIndex++;
if (gainNoiseIndex == MAX_NUM_SMOOTH_COEFS)
gainNoiseIndex = 0;
}
ASSERT(env == 0); /* should only be reset when env == 0 */
}
iStart = sbrGrid->envTimeBorder[env];
iEnd = sbrGrid->envTimeBorder[env+1];
for (i = iStart; i < iEnd; i++) {
/* save new values in temp buffers (delay)
* we only store MAX_NUM_SMOOTH_COEFS most recent values,
* so don't keep storing the same value over and over
*/
if (i - iStart < MAX_NUM_SMOOTH_COEFS) {
for (m = 0; m < sbrFreq->numQMFBands; m++) {
sbrChan->gTemp[gainNoiseIndex][m] = psi->gLimBoost[m];
sbrChan->qTemp[gainNoiseIndex][m] = psi->qmLimBoost[m];
}
}
/* see 4.6.18.7.6 */
XBuf = psi->XBuf[i + HF_ADJ][sbrFreq->kStart];
gbMask = 0;
for (m = 0; m < sbrFreq->numQMFBands; m++) {
if (env == psi->la || env == sbrChan->laPrev) {
/* no smoothing filter for gain, and qFilt = 0 (only need to do once) */
if (i == iStart) {
psi->gFiltLast[m] = sbrChan->gTemp[gainNoiseIndex][m];
psi->qFiltLast[m] = 0;
}
} else if (hSL == 0) {
/* no smoothing filter for gain, (only need to do once) */
if (i == iStart) {
psi->gFiltLast[m] = sbrChan->gTemp[gainNoiseIndex][m];
psi->qFiltLast[m] = sbrChan->qTemp[gainNoiseIndex][m];
}
} else {
/* apply smoothing filter to gain and noise (after MAX_NUM_SMOOTH_COEFS, it's always the same) */
if (i - iStart < MAX_NUM_SMOOTH_COEFS) {
gFilt = 0;
qFilt = 0;
idx = gainNoiseIndex;
for (j = 0; j < MAX_NUM_SMOOTH_COEFS; j++) {
/* sum(abs(hSmoothCoef[j])) for all j < 1.0 */
gFilt += MULSHIFT32(sbrChan->gTemp[idx][m], hSmoothCoef[j]);
qFilt += MULSHIFT32(sbrChan->qTemp[idx][m], hSmoothCoef[j]);
idx--;
if (idx < 0)
idx += MAX_NUM_SMOOTH_COEFS;
}
psi->gFiltLast[m] = gFilt << 1; /* restore to Q(FBITS_GLIM_BOOST) (gain of filter < 1.0, so no overflow) */
psi->qFiltLast[m] = qFilt << 1; /* restore to Q(FBITS_QLIM_BOOST) */
}
}
if (psi->smBoost[m] != 0) {
/* add scaled signal and sinusoid, don't add noise (qFilt = 0) */
smre = psi->smBoost[m];
smim = smre;
/* sinIndex: [0] xre += sm [1] xim += sm*s [2] xre -= sm [3] xim -= sm*s */
s = (sinIndex >> 1); /* if 2 or 3, flip sign to subtract sm */
s <<= 31;
smre ^= (s >> 31);
smre -= (s >> 31);
s ^= ((m + sbrFreq->kStart) << 31);
smim ^= (s >> 31);
smim -= (s >> 31);
/* if sinIndex == 0 or 2, smim = 0; if sinIndex == 1 or 3, smre = 0 */
s = sinIndex << 31;
smim &= (s >> 31);
s ^= 0x80000000;
smre &= (s >> 31);
noiseTabIndex += 2; /* noise filtered by 0, but still need to bump index */
} else {
/* add scaled signal and scaled noise */
qFilt = psi->qFiltLast[m];
n = noiseTab[noiseTabIndex++];
smre = MULSHIFT32(n, qFilt) >> (FBITS_QLIM_BOOST - 1 - FBITS_OUT_QMFA);
n = noiseTab[noiseTabIndex++];
smim = MULSHIFT32(n, qFilt) >> (FBITS_QLIM_BOOST - 1 - FBITS_OUT_QMFA);
}
noiseTabIndex &= 1023; /* 512 complex numbers */
gFilt = psi->gFiltLast[m];
xre = MULSHIFT32(gFilt, XBuf[0]);
xim = MULSHIFT32(gFilt, XBuf[1]);
CLIP_2N_SHIFT30(xre, 32 - FBITS_GLIM_BOOST);
CLIP_2N_SHIFT30(xim, 32 - FBITS_GLIM_BOOST);
xre += smre; *XBuf++ = xre;
xim += smim; *XBuf++ = xim;
gbMask |= FASTABS(xre);
gbMask |= FASTABS(xim);
}
/* update circular buffer index */
gainNoiseIndex++;
if (gainNoiseIndex == MAX_NUM_SMOOTH_COEFS)
gainNoiseIndex = 0;
sinIndex++;
sinIndex &= 3;
/* ensure MIN_GBITS_IN_QMFS guard bits in output
* almost never occurs in practice, but checking here makes synth QMF logic very simple
*/
if (gbMask >> (31 - MIN_GBITS_IN_QMFS)) {
XBuf = psi->XBuf[i + HF_ADJ][sbrFreq->kStart];
for (m = 0; m < sbrFreq->numQMFBands; m++) {
xre = XBuf[0]; xim = XBuf[1];
CLIP_2N(xre, (31 - MIN_GBITS_IN_QMFS));
CLIP_2N(xim, (31 - MIN_GBITS_IN_QMFS));
*XBuf++ = xre; *XBuf++ = xim;
}
CLIP_2N(gbMask, (31 - MIN_GBITS_IN_QMFS));
}
gbIdx = ((i + HF_ADJ) >> 5) & 0x01;
sbrChan->gbMask[gbIdx] |= gbMask;
}
sbrChan->noiseTabIndex = noiseTabIndex;
sbrChan->sinIndex = sinIndex;
sbrChan->gainNoiseIndex = gainNoiseIndex;
}
/**************************************************************************************
* Function: AdjustHighFreq
*
* Description: adjust high frequencies and add noise and sinusoids (4.6.18.7)
*
* Inputs: initialized PSInfoSBR struct
* initialized SBRHeader struct for this SCE/CPE block
* initialized SBRGrid struct for this channel
* initialized SBRFreq struct for this SCE/CPE block
* initialized SBRChan struct for this channel
* index of current channel (0 for SCE, 0 or 1 for CPE)
*
* Outputs: complete reconstructed subband QMF samples for this channel
*
* Return: none
**************************************************************************************/
void AdjustHighFreq(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch)
{
int i, env, hfReset;
unsigned char frameClass, pointer;
frameClass = sbrGrid->frameClass;
pointer = sbrGrid->pointer;
/* derive la from table 4.159 */
if ((frameClass == SBR_GRID_FIXVAR || frameClass == SBR_GRID_VARVAR) && pointer > 0)
psi->la = sbrGrid->numEnv + 1 - pointer;
else if (frameClass == SBR_GRID_VARFIX && pointer > 1)
psi->la = pointer - 1;
else
psi->la = -1;
/* for each envelope, estimate gain and adjust SBR QMF bands */
hfReset = sbrChan->reset;
for (env = 0; env < sbrGrid->numEnv; env++) {
EstimateEnvelope(psi, sbrHdr, sbrGrid, sbrFreq, env);
CalcGain(psi, sbrHdr, sbrGrid, sbrFreq, sbrChan, ch, env);
MapHF(psi, sbrHdr, sbrGrid, sbrFreq, sbrChan, env, hfReset);
hfReset = 0; /* only set for first envelope after header reset */
}
/* set saved sine flags to 0 for QMF bands outside of current frequency range */
for (i = 0; i < sbrFreq->freqLimiter[0] + sbrFreq->kStart; i++)
sbrChan->addHarmonic[0][i] = 0;
for (i = sbrFreq->freqLimiter[sbrFreq->nLimiter] + sbrFreq->kStart; i < 64; i++)
sbrChan->addHarmonic[0][i] = 0;
sbrChan->addHarmonicFlag[0] = sbrChan->addHarmonicFlag[1];
/* save la for next frame */
if (psi->la == sbrGrid->numEnv)
sbrChan->laPrev = 0;
else
sbrChan->laPrev = -1;
}
|
1137519-player
|
aac/sbrhfadj.c
|
C
|
lgpl
| 32,566
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: bitstream.h,v 1.1 2005/02/26 01:47:34 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* bitstream.h - definitions of bitstream handling functions
**************************************************************************************/
#ifndef _BITSTREAM_H
#define _BITSTREAM_H
#include "aaccommon.h"
/* additional external symbols to name-mangle for static linking */
#define SetBitstreamPointer STATNAME(SetBitstreamPointer)
#define GetBits STATNAME(GetBits)
#define GetBitsNoAdvance STATNAME(GetBitsNoAdvance)
#define AdvanceBitstream STATNAME(AdvanceBitstream)
#define CalcBitsUsed STATNAME(CalcBitsUsed)
#define ByteAlignBitstream STATNAME(ByteAlignBitstream)
typedef struct _BitStreamInfo {
unsigned char *bytePtr;
unsigned int iCache;
int cachedBits;
int nBytes;
} BitStreamInfo;
/* bitstream.c */
void SetBitstreamPointer(BitStreamInfo *bsi, int nBytes, unsigned char *buf);
unsigned int GetBits(BitStreamInfo *bsi, int nBits);
unsigned int GetBitsNoAdvance(BitStreamInfo *bsi, int nBits);
void AdvanceBitstream(BitStreamInfo *bsi, int nBits);
int CalcBitsUsed(BitStreamInfo *bsi, unsigned char *startBuf, int startOffset);
void ByteAlignBitstream(BitStreamInfo *bsi);
#endif /* _BITSTREAM_H */
|
1137519-player
|
aac/bitstream.h
|
C
|
lgpl
| 3,080
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: bitstream.c,v 1.2 2005/09/27 20:31:11 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* bitstream.c - bitstream parsing functions
**************************************************************************************/
#include "bitstream.h"
/**************************************************************************************
* Function: SetBitstreamPointer
*
* Description: initialize bitstream reader
*
* Inputs: pointer to BitStreamInfo struct
* number of bytes in bitstream
* pointer to byte-aligned buffer of data to read from
*
* Outputs: initialized bitstream info struct
*
* Return: none
**************************************************************************************/
void SetBitstreamPointer(BitStreamInfo *bsi, int nBytes, unsigned char *buf)
{
/* init bitstream */
bsi->bytePtr = buf;
bsi->iCache = 0; /* 4-byte unsigned int */
bsi->cachedBits = 0; /* i.e. zero bits in cache */
bsi->nBytes = nBytes;
}
/**************************************************************************************
* Function: RefillBitstreamCache
*
* Description: read new data from bitstream buffer into 32-bit cache
*
* Inputs: pointer to initialized BitStreamInfo struct
*
* Outputs: updated bitstream info struct
*
* Return: none
*
* Notes: only call when iCache is completely drained (resets bitOffset to 0)
* always loads 4 new bytes except when bsi->nBytes < 4 (end of buffer)
* stores data as big-endian in cache, regardless of machine endian-ness
**************************************************************************************/
static __inline void RefillBitstreamCache(BitStreamInfo *bsi)
{
int nBytes = bsi->nBytes;
/* optimize for common case, independent of machine endian-ness */
if (nBytes >= 4) {
bsi->iCache = (*bsi->bytePtr++) << 24;
bsi->iCache |= (*bsi->bytePtr++) << 16;
bsi->iCache |= (*bsi->bytePtr++) << 8;
bsi->iCache |= (*bsi->bytePtr++);
bsi->cachedBits = 32;
bsi->nBytes -= 4;
} else {
bsi->iCache = 0;
while (nBytes--) {
bsi->iCache |= (*bsi->bytePtr++);
bsi->iCache <<= 8;
}
bsi->iCache <<= ((3 - bsi->nBytes)*8);
bsi->cachedBits = 8*bsi->nBytes;
bsi->nBytes = 0;
}
}
/**************************************************************************************
* Function: GetBits
*
* Description: get bits from bitstream, advance bitstream pointer
*
* Inputs: pointer to initialized BitStreamInfo struct
* number of bits to get from bitstream
*
* Outputs: updated bitstream info struct
*
* Return: the next nBits bits of data from bitstream buffer
*
* Notes: nBits must be in range [0, 31], nBits outside this range masked by 0x1f
* for speed, does not indicate error if you overrun bit buffer
* if nBits == 0, returns 0
**************************************************************************************/
unsigned int GetBits(BitStreamInfo *bsi, int nBits)
{
unsigned int data, lowBits;
nBits &= 0x1f; /* nBits mod 32 to avoid unpredictable results like >> by negative amount */
data = bsi->iCache >> (31 - nBits); /* unsigned >> so zero-extend */
data >>= 1; /* do as >> 31, >> 1 so that nBits = 0 works okay (returns 0) */
bsi->iCache <<= nBits; /* left-justify cache */
bsi->cachedBits -= nBits; /* how many bits have we drawn from the cache so far */
/* if we cross an int boundary, refill the cache */
if (bsi->cachedBits < 0) {
lowBits = -bsi->cachedBits;
RefillBitstreamCache(bsi);
data |= bsi->iCache >> (32 - lowBits); /* get the low-order bits */
bsi->cachedBits -= lowBits; /* how many bits have we drawn from the cache so far */
bsi->iCache <<= lowBits; /* left-justify cache */
}
return data;
}
/**************************************************************************************
* Function: GetBitsNoAdvance
*
* Description: get bits from bitstream, do not advance bitstream pointer
*
* Inputs: pointer to initialized BitStreamInfo struct
* number of bits to get from bitstream
*
* Outputs: none (state of BitStreamInfo struct left unchanged)
*
* Return: the next nBits bits of data from bitstream buffer
*
* Notes: nBits must be in range [0, 31], nBits outside this range masked by 0x1f
* for speed, does not indicate error if you overrun bit buffer
* if nBits == 0, returns 0
**************************************************************************************/
unsigned int GetBitsNoAdvance(BitStreamInfo *bsi, int nBits)
{
unsigned char *buf;
unsigned int data, iCache;
signed int lowBits;
nBits &= 0x1f; /* nBits mod 32 to avoid unpredictable results like >> by negative amount */
data = bsi->iCache >> (31 - nBits); /* unsigned >> so zero-extend */
data >>= 1; /* do as >> 31, >> 1 so that nBits = 0 works okay (returns 0) */
lowBits = nBits - bsi->cachedBits; /* how many bits do we have left to read */
/* if we cross an int boundary, read next bytes in buffer */
if (lowBits > 0) {
iCache = 0;
buf = bsi->bytePtr;
while (lowBits > 0) {
iCache <<= 8;
if (buf < bsi->bytePtr + bsi->nBytes)
iCache |= (unsigned int)*buf++;
lowBits -= 8;
}
lowBits = -lowBits;
data |= iCache >> lowBits;
}
return data;
}
/**************************************************************************************
* Function: AdvanceBitstream
*
* Description: move bitstream pointer ahead
*
* Inputs: pointer to initialized BitStreamInfo struct
* number of bits to advance bitstream
*
* Outputs: updated bitstream info struct
*
* Return: none
*
* Notes: generally used following GetBitsNoAdvance(bsi, maxBits)
**************************************************************************************/
void AdvanceBitstream(BitStreamInfo *bsi, int nBits)
{
nBits &= 0x1f;
if (nBits > bsi->cachedBits) {
nBits -= bsi->cachedBits;
RefillBitstreamCache(bsi);
}
bsi->iCache <<= nBits;
bsi->cachedBits -= nBits;
}
/**************************************************************************************
* Function: CalcBitsUsed
*
* Description: calculate how many bits have been read from bitstream
*
* Inputs: pointer to initialized BitStreamInfo struct
* pointer to start of bitstream buffer
* bit offset into first byte of startBuf (0-7)
*
* Outputs: none
*
* Return: number of bits read from bitstream, as offset from startBuf:startOffset
**************************************************************************************/
int CalcBitsUsed(BitStreamInfo *bsi, unsigned char *startBuf, int startOffset)
{
int bitsUsed;
bitsUsed = (bsi->bytePtr - startBuf) * 8;
bitsUsed -= bsi->cachedBits;
bitsUsed -= startOffset;
return bitsUsed;
}
/**************************************************************************************
* Function: ByteAlignBitstream
*
* Description: bump bitstream pointer to start of next byte
*
* Inputs: pointer to initialized BitStreamInfo struct
*
* Outputs: byte-aligned bitstream BitStreamInfo struct
*
* Return: none
*
* Notes: if bitstream is already byte-aligned, do nothing
**************************************************************************************/
void ByteAlignBitstream(BitStreamInfo *bsi)
{
int offset;
offset = bsi->cachedBits & 0x07;
AdvanceBitstream(bsi, offset);
}
|
1137519-player
|
aac/bitstream.c
|
C
|
lgpl
| 9,392
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: dequant.c,v 1.2 2005/05/20 18:05:41 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com), Ken Cooke (kenc@real.com)
* February 2005
*
* dequant.c - transform coefficient dequantization and short-block deinterleaving
**************************************************************************************/
#include "coder.h"
#include "assembly.h"
#define SF_OFFSET 100
/* pow(2, i/4.0) for i = [0,1,2,3], format = Q30 */
static const int pow14[4] = {
0x40000000, 0x4c1bf829, 0x5a82799a, 0x6ba27e65
};
/* pow(2, i/4.0) * pow(j, 4.0/3.0) for i = [0,1,2,3], j = [0,1,2,...,15]
* format = Q28 for j = [0-3], Q25 for j = [4-15]
*/
static const int pow43_14[4][16] = {
{
0x00000000, 0x10000000, 0x285145f3, 0x453a5cdb, /* Q28 */
0x0cb2ff53, 0x111989d6, 0x15ce31c8, 0x1ac7f203, /* Q25 */
0x20000000, 0x257106b9, 0x2b16b4a3, 0x30ed74b4, /* Q25 */
0x36f23fa5, 0x3d227bd3, 0x437be656, 0x49fc823c, /* Q25 */
},
{
0x00000000, 0x1306fe0a, 0x2ff221af, 0x52538f52,
0x0f1a1bf4, 0x1455ccc2, 0x19ee62a8, 0x1fd92396,
0x260dfc14, 0x2c8694d8, 0x333dcb29, 0x3a2f5c7a,
0x4157aed5, 0x48b3aaa3, 0x50409f76, 0x57fc3010,
},
{
0x00000000, 0x16a09e66, 0x39047c0f, 0x61e734aa,
0x11f59ac4, 0x182ec633, 0x1ed66a45, 0x25dfc55a,
0x2d413ccd, 0x34f3462d, 0x3cefc603, 0x4531ab69,
0x4db4adf8, 0x56752054, 0x5f6fcfcd, 0x68a1eca1,
},
{
0x00000000, 0x1ae89f99, 0x43ce3e4b, 0x746d57b2,
0x155b8109, 0x1cc21cdc, 0x24ac1839, 0x2d0a479e,
0x35d13f33, 0x3ef80748, 0x48775c93, 0x524938cd,
0x5c68841d, 0x66d0df0a, 0x717e7bfe, 0x7c6e0305,
},
};
/* pow(j, 4.0 / 3.0) for j = [16,17,18,...,63], format = Q23 */
static const int pow43[48] = {
0x1428a2fa, 0x15db1bd6, 0x1796302c, 0x19598d85,
0x1b24e8bb, 0x1cf7fcfa, 0x1ed28af2, 0x20b4582a,
0x229d2e6e, 0x248cdb55, 0x26832fda, 0x28800000,
0x2a832287, 0x2c8c70a8, 0x2e9bc5d8, 0x30b0ff99,
0x32cbfd4a, 0x34eca001, 0x3712ca62, 0x393e6088,
0x3b6f47e0, 0x3da56717, 0x3fe0a5fc, 0x4220ed72,
0x44662758, 0x46b03e7c, 0x48ff1e87, 0x4b52b3f3,
0x4daaebfd, 0x5007b497, 0x5268fc62, 0x54ceb29c,
0x5738c721, 0x59a72a59, 0x5c19cd35, 0x5e90a129,
0x610b9821, 0x638aa47f, 0x660db90f, 0x6894c90b,
0x6b1fc80c, 0x6daeaa0d, 0x70416360, 0x72d7e8b0,
0x75722ef9, 0x78102b85, 0x7ab1d3ec, 0x7d571e09,
};
/* sqrt(0.5), format = Q31 */
#define SQRTHALF 0x5a82799a
/* Minimax polynomial approximation to pow(x, 4/3), over the range
* poly43lo: x = [0.5, 0.7071]
* poly43hi: x = [0.7071, 1.0]
*
* Relative error < 1E-7
* Coefs are scaled by 4, 2, 1, 0.5, 0.25
*/
static const int poly43lo[5] = { 0x29a0bda9, 0xb02e4828, 0x5957aa1b, 0x236c498d, 0xff581859 };
static const int poly43hi[5] = { 0x10852163, 0xd333f6a4, 0x46e9408b, 0x27c2cef0, 0xfef577b4 };
/* pow2exp[i] = pow(2, i*4/3) exponent */
static const int pow2exp[8] = { 14, 13, 11, 10, 9, 7, 6, 5 };
/* pow2exp[i] = pow(2, i*4/3) fraction */
static const int pow2frac[8] = {
0x6597fa94, 0x50a28be6, 0x7fffffff, 0x6597fa94,
0x50a28be6, 0x7fffffff, 0x6597fa94, 0x50a28be6
};
/**************************************************************************************
* Function: DequantBlock
*
* Description: dequantize one block of transform coefficients (in-place)
*
* Inputs: quantized transform coefficients, range = [0, 8191]
* number of samples to dequantize
* scalefactor for this block of data, range = [0, 256]
*
* Outputs: dequantized transform coefficients in Q(FBITS_OUT_DQ_OFF)
*
* Return: guard bit mask (OR of abs value of all dequantized coefs)
*
* Notes: applies dequant formula y = pow(x, 4.0/3.0) * pow(2, (scale - 100)/4.0)
* * pow(2, FBITS_OUT_DQ_OFF)
* clips outputs to Q(FBITS_OUT_DQ_OFF)
* output has no minimum number of guard bits
**************************************************************************************/
static int DequantBlock(int *inbuf, int nSamps, int scale)
{
int iSamp, scalef, scalei, x, y, gbMask, shift, tab4[4];
const int *tab16, *coef;
if (nSamps <= 0)
return 0;
scale -= SF_OFFSET; /* new range = [-100, 156] */
/* with two's complement numbers, scalei/scalef factorization works for pos and neg values of scale:
* [+4...+7] >> 2 = +1, [ 0...+3] >> 2 = 0, [-4...-1] >> 2 = -1, [-8...-5] >> 2 = -2 ...
* (-1 & 0x3) = 3, (-2 & 0x3) = 2, (-3 & 0x3) = 1, (0 & 0x3) = 0
*
* Example: 2^(-5/4) = 2^(-1) * 2^(-1/4) = 2^-2 * 2^(3/4)
*/
tab16 = pow43_14[scale & 0x3];
scalef = pow14[scale & 0x3];
scalei = (scale >> 2) + FBITS_OUT_DQ_OFF;
/* cache first 4 values:
* tab16[j] = Q28 for j = [0,3]
* tab4[x] = x^(4.0/3.0) * 2^(0.25*scale), Q(FBITS_OUT_DQ_OFF)
*/
shift = 28 - scalei;
if (shift > 31) {
tab4[0] = tab4[1] = tab4[2] = tab4[3] = 0;
} else if (shift <= 0) {
shift = -shift;
if (shift > 31)
shift = 31;
for (x = 0; x < 4; x++) {
y = tab16[x];
if (y > (0x7fffffff >> shift))
y = 0x7fffffff; /* clip (rare) */
else
y <<= shift;
tab4[x] = y;
}
} else {
tab4[0] = 0;
tab4[1] = tab16[1] >> shift;
tab4[2] = tab16[2] >> shift;
tab4[3] = tab16[3] >> shift;
}
gbMask = 0;
do {
iSamp = *inbuf;
x = FASTABS(iSamp);
if (x < 4) {
y = tab4[x];
} else {
if (x < 16) {
/* result: y = Q25 (tab16 = Q25) */
y = tab16[x];
shift = 25 - scalei;
} else if (x < 64) {
/* result: y = Q21 (pow43tab[j] = Q23, scalef = Q30) */
y = pow43[x-16];
shift = 21 - scalei;
y = MULSHIFT32(y, scalef);
} else {
/* normalize to [0x40000000, 0x7fffffff]
* input x = [64, 8191] = [64, 2^13-1]
* ranges:
* shift = 7: 64 - 127
* shift = 6: 128 - 255
* shift = 5: 256 - 511
* shift = 4: 512 - 1023
* shift = 3: 1024 - 2047
* shift = 2: 2048 - 4095
* shift = 1: 4096 - 8191
*/
x <<= 17;
shift = 0;
if (x < 0x08000000)
x <<= 4, shift += 4;
if (x < 0x20000000)
x <<= 2, shift += 2;
if (x < 0x40000000)
x <<= 1, shift += 1;
coef = (x < SQRTHALF) ? poly43lo : poly43hi;
/* polynomial */
y = coef[0];
y = MULSHIFT32(y, x) + coef[1];
y = MULSHIFT32(y, x) + coef[2];
y = MULSHIFT32(y, x) + coef[3];
y = MULSHIFT32(y, x) + coef[4];
y = MULSHIFT32(y, pow2frac[shift]) << 3;
/* fractional scale
* result: y = Q21 (pow43tab[j] = Q23, scalef = Q30)
*/
y = MULSHIFT32(y, scalef); /* now y is Q24 */
shift = 24 - scalei - pow2exp[shift];
}
/* integer scale */
if (shift <= 0) {
shift = -shift;
if (shift > 31)
shift = 31;
if (y > (0x7fffffff >> shift))
y = 0x7fffffff; /* clip (rare) */
else
y <<= shift;
} else {
if (shift > 31)
shift = 31;
y >>= shift;
}
}
/* sign and store (gbMask used to count GB's) */
gbMask |= y;
/* apply sign */
iSamp >>= 31;
y ^= iSamp;
y -= iSamp;
*inbuf++ = y;
} while (--nSamps);
return gbMask;
}
/**************************************************************************************
* Function: Dequantize
*
* Description: dequantize all transform coefficients for one channel
*
* Inputs: valid AACDecInfo struct (including unpacked, quantized coefficients)
* index of current channel
*
* Outputs: dequantized coefficients, including short-block deinterleaving
* flags indicating if intensity and/or PNS is active
* minimum guard bit count for dequantized coefficients
*
* Return: 0 if successful, error code (< 0) if error
**************************************************************************************/
int Dequantize(AACDecInfo *aacDecInfo, int ch)
{
int gp, cb, sfb, win, width, nSamps, gbMask;
int *coef;
const short *sfbTab;
unsigned char *sfbCodeBook;
short *scaleFactors;
PSInfoBase *psi;
ICSInfo *icsInfo;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return ERR_AAC_NULL_POINTER;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
icsInfo = (ch == 1 && psi->commonWin == 1) ? &(psi->icsInfo[0]) : &(psi->icsInfo[ch]);
if (icsInfo->winSequence == 2) {
sfbTab = sfBandTabShort + sfBandTabShortOffset[psi->sampRateIdx];
nSamps = NSAMPS_SHORT;
} else {
sfbTab = sfBandTabLong + sfBandTabLongOffset[psi->sampRateIdx];
nSamps = NSAMPS_LONG;
}
coef = psi->coef[ch];
sfbCodeBook = psi->sfbCodeBook[ch];
scaleFactors = psi->scaleFactors[ch];
psi->intensityUsed[ch] = 0;
psi->pnsUsed[ch] = 0;
gbMask = 0;
for (gp = 0; gp < icsInfo->numWinGroup; gp++) {
for (win = 0; win < icsInfo->winGroupLen[gp]; win++) {
for (sfb = 0; sfb < icsInfo->maxSFB; sfb++) {
/* dequantize one scalefactor band (not necessary if codebook is intensity or PNS)
* for zero codebook, still run dequantizer in case non-zero pulse data was added
*/
cb = (int)(sfbCodeBook[sfb]);
width = sfbTab[sfb+1] - sfbTab[sfb];
if (cb >= 0 && cb <= 11)
gbMask |= DequantBlock(coef, width, scaleFactors[sfb]);
else if (cb == 13)
psi->pnsUsed[ch] = 1;
else if (cb == 14 || cb == 15)
psi->intensityUsed[ch] = 1; /* should only happen if ch == 1 */
coef += width;
}
coef += (nSamps - sfbTab[icsInfo->maxSFB]);
}
sfbCodeBook += icsInfo->maxSFB;
scaleFactors += icsInfo->maxSFB;
}
aacDecInfo->pnsUsed |= psi->pnsUsed[ch]; /* set flag if PNS used for any channel */
/* calculate number of guard bits in dequantized data */
psi->gbCurrent[ch] = CLZ(gbMask) - 1;
return ERR_AAC_NONE;
}
/**************************************************************************************
* Function: DeinterleaveShortBlocks
*
* Description: deinterleave transform coefficients in short blocks for one channel
*
* Inputs: valid AACDecInfo struct (including unpacked, quantized coefficients)
* index of current channel
*
* Outputs: deinterleaved coefficients (window groups into 8 separate windows)
*
* Return: 0 if successful, error code (< 0) if error
*
* Notes: only necessary if deinterleaving not part of Huffman decoding
**************************************************************************************/
int DeinterleaveShortBlocks(AACDecInfo *aacDecInfo, int ch)
{
/* not used for this implementation - short block deinterleaving performed during Huffman decoding */
return ERR_AAC_NONE;
}
|
1137519-player
|
aac/dequant.c
|
C
|
lgpl
| 12,135
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: tns.c,v 1.2 2005/05/24 16:01:55 albertofloyd Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* tns.c - apply TNS to spectrum
**************************************************************************************/
#include "coder.h"
#include "assembly.h"
#define FBITS_LPC_COEFS 20
/* inverse quantization tables for TNS filter coefficients, format = Q31
* see bottom of file for table generation
* negative (vs. spec) since we use MADD for filter kernel
*/
static const int invQuant3[16] = {
0x00000000, 0xc8767f65, 0x9becf22c, 0x83358feb, 0x83358feb, 0x9becf22c, 0xc8767f65, 0x00000000,
0x2bc750e9, 0x5246dd49, 0x6ed9eba1, 0x7e0e2e32, 0x7e0e2e32, 0x6ed9eba1, 0x5246dd49, 0x2bc750e9,
};
static const int invQuant4[16] = {
0x00000000, 0xe5632654, 0xcbf00dbe, 0xb4c373ee, 0xa0e0a15f, 0x9126145f, 0x8643c7b3, 0x80b381ac,
0x7f7437ad, 0x7b1d1a49, 0x7294b5f2, 0x66256db2, 0x563ba8aa, 0x4362210e, 0x2e3d2abb, 0x17851aad,
};
/**************************************************************************************
* Function: DecodeLPCCoefs
*
* Description: decode LPC coefficients for TNS
*
* Inputs: order of TNS filter
* resolution of coefficients (3 or 4 bits)
* coefficients unpacked from bitstream
* scratch buffer (b) of size >= order
*
* Outputs: LPC coefficients in Q(FBITS_LPC_COEFS), in 'a'
*
* Return: none
*
* Notes: assumes no guard bits in input transform coefficients
* a[i] = Q(FBITS_LPC_COEFS), don't store a0 = 1.0
* (so a[0] = first delay tap, etc.)
* max abs(a[i]) < log2(order), so for max order = 20 a[i] < 4.4
* (up to 3 bits of gain) so a[i] has at least 31 - FBITS_LPC_COEFS - 3
* guard bits
* to ensure no intermediate overflow in all-pole filter, set
* FBITS_LPC_COEFS such that number of guard bits >= log2(max order)
**************************************************************************************/
static void DecodeLPCCoefs(int order, int res, signed char *filtCoef, int *a, int *b)
{
int i, m, t;
const int *invQuantTab;
if (res == 3) invQuantTab = invQuant3;
else if (res == 4) invQuantTab = invQuant4;
else return;
for (m = 0; m < order; m++) {
t = invQuantTab[filtCoef[m] & 0x0f]; /* t = Q31 */
for (i = 0; i < m; i++)
b[i] = a[i] - (MULSHIFT32(t, a[m-i-1]) << 1);
for (i = 0; i < m; i++)
a[i] = b[i];
a[m] = t >> (31 - FBITS_LPC_COEFS);
}
}
/**************************************************************************************
* Function: FilterRegion
*
* Description: apply LPC filter to one region of coefficients
*
* Inputs: number of transform coefficients in this region
* direction flag (forward = 1, backward = -1)
* order of filter
* 'size' transform coefficients
* 'order' LPC coefficients in Q(FBITS_LPC_COEFS)
* scratch buffer for history (must be >= order samples long)
*
* Outputs: filtered transform coefficients
*
* Return: guard bit mask (OR of abs value of all filtered transform coefs)
*
* Notes: assumes no guard bits in input transform coefficients
* gains 0 int bits
* history buffer does not need to be preserved between regions
**************************************************************************************/
static int FilterRegion(int size, int dir, int order, int *audioCoef, int *a, int *hist)
{
int i, j, y, hi32, inc, gbMask;
U64 sum64;
/* init history to 0 every time */
for (i = 0; i < order; i++)
hist[i] = 0;
sum64.w64 = 0; /* avoid warning */
gbMask = 0;
inc = (dir ? -1 : 1);
do {
/* sum64 = a0*y[n] = 1.0*y[n] */
y = *audioCoef;
sum64.r.hi32 = y >> (32 - FBITS_LPC_COEFS);
sum64.r.lo32 = y << FBITS_LPC_COEFS;
/* sum64 += (a1*y[n-1] + a2*y[n-2] + ... + a[order-1]*y[n-(order-1)]) */
for (j = order - 1; j > 0; j--) {
sum64.w64 = MADD64(sum64.w64, hist[j], a[j]);
hist[j] = hist[j-1];
}
sum64.w64 = MADD64(sum64.w64, hist[0], a[0]);
y = (sum64.r.hi32 << (32 - FBITS_LPC_COEFS)) | (sum64.r.lo32 >> FBITS_LPC_COEFS);
/* clip output (rare) */
hi32 = sum64.r.hi32;
if ((hi32 >> 31) != (hi32 >> (FBITS_LPC_COEFS-1)))
y = (hi32 >> 31) ^ 0x7fffffff;
hist[0] = y;
*audioCoef = y;
audioCoef += inc;
gbMask |= FASTABS(y);
} while (--size);
return gbMask;
}
/**************************************************************************************
* Function: TNSFilter
*
* Description: apply temporal noise shaping, if enabled
*
* Inputs: valid AACDecInfo struct
* index of current channel
*
* Outputs: updated transform coefficients
* updated minimum guard bit count for this channel
*
* Return: 0 if successful, -1 if error
**************************************************************************************/
int TNSFilter(AACDecInfo *aacDecInfo, int ch)
{
int win, winLen, nWindows, nSFB, filt, bottom, top, order, maxOrder, dir;
int start, end, size, tnsMaxBand, numFilt, gbMask;
int *audioCoef;
unsigned char *filtLength, *filtOrder, *filtRes, *filtDir;
signed char *filtCoef;
const unsigned char *tnsMaxBandTab;
const short *sfbTab;
ICSInfo *icsInfo;
TNSInfo *ti;
PSInfoBase *psi;
/* validate pointers */
if (!aacDecInfo || !aacDecInfo->psInfoBase)
return -1;
psi = (PSInfoBase *)(aacDecInfo->psInfoBase);
icsInfo = (ch == 1 && psi->commonWin == 1) ? &(psi->icsInfo[0]) : &(psi->icsInfo[ch]);
ti = &psi->tnsInfo[ch];
if (!ti->tnsDataPresent)
return 0;
if (icsInfo->winSequence == 2) {
nWindows = NWINDOWS_SHORT;
winLen = NSAMPS_SHORT;
nSFB = sfBandTotalShort[psi->sampRateIdx];
maxOrder = tnsMaxOrderShort[aacDecInfo->profile];
sfbTab = sfBandTabShort + sfBandTabShortOffset[psi->sampRateIdx];
tnsMaxBandTab = tnsMaxBandsShort + tnsMaxBandsShortOffset[aacDecInfo->profile];
tnsMaxBand = tnsMaxBandTab[psi->sampRateIdx];
} else {
nWindows = NWINDOWS_LONG;
winLen = NSAMPS_LONG;
nSFB = sfBandTotalLong[psi->sampRateIdx];
maxOrder = tnsMaxOrderLong[aacDecInfo->profile];
sfbTab = sfBandTabLong + sfBandTabLongOffset[psi->sampRateIdx];
tnsMaxBandTab = tnsMaxBandsLong + tnsMaxBandsLongOffset[aacDecInfo->profile];
tnsMaxBand = tnsMaxBandTab[psi->sampRateIdx];
}
if (tnsMaxBand > icsInfo->maxSFB)
tnsMaxBand = icsInfo->maxSFB;
filtRes = ti->coefRes;
filtLength = ti->length;
filtOrder = ti->order;
filtDir = ti->dir;
filtCoef = ti->coef;
gbMask = 0;
audioCoef = psi->coef[ch];
for (win = 0; win < nWindows; win++) {
bottom = nSFB;
numFilt = ti->numFilt[win];
for (filt = 0; filt < numFilt; filt++) {
top = bottom;
bottom = top - *filtLength++;
bottom = MAX(bottom, 0);
order = *filtOrder++;
order = MIN(order, maxOrder);
if (order) {
start = sfbTab[MIN(bottom, tnsMaxBand)];
end = sfbTab[MIN(top, tnsMaxBand)];
size = end - start;
if (size > 0) {
dir = *filtDir++;
if (dir)
start = end - 1;
DecodeLPCCoefs(order, filtRes[win], filtCoef, psi->tnsLPCBuf, psi->tnsWorkBuf);
gbMask |= FilterRegion(size, dir, order, audioCoef + start, psi->tnsLPCBuf, psi->tnsWorkBuf);
}
filtCoef += order;
}
}
audioCoef += winLen;
}
/* update guard bit count if necessary */
size = CLZ(gbMask) - 1;
if (psi->gbCurrent[ch] > size)
psi->gbCurrent[ch] = size;
return 0;
}
/* Code to generate invQuantXXX[] tables
* {
* int res, i, t;
* double powScale, iqfac, iqfac_m, d;
*
* powScale = pow(2.0, 31) * -1.0; / ** make coefficients negative for using MADD in kernel ** /
* for (res = 3; res <= 4; res++) {
* iqfac = ( ((1 << (res-1)) - 0.5) * (2.0 / M_PI) );
* iqfac_m = ( ((1 << (res-1)) + 0.5) * (2.0 / M_PI) );
* printf("static const int invQuant%d[16] = {\n", res);
* for (i = 0; i < 16; i++) {
* / ** extend bottom 4 bits into signed, 2's complement number ** /
* t = (i << 28) >> 28;
*
* if (t >= 0) d = sin(t / iqfac);
* else d = sin(t / iqfac_m);
*
* d *= powScale;
* printf("0x%08x, ", (int)(d > 0 ? d + 0.5 : d - 0.5));
* if ((i & 0x07) == 0x07)
* printf("\n");
* }
* printf("};\n\n");
* }
* }
*/
|
1137519-player
|
aac/tns.c
|
C
|
lgpl
| 10,214
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbrside.c,v 1.2 2005/05/24 16:01:55 albertofloyd Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbrside.c - functions for unpacking side info from SBR bitstream
**************************************************************************************/
#include "sbr.h"
/**************************************************************************************
* Function: GetSampRateIdx
*
* Description: get index of given sample rate
*
* Inputs: sample rate (in Hz)
*
* Outputs: none
*
* Return: index of sample rate (table 1.15 in 14496-3:2001(E))
* -1 if sample rate not found in table
**************************************************************************************/
int GetSampRateIdx(int sampRate)
{
int idx;
for (idx = 0; idx < NUM_SAMPLE_RATES; idx++) {
if (sampRate == sampRateTab[idx])
return idx;
}
return -1;
}
/**************************************************************************************
* Function: UnpackSBRHeader
*
* Description: unpack SBR header (table 4.56)
*
* Inputs: BitStreamInfo struct pointing to start of SBR header
*
* Outputs: initialized SBRHeader struct for this SCE/CPE block
*
* Return: non-zero if frame reset is triggered, zero otherwise
**************************************************************************************/
int UnpackSBRHeader(BitStreamInfo *bsi, SBRHeader *sbrHdr)
{
SBRHeader sbrHdrPrev;
/* save previous values so we know whether to reset decoder */
sbrHdrPrev.startFreq = sbrHdr->startFreq;
sbrHdrPrev.stopFreq = sbrHdr->stopFreq;
sbrHdrPrev.freqScale = sbrHdr->freqScale;
sbrHdrPrev.alterScale = sbrHdr->alterScale;
sbrHdrPrev.crossOverBand = sbrHdr->crossOverBand;
sbrHdrPrev.noiseBands = sbrHdr->noiseBands;
sbrHdr->ampRes = GetBits(bsi, 1);
sbrHdr->startFreq = GetBits(bsi, 4);
sbrHdr->stopFreq = GetBits(bsi, 4);
sbrHdr->crossOverBand = GetBits(bsi, 3);
sbrHdr->resBitsHdr = GetBits(bsi, 2);
sbrHdr->hdrExtra1 = GetBits(bsi, 1);
sbrHdr->hdrExtra2 = GetBits(bsi, 1);
if (sbrHdr->hdrExtra1) {
sbrHdr->freqScale = GetBits(bsi, 2);
sbrHdr->alterScale = GetBits(bsi, 1);
sbrHdr->noiseBands = GetBits(bsi, 2);
} else {
/* defaults */
sbrHdr->freqScale = 2;
sbrHdr->alterScale = 1;
sbrHdr->noiseBands = 2;
}
if (sbrHdr->hdrExtra2) {
sbrHdr->limiterBands = GetBits(bsi, 2);
sbrHdr->limiterGains = GetBits(bsi, 2);
sbrHdr->interpFreq = GetBits(bsi, 1);
sbrHdr->smoothMode = GetBits(bsi, 1);
} else {
/* defaults */
sbrHdr->limiterBands = 2;
sbrHdr->limiterGains = 2;
sbrHdr->interpFreq = 1;
sbrHdr->smoothMode = 1;
}
sbrHdr->count++;
/* if any of these have changed from previous frame, reset the SBR module */
if (sbrHdr->startFreq != sbrHdrPrev.startFreq || sbrHdr->stopFreq != sbrHdrPrev.stopFreq ||
sbrHdr->freqScale != sbrHdrPrev.freqScale || sbrHdr->alterScale != sbrHdrPrev.alterScale ||
sbrHdr->crossOverBand != sbrHdrPrev.crossOverBand || sbrHdr->noiseBands != sbrHdrPrev.noiseBands
)
return -1;
else
return 0;
}
/* cLog2[i] = ceil(log2(i)) (disregard i == 0) */
static const unsigned char cLog2[9] = {0, 0, 1, 2, 2, 3, 3, 3, 3};
/**************************************************************************************
* Function: UnpackSBRGrid
*
* Description: unpack SBR grid (table 4.62)
*
* Inputs: BitStreamInfo struct pointing to start of SBR grid
* initialized SBRHeader struct for this SCE/CPE block
*
* Outputs: initialized SBRGrid struct for this channel
*
* Return: none
**************************************************************************************/
static void UnpackSBRGrid(BitStreamInfo *bsi, SBRHeader *sbrHdr, SBRGrid *sbrGrid)
{
int numEnvRaw, env, rel, pBits, border, middleBorder=0;
unsigned char relBordLead[MAX_NUM_ENV], relBordTrail[MAX_NUM_ENV];
unsigned char relBorder0[3], relBorder1[3], relBorder[3];
unsigned char numRelBorder0, numRelBorder1, numRelBorder, numRelLead=0, numRelTrail;
unsigned char absBordLead=0, absBordTrail=0, absBorder;
sbrGrid->ampResFrame = sbrHdr->ampRes;
sbrGrid->frameClass = GetBits(bsi, 2);
switch (sbrGrid->frameClass) {
case SBR_GRID_FIXFIX:
numEnvRaw = GetBits(bsi, 2);
sbrGrid->numEnv = (1 << numEnvRaw);
if (sbrGrid->numEnv == 1)
sbrGrid->ampResFrame = 0;
ASSERT(sbrGrid->numEnv == 1 || sbrGrid->numEnv == 2 || sbrGrid->numEnv == 4);
sbrGrid->freqRes[0] = GetBits(bsi, 1);
for (env = 1; env < sbrGrid->numEnv; env++)
sbrGrid->freqRes[env] = sbrGrid->freqRes[0];
absBordLead = 0;
absBordTrail = NUM_TIME_SLOTS;
numRelLead = sbrGrid->numEnv - 1;
numRelTrail = 0;
/* numEnv = 1, 2, or 4 */
if (sbrGrid->numEnv == 1) border = NUM_TIME_SLOTS / 1;
else if (sbrGrid->numEnv == 2) border = NUM_TIME_SLOTS / 2;
else border = NUM_TIME_SLOTS / 4;
for (rel = 0; rel < numRelLead; rel++)
relBordLead[rel] = border;
middleBorder = (sbrGrid->numEnv >> 1);
break;
case SBR_GRID_FIXVAR:
absBorder = GetBits(bsi, 2) + NUM_TIME_SLOTS;
numRelBorder = GetBits(bsi, 2);
sbrGrid->numEnv = numRelBorder + 1;
for (rel = 0; rel < numRelBorder; rel++)
relBorder[rel] = 2*GetBits(bsi, 2) + 2;
pBits = cLog2[sbrGrid->numEnv + 1];
sbrGrid->pointer = GetBits(bsi, pBits);
for (env = sbrGrid->numEnv - 1; env >= 0; env--)
sbrGrid->freqRes[env] = GetBits(bsi, 1);
absBordLead = 0;
absBordTrail = absBorder;
numRelLead = 0;
numRelTrail = numRelBorder;
for (rel = 0; rel < numRelTrail; rel++)
relBordTrail[rel] = relBorder[rel];
if (sbrGrid->pointer > 1) middleBorder = sbrGrid->numEnv + 1 - sbrGrid->pointer;
else middleBorder = sbrGrid->numEnv - 1;
break;
case SBR_GRID_VARFIX:
absBorder = GetBits(bsi, 2);
numRelBorder = GetBits(bsi, 2);
sbrGrid->numEnv = numRelBorder + 1;
for (rel = 0; rel < numRelBorder; rel++)
relBorder[rel] = 2*GetBits(bsi, 2) + 2;
pBits = cLog2[sbrGrid->numEnv + 1];
sbrGrid->pointer = GetBits(bsi, pBits);
for (env = 0; env < sbrGrid->numEnv; env++)
sbrGrid->freqRes[env] = GetBits(bsi, 1);
absBordLead = absBorder;
absBordTrail = NUM_TIME_SLOTS;
numRelLead = numRelBorder;
numRelTrail = 0;
for (rel = 0; rel < numRelLead; rel++)
relBordLead[rel] = relBorder[rel];
if (sbrGrid->pointer == 0) middleBorder = 1;
else if (sbrGrid->pointer == 1) middleBorder = sbrGrid->numEnv - 1;
else middleBorder = sbrGrid->pointer - 1;
break;
case SBR_GRID_VARVAR:
absBordLead = GetBits(bsi, 2); /* absBorder0 */
absBordTrail = GetBits(bsi, 2) + NUM_TIME_SLOTS; /* absBorder1 */
numRelBorder0 = GetBits(bsi, 2);
numRelBorder1 = GetBits(bsi, 2);
sbrGrid->numEnv = numRelBorder0 + numRelBorder1 + 1;
ASSERT(sbrGrid->numEnv <= 5);
for (rel = 0; rel < numRelBorder0; rel++)
relBorder0[rel] = 2*GetBits(bsi, 2) + 2;
for (rel = 0; rel < numRelBorder1; rel++)
relBorder1[rel] = 2*GetBits(bsi, 2) + 2;
pBits = cLog2[numRelBorder0 + numRelBorder1 + 2];
sbrGrid->pointer = GetBits(bsi, pBits);
for (env = 0; env < sbrGrid->numEnv; env++)
sbrGrid->freqRes[env] = GetBits(bsi, 1);
numRelLead = numRelBorder0;
numRelTrail = numRelBorder1;
for (rel = 0; rel < numRelLead; rel++)
relBordLead[rel] = relBorder0[rel];
for (rel = 0; rel < numRelTrail; rel++)
relBordTrail[rel] = relBorder1[rel];
if (sbrGrid->pointer > 1) middleBorder = sbrGrid->numEnv + 1 - sbrGrid->pointer;
else middleBorder = sbrGrid->numEnv - 1;
break;
}
/* build time border vector */
sbrGrid->envTimeBorder[0] = absBordLead * SAMPLES_PER_SLOT;
rel = 0;
border = absBordLead;
for (env = 1; env <= numRelLead; env++) {
border += relBordLead[rel++];
sbrGrid->envTimeBorder[env] = border * SAMPLES_PER_SLOT;
}
rel = 0;
border = absBordTrail;
for (env = sbrGrid->numEnv - 1; env > numRelLead; env--) {
border -= relBordTrail[rel++];
sbrGrid->envTimeBorder[env] = border * SAMPLES_PER_SLOT;
}
sbrGrid->envTimeBorder[sbrGrid->numEnv] = absBordTrail * SAMPLES_PER_SLOT;
if (sbrGrid->numEnv > 1) {
sbrGrid->numNoiseFloors = 2;
sbrGrid->noiseTimeBorder[0] = sbrGrid->envTimeBorder[0];
sbrGrid->noiseTimeBorder[1] = sbrGrid->envTimeBorder[middleBorder];
sbrGrid->noiseTimeBorder[2] = sbrGrid->envTimeBorder[sbrGrid->numEnv];
} else {
sbrGrid->numNoiseFloors = 1;
sbrGrid->noiseTimeBorder[0] = sbrGrid->envTimeBorder[0];
sbrGrid->noiseTimeBorder[1] = sbrGrid->envTimeBorder[1];
}
}
/**************************************************************************************
* Function: UnpackDeltaTimeFreq
*
* Description: unpack time/freq flags for delta coding of SBR envelopes (table 4.63)
*
* Inputs: BitStreamInfo struct pointing to start of dt/df flags
* number of envelopes
* number of noise floors
*
* Outputs: delta flags for envelope and noise floors
*
* Return: none
**************************************************************************************/
static void UnpackDeltaTimeFreq(BitStreamInfo *bsi, int numEnv, unsigned char *deltaFlagEnv,
int numNoiseFloors, unsigned char *deltaFlagNoise)
{
int env, noiseFloor;
for (env = 0; env < numEnv; env++)
deltaFlagEnv[env] = GetBits(bsi, 1);
for (noiseFloor = 0; noiseFloor < numNoiseFloors; noiseFloor++)
deltaFlagNoise[noiseFloor] = GetBits(bsi, 1);
}
/**************************************************************************************
* Function: UnpackInverseFilterMode
*
* Description: unpack invf flags for chirp factor calculation (table 4.64)
*
* Inputs: BitStreamInfo struct pointing to start of invf flags
* number of noise floor bands
*
* Outputs: invf flags for noise floor bands
*
* Return: none
**************************************************************************************/
static void UnpackInverseFilterMode(BitStreamInfo *bsi, int numNoiseFloorBands, unsigned char *mode)
{
int n;
for (n = 0; n < numNoiseFloorBands; n++)
mode[n] = GetBits(bsi, 2);
}
/**************************************************************************************
* Function: UnpackSinusoids
*
* Description: unpack sinusoid (harmonic) flags for each SBR subband (table 4.67)
*
* Inputs: BitStreamInfo struct pointing to start of sinusoid flags
* number of high resolution SBR subbands (nHigh)
*
* Outputs: sinusoid flags for each SBR subband, zero-filled above nHigh
*
* Return: none
**************************************************************************************/
static void UnpackSinusoids(BitStreamInfo *bsi, int nHigh, int addHarmonicFlag, unsigned char *addHarmonic)
{
int n;
n = 0;
if (addHarmonicFlag) {
for ( ; n < nHigh; n++)
addHarmonic[n] = GetBits(bsi, 1);
}
/* zero out unused bands */
for ( ; n < MAX_QMF_BANDS; n++)
addHarmonic[n] = 0;
}
/**************************************************************************************
* Function: CopyCouplingGrid
*
* Description: copy grid parameters from left to right for channel coupling
*
* Inputs: initialized SBRGrid struct for left channel
*
* Outputs: initialized SBRGrid struct for right channel
*
* Return: none
**************************************************************************************/
static void CopyCouplingGrid(SBRGrid *sbrGridLeft, SBRGrid *sbrGridRight)
{
int env, noiseFloor;
sbrGridRight->frameClass = sbrGridLeft->frameClass;
sbrGridRight->ampResFrame = sbrGridLeft->ampResFrame;
sbrGridRight->pointer = sbrGridLeft->pointer;
sbrGridRight->numEnv = sbrGridLeft->numEnv;
for (env = 0; env < sbrGridLeft->numEnv; env++) {
sbrGridRight->envTimeBorder[env] = sbrGridLeft->envTimeBorder[env];
sbrGridRight->freqRes[env] = sbrGridLeft->freqRes[env];
}
sbrGridRight->envTimeBorder[env] = sbrGridLeft->envTimeBorder[env]; /* borders are [0, numEnv] inclusive */
sbrGridRight->numNoiseFloors = sbrGridLeft->numNoiseFloors;
for (noiseFloor = 0; noiseFloor <= sbrGridLeft->numNoiseFloors; noiseFloor++)
sbrGridRight->noiseTimeBorder[noiseFloor] = sbrGridLeft->noiseTimeBorder[noiseFloor];
/* numEnvPrev, numNoiseFloorsPrev, freqResPrev are updated in DecodeSBREnvelope() and DecodeSBRNoise() */
}
/**************************************************************************************
* Function: CopyCouplingInverseFilterMode
*
* Description: copy invf flags from left to right for channel coupling
*
* Inputs: invf flags for left channel
* number of noise floor bands
*
* Outputs: invf flags for right channel
*
* Return: none
**************************************************************************************/
static void CopyCouplingInverseFilterMode(int numNoiseFloorBands, unsigned char *modeLeft, unsigned char *modeRight)
{
int band;
for (band = 0; band < numNoiseFloorBands; band++)
modeRight[band] = modeLeft[band];
}
/**************************************************************************************
* Function: UnpackSBRSingleChannel
*
* Description: unpack sideband info (grid, delta flags, invf flags, envelope and
* noise floor configuration, sinusoids) for a single channel
*
* Inputs: BitStreamInfo struct pointing to start of sideband info
* initialized PSInfoSBR struct (after parsing SBR header and building
* frequency tables)
* base output channel (range = [0, nChans-1])
*
* Outputs: updated PSInfoSBR struct (SBRGrid and SBRChan)
*
* Return: none
**************************************************************************************/
void UnpackSBRSingleChannel(BitStreamInfo *bsi, PSInfoSBR *psi, int chBase)
{
int bitsLeft;
SBRHeader *sbrHdr = &(psi->sbrHdr[chBase]);
SBRGrid *sbrGridL = &(psi->sbrGrid[chBase+0]);
SBRFreq *sbrFreq = &(psi->sbrFreq[chBase]);
SBRChan *sbrChanL = &(psi->sbrChan[chBase+0]);
psi->dataExtra = GetBits(bsi, 1);
if (psi->dataExtra)
psi->resBitsData = GetBits(bsi, 4);
UnpackSBRGrid(bsi, sbrHdr, sbrGridL);
UnpackDeltaTimeFreq(bsi, sbrGridL->numEnv, sbrChanL->deltaFlagEnv, sbrGridL->numNoiseFloors, sbrChanL->deltaFlagNoise);
UnpackInverseFilterMode(bsi, sbrFreq->numNoiseFloorBands, sbrChanL->invfMode[1]);
DecodeSBREnvelope(bsi, psi, sbrGridL, sbrFreq, sbrChanL, 0);
DecodeSBRNoise(bsi, psi, sbrGridL, sbrFreq, sbrChanL, 0);
sbrChanL->addHarmonicFlag[1] = GetBits(bsi, 1);
UnpackSinusoids(bsi, sbrFreq->nHigh, sbrChanL->addHarmonicFlag[1], sbrChanL->addHarmonic[1]);
psi->extendedDataPresent = GetBits(bsi, 1);
if (psi->extendedDataPresent) {
psi->extendedDataSize = GetBits(bsi, 4);
if (psi->extendedDataSize == 15)
psi->extendedDataSize += GetBits(bsi, 8);
bitsLeft = 8 * psi->extendedDataSize;
/* get ID, unpack extension info, do whatever is necessary with it... */
while (bitsLeft > 0) {
GetBits(bsi, 8);
bitsLeft -= 8;
}
}
}
/**************************************************************************************
* Function: UnpackSBRChannelPair
*
* Description: unpack sideband info (grid, delta flags, invf flags, envelope and
* noise floor configuration, sinusoids) for a channel pair
*
* Inputs: BitStreamInfo struct pointing to start of sideband info
* initialized PSInfoSBR struct (after parsing SBR header and building
* frequency tables)
* base output channel (range = [0, nChans-1])
*
* Outputs: updated PSInfoSBR struct (SBRGrid and SBRChan for both channels)
*
* Return: none
**************************************************************************************/
void UnpackSBRChannelPair(BitStreamInfo *bsi, PSInfoSBR *psi, int chBase)
{
int bitsLeft;
SBRHeader *sbrHdr = &(psi->sbrHdr[chBase]);
SBRGrid *sbrGridL = &(psi->sbrGrid[chBase+0]), *sbrGridR = &(psi->sbrGrid[chBase+1]);
SBRFreq *sbrFreq = &(psi->sbrFreq[chBase]);
SBRChan *sbrChanL = &(psi->sbrChan[chBase+0]), *sbrChanR = &(psi->sbrChan[chBase+1]);
psi->dataExtra = GetBits(bsi, 1);
if (psi->dataExtra) {
psi->resBitsData = GetBits(bsi, 4);
psi->resBitsData = GetBits(bsi, 4);
}
psi->couplingFlag = GetBits(bsi, 1);
if (psi->couplingFlag) {
UnpackSBRGrid(bsi, sbrHdr, sbrGridL);
CopyCouplingGrid(sbrGridL, sbrGridR);
UnpackDeltaTimeFreq(bsi, sbrGridL->numEnv, sbrChanL->deltaFlagEnv, sbrGridL->numNoiseFloors, sbrChanL->deltaFlagNoise);
UnpackDeltaTimeFreq(bsi, sbrGridR->numEnv, sbrChanR->deltaFlagEnv, sbrGridR->numNoiseFloors, sbrChanR->deltaFlagNoise);
UnpackInverseFilterMode(bsi, sbrFreq->numNoiseFloorBands, sbrChanL->invfMode[1]);
CopyCouplingInverseFilterMode(sbrFreq->numNoiseFloorBands, sbrChanL->invfMode[1], sbrChanR->invfMode[1]);
DecodeSBREnvelope(bsi, psi, sbrGridL, sbrFreq, sbrChanL, 0);
DecodeSBRNoise(bsi, psi, sbrGridL, sbrFreq, sbrChanL, 0);
DecodeSBREnvelope(bsi, psi, sbrGridR, sbrFreq, sbrChanR, 1);
DecodeSBRNoise(bsi, psi, sbrGridR, sbrFreq, sbrChanR, 1);
/* pass RIGHT sbrChan struct */
UncoupleSBREnvelope(psi, sbrGridL, sbrFreq, sbrChanR);
UncoupleSBRNoise(psi, sbrGridL, sbrFreq, sbrChanR);
} else {
UnpackSBRGrid(bsi, sbrHdr, sbrGridL);
UnpackSBRGrid(bsi, sbrHdr, sbrGridR);
UnpackDeltaTimeFreq(bsi, sbrGridL->numEnv, sbrChanL->deltaFlagEnv, sbrGridL->numNoiseFloors, sbrChanL->deltaFlagNoise);
UnpackDeltaTimeFreq(bsi, sbrGridR->numEnv, sbrChanR->deltaFlagEnv, sbrGridR->numNoiseFloors, sbrChanR->deltaFlagNoise);
UnpackInverseFilterMode(bsi, sbrFreq->numNoiseFloorBands, sbrChanL->invfMode[1]);
UnpackInverseFilterMode(bsi, sbrFreq->numNoiseFloorBands, sbrChanR->invfMode[1]);
DecodeSBREnvelope(bsi, psi, sbrGridL, sbrFreq, sbrChanL, 0);
DecodeSBREnvelope(bsi, psi, sbrGridR, sbrFreq, sbrChanR, 1);
DecodeSBRNoise(bsi, psi, sbrGridL, sbrFreq, sbrChanL, 0);
DecodeSBRNoise(bsi, psi, sbrGridR, sbrFreq, sbrChanR, 1);
}
sbrChanL->addHarmonicFlag[1] = GetBits(bsi, 1);
UnpackSinusoids(bsi, sbrFreq->nHigh, sbrChanL->addHarmonicFlag[1], sbrChanL->addHarmonic[1]);
sbrChanR->addHarmonicFlag[1] = GetBits(bsi, 1);
UnpackSinusoids(bsi, sbrFreq->nHigh, sbrChanR->addHarmonicFlag[1], sbrChanR->addHarmonic[1]);
psi->extendedDataPresent = GetBits(bsi, 1);
if (psi->extendedDataPresent) {
psi->extendedDataSize = GetBits(bsi, 4);
if (psi->extendedDataSize == 15)
psi->extendedDataSize += GetBits(bsi, 8);
bitsLeft = 8 * psi->extendedDataSize;
/* get ID, unpack extension info, do whatever is necessary with it... */
while (bitsLeft > 0) {
GetBits(bsi, 8);
bitsLeft -= 8;
}
}
}
|
1137519-player
|
aac/sbrside.c
|
C
|
lgpl
| 20,531
|
@ ***** BEGIN LICENSE BLOCK *****
@ Source last modified: $Id: sbrqmfsk.s,v 1.1 2005/02/26 01:47:35 jrecker Exp $
@
@ Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
@
@ The contents of this file, and the files included with this file,
@ are subject to the current version of the RealNetworks Public
@ Source License (the "RPSL") available at
@ http://www.helixcommunity.org/content/rpsl unless you have licensed
@ the file under the current version of the RealNetworks Community
@ Source License (the "RCSL") available at
@ http://www.helixcommunity.org/content/rcsl, in which case the RCSL
@ will apply. You may also obtain the license terms directly from
@ RealNetworks. You may not use this file except in compliance with
@ the RPSL or, if you have a valid RCSL with RealNetworks applicable
@ to this file, the RCSL. Please see the applicable RPSL or RCSL for
@ the rights, obligations and limitations governing use of the
@ contents of the file.
@
@ This file is part of the Helix DNA Technology. RealNetworks is the
@ developer and/or licensor of the Original Code and owns the
@ copyrights in the portions it created.
@
@ This file, and the files included with this file, is distributed
@ and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
@ KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
@ ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
@ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
@ ENJOYMENT OR NON-INFRINGEMENT.
@
@ Technology Compatibility Kit Test Suite(s) Location:
@ http://www.helixcommunity.org/content/tck
@
@ Contributor(s):
@
@ ***** END LICENSE BLOCK *****
.text
.code 32
.align
CPTR .req r0
DELAY .req r1
DIDX .req r2
OUTBUF .req r3
K .req r4
DOFF0 .req r5
DOFF1 .req r6
SUMLO .req r7
SUMHI .req r8
NCHANS .req r9
COEF0 .req r10
DVAL0 .req r11
COEF1 .req r12
DVAL1 .req r14
.set FBITS_OUT_QMFS, (14 - (1+2+3+2+1) - (2+3+2) + 6 - 1)
.set RND_VAL, (1 << (FBITS_OUT_QMFS - 1))
@ void QMFSynthesisConv(int *cPtr, int *delay, int dIdx, short *outbuf, int nChans);
@ see comments in sbrqmf.c
.global raac_QMFSynthesisConv
raac_QMFSynthesisConv:
stmfd sp!, {r4-r11, r14}
ldr NCHANS, [r13, #4*9] @ we saved 9 registers on stack
mov DOFF0, DIDX, lsl #7 @ dOff0 = 128*dIdx
subs DOFF1, DOFF0, #1 @ dOff1 = dOff0 - 1
addlt DOFF1, DOFF1, #1280 @ if (dOff1 < 0) then dOff1 += 1280
mov K, #64
SRC_Loop_Start:
ldr COEF0, [CPTR], #4
ldr COEF1, [CPTR], #4
ldr DVAL0, [DELAY, DOFF0, lsl #2]
ldr DVAL1, [DELAY, DOFF1, lsl #2]
smull SUMLO, SUMHI, COEF0, DVAL0
subs DOFF0, DOFF0, #256
addlt DOFF0, DOFF0, #1280
smlal SUMLO, SUMHI, COEF1, DVAL1
subs DOFF1, DOFF1, #256
addlt DOFF1, DOFF1, #1280
ldr COEF0, [CPTR], #4
ldr COEF1, [CPTR], #4
ldr DVAL0, [DELAY, DOFF0, lsl #2]
ldr DVAL1, [DELAY, DOFF1, lsl #2]
smlal SUMLO, SUMHI, COEF0, DVAL0
subs DOFF0, DOFF0, #256
addlt DOFF0, DOFF0, #1280
smlal SUMLO, SUMHI, COEF1, DVAL1
subs DOFF1, DOFF1, #256
addlt DOFF1, DOFF1, #1280
ldr COEF0, [CPTR], #4
ldr COEF1, [CPTR], #4
ldr DVAL0, [DELAY, DOFF0, lsl #2]
ldr DVAL1, [DELAY, DOFF1, lsl #2]
smlal SUMLO, SUMHI, COEF0, DVAL0
subs DOFF0, DOFF0, #256
addlt DOFF0, DOFF0, #1280
smlal SUMLO, SUMHI, COEF1, DVAL1
subs DOFF1, DOFF1, #256
addlt DOFF1, DOFF1, #1280
ldr COEF0, [CPTR], #4
ldr COEF1, [CPTR], #4
ldr DVAL0, [DELAY, DOFF0, lsl #2]
ldr DVAL1, [DELAY, DOFF1, lsl #2]
smlal SUMLO, SUMHI, COEF0, DVAL0
subs DOFF0, DOFF0, #256
addlt DOFF0, DOFF0, #1280
smlal SUMLO, SUMHI, COEF1, DVAL1
subs DOFF1, DOFF1, #256
addlt DOFF1, DOFF1, #1280
ldr COEF0, [CPTR], #4
ldr COEF1, [CPTR], #4
ldr DVAL0, [DELAY, DOFF0, lsl #2]
ldr DVAL1, [DELAY, DOFF1, lsl #2]
smlal SUMLO, SUMHI, COEF0, DVAL0
subs DOFF0, DOFF0, #256
addlt DOFF0, DOFF0, #1280
smlal SUMLO, SUMHI, COEF1, DVAL1
subs DOFF1, DOFF1, #256
addlt DOFF1, DOFF1, #1280
add DOFF0, DOFF0, #1
sub DOFF1, DOFF1, #1
add SUMHI, SUMHI, #RND_VAL
mov SUMHI, SUMHI, asr #FBITS_OUT_QMFS
mov SUMLO, SUMHI, asr #31
cmp SUMLO, SUMHI, asr #15
eorne SUMHI, SUMLO, #0x7f00 @ takes 2 instructions for immediate value of 0x7fffffff
eorne SUMHI, SUMHI, #0x00ff
strh SUMHI, [OUTBUF, #0]
add OUTBUF, OUTBUF, NCHANS, lsl #1
subs K, K, #1
bne SRC_Loop_Start
ldmfd sp!, {r4-r11, pc}
.end
|
1137519-player
|
aac/armgcc/sbrqmfsk.s
|
Motorola 68K Assembly
|
lgpl
| 5,187
|
@ ***** BEGIN LICENSE BLOCK *****
@ Source last modified: $Id: sbrcov.s,v 1.1 2005/02/26 01:47:35 jrecker Exp $
@
@ Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
@
@ The contents of this file, and the files included with this file,
@ are subject to the current version of the RealNetworks Public
@ Source License (the "RPSL") available at
@ http://www.helixcommunity.org/content/rpsl unless you have licensed
@ the file under the current version of the RealNetworks Community
@ Source License (the "RCSL") available at
@ http://www.helixcommunity.org/content/rcsl, in which case the RCSL
@ will apply. You may also obtain the license terms directly from
@ RealNetworks. You may not use this file except in compliance with
@ the RPSL or, if you have a valid RCSL with RealNetworks applicable
@ to this file, the RCSL. Please see the applicable RPSL or RCSL for
@ the rights, obligations and limitations governing use of the
@ contents of the file.
@
@ This file is part of the Helix DNA Technology. RealNetworks is the
@ developer and/or licensor of the Original Code and owns the
@ copyrights in the portions it created.
@
@ This file, and the files included with this file, is distributed
@ and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
@ KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
@ ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
@ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
@ ENJOYMENT OR NON-INFRINGEMENT.
@
@ Technology Compatibility Kit Test Suite(s) Location:
@ http://www.helixcommunity.org/content/tck
@
@ Contributor(s):
@
@ ***** END LICENSE BLOCK *****
.text
.code 32
.align
@ commmon
XBUF .req r0
ACCBUF .req r1
NCT .req r2
X0RE .req r3
X0IM .req r4
X1RE .req r5
X1IM .req r6
X0IMNEG .req r14
@ CVKernel1 - in loop
P01RELO .req r7
P01REHI .req r8
P01IMLO .req r9
P01IMHI .req r10
P11RELO .req r11
P11REHI .req r12
@ CVKernel1 - out of loop
P12RELO .req r7
P12REHI .req r8
P12IMLO .req r9
P12IMHI .req r10
P22RELO .req r11
P22REHI .req r12
@ void CVKernel1(int *XBuf, int *accBuf)
@ see comments in sbrhfgen.c
.global raac_CVKernel1
raac_CVKernel1:
stmfd sp!, {r4-r11, r14}
ldr X0RE, [XBUF], #4*(1)
ldr X0IM, [XBUF], #4*(2*64-1)
ldr X1RE, [XBUF], #4*(1)
ldr X1IM, [XBUF], #4*(2*64-1)
rsb X0IMNEG, X0IM, #0
smull P12RELO, P12REHI, X1RE, X0RE
smlal P12RELO, P12REHI, X1IM, X0IM
smull P12IMLO, P12IMHI, X0RE, X1IM
smlal P12IMLO, P12IMHI, X0IMNEG, X1RE
smull P22RELO, P22REHI, X0RE, X0RE
smlal P22RELO, P22REHI, X0IM, X0IM
add NCT, ACCBUF, #(4*6)
stmia NCT, {P12RELO-P22REHI}
mov P01RELO, #0
mov P01REHI, #0
mov P01IMLO, #0
mov P01IMHI, #0
mov P11RELO, #0
mov P11REHI, #0
mov NCT, #(16*2 + 6)
CV1_Loop_Start:
mov X0RE, X1RE
ldr X1RE, [XBUF], #4*(1)
mov X0IM, X1IM
ldr X1IM, [XBUF], #4*(2*64-1)
rsb X0IMNEG, X0IM, #0
smlal P01RELO, P01REHI, X1RE, X0RE
smlal P01RELO, P01REHI, X1IM, X0IM
smlal P01IMLO, P01IMHI, X0RE, X1IM
smlal P01IMLO, P01IMHI, X0IMNEG, X1RE
smlal P11RELO, P11REHI, X0RE, X0RE
smlal P11RELO, P11REHI, X0IM, X0IM
subs NCT, NCT, #1
bne CV1_Loop_Start
stmia ACCBUF, {P01RELO-P11REHI}
ldr XBUF, [ACCBUF, #4*(6)] @ load P12RELO into temp buf
ldr NCT, [ACCBUF, #4*(7)] @ load P12REHI into temp buf
rsb X0RE, X0RE, #0
adds P12RELO, XBUF, P01RELO @ P12RELO and P01RELO are same reg
adc P12REHI, NCT, P01REHI @ P12REHI and P01REHI are same reg
smlal P12RELO, P12REHI, X1RE, X0RE
smlal P12RELO, P12REHI, X1IM, X0IMNEG
ldr XBUF, [ACCBUF, #4*(8)] @ load P12IMLO into temp buf
ldr NCT, [ACCBUF, #4*(9)] @ load P12IMHI into temp buf
adds P12IMLO, XBUF, P01IMLO @ P12IMLO and P01IMLO are same reg
adc P12IMHI, NCT, P01IMHI @ P12IMHI and P01IMHI are same reg
smlal P12IMLO, P12IMHI, X0RE, X1IM
smlal P12IMLO, P12IMHI, X0IM, X1RE
ldr XBUF, [ACCBUF, #4*(10)] @ load P22RELO into temp buf
ldr NCT, [ACCBUF, #4*(11)] @ load P22REHI into temp buf
adds P22RELO, XBUF, P11RELO @ P22RELO and P11RELO are same reg
adc P22REHI, NCT, P11REHI @ P22REHI and P11REHI are same reg
rsb XBUF, X0RE, #0
smlal P22RELO, P22REHI, X0RE, XBUF
rsb NCT, X0IM, #0
smlal P22RELO, P22REHI, X0IM, NCT
add ACCBUF, ACCBUF, #(4*6)
stmia ACCBUF, {P12RELO-P22REHI}
ldmfd sp!, {r4-r11, pc}
@ CVKernel2
P02RELO .req r7
P02REHI .req r8
P02IMLO .req r9
P02IMHI .req r10
X2RE .req r11
X2IM .req r12
@ void CVKernel2(int *XBuf, int *accBuf)
@ see comments in sbrhfgen.c
.global raac_CVKernel2
raac_CVKernel2:
stmfd sp!, {r4-r11, r14}
mov P02RELO, #0
mov P02REHI, #0
mov P02IMLO, #0
mov P02IMHI, #0
ldr X0RE, [XBUF], #4*(1)
ldr X0IM, [XBUF], #4*(2*64-1)
ldr X1RE, [XBUF], #4*(1)
ldr X1IM, [XBUF], #4*(2*64-1)
mov NCT, #(16*2 + 6)
CV2_Loop_Start:
ldr X2RE, [XBUF], #4*(1)
ldr X2IM, [XBUF], #4*(2*64-1)
rsb X0IMNEG, X0IM, #0
smlal P02RELO, P02REHI, X2RE, X0RE
smlal P02RELO, P02REHI, X2IM, X0IM
smlal P02IMLO, P02IMHI, X0RE, X2IM
smlal P02IMLO, P02IMHI, X0IMNEG, X2RE
mov X0RE, X1RE
mov X0IM, X1IM
mov X1RE, X2RE
mov X1IM, X2IM
subs NCT, NCT, #1
bne CV2_Loop_Start
stmia ACCBUF, {P02RELO-P02IMHI}
ldmfd sp!, {r4-r11, pc}
.end
|
1137519-player
|
aac/armgcc/sbrcov.s
|
Unix Assembly
|
lgpl
| 6,315
|
@ ***** BEGIN LICENSE BLOCK *****
@ Source last modified: $Id: sbrqmfak.s,v 1.1 2005/02/26 01:47:35 jrecker Exp $
@
@ Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
@
@ The contents of this file, and the files included with this file,
@ are subject to the current version of the RealNetworks Public
@ Source License (the "RPSL") available at
@ http://www.helixcommunity.org/content/rpsl unless you have licensed
@ the file under the current version of the RealNetworks Community
@ Source License (the "RCSL") available at
@ http://www.helixcommunity.org/content/rcsl, in which case the RCSL
@ will apply. You may also obtain the license terms directly from
@ RealNetworks. You may not use this file except in compliance with
@ the RPSL or, if you have a valid RCSL with RealNetworks applicable
@ to this file, the RCSL. Please see the applicable RPSL or RCSL for
@ the rights, obligations and limitations governing use of the
@ contents of the file.
@
@ This file is part of the Helix DNA Technology. RealNetworks is the
@ developer and/or licensor of the Original Code and owns the
@ copyrights in the portions it created.
@
@ This file, and the files included with this file, is distributed
@ and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
@ KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
@ ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
@ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
@ ENJOYMENT OR NON-INFRINGEMENT.
@
@ Technology Compatibility Kit Test Suite(s) Location:
@ http://www.helixcommunity.org/content/tck
@
@ Contributor(s):
@
@ ***** END LICENSE BLOCK *****
.text
.code 32
.align
CPTR0 .req r0
DELAY .req r1
DIDX .req r2
UBUF .req r3
CPTR1 .req r4
K .req r5
DOFF .req r6
ULO0 .req r7
UHI0 .req r8
ULO1 .req r9
UHI1 .req r10
COEF0 .req r11
DVAL0 .req r12
COEF1 .req r14
DVAL1 .req r2 @ overlay with DIDX
@void QMFAnalysisConv(int *cTab, int *delay, int dIdx, int *uBuf)
@ see comments in sbrqmf.c
.global raac_QMFAnalysisConv
raac_QMFAnalysisConv:
stmfd sp!, {r4-r11, r14}
mov DOFF, DIDX, lsl #5 @ dOff0 = 32*dIdx
add DOFF, DOFF, #31 @ dOff0 = 32*dIdx + 31
add CPTR1, CPTR0, #4*(164) @ cPtr1 = cPtr0 + 164
@ special first pass (flip sign for cTab[384], cTab[512])
ldr COEF0, [CPTR0], #4
ldr COEF1, [CPTR0], #4
ldr DVAL0, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
ldr DVAL1, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
smull ULO0, UHI0, COEF0, DVAL0
smull ULO1, UHI1, COEF1, DVAL1
ldr COEF0, [CPTR0], #4
ldr COEF1, [CPTR0], #4
ldr DVAL0, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
ldr DVAL1, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
smlal ULO0, UHI0, COEF0, DVAL0
smlal ULO1, UHI1, COEF1, DVAL1
ldr COEF0, [CPTR0], #4
ldr COEF1, [CPTR1], #-4
ldr DVAL0, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
ldr DVAL1, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
smlal ULO0, UHI0, COEF0, DVAL0
smlal ULO1, UHI1, COEF1, DVAL1
ldr COEF0, [CPTR1], #-4
ldr COEF1, [CPTR1], #-4
ldr DVAL0, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
ldr DVAL1, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
rsb COEF0, COEF0, #0
smlal ULO0, UHI0, COEF0, DVAL0
smlal ULO1, UHI1, COEF1, DVAL1
ldr COEF0, [CPTR1], #-4
ldr COEF1, [CPTR1], #-4
ldr DVAL0, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
ldr DVAL1, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
rsb COEF0, COEF0, #0
smlal ULO0, UHI0, COEF0, DVAL0
smlal ULO1, UHI1, COEF1, DVAL1
str UHI1, [UBUF, #4*32]
str UHI0, [UBUF], #4
sub DOFF, DOFF, #1
mov K, #31
SRC_Loop_Start:
ldr COEF0, [CPTR0], #4
ldr COEF1, [CPTR0], #4
ldr DVAL0, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
ldr DVAL1, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
smull ULO0, UHI0, COEF0, DVAL0
smull ULO1, UHI1, COEF1, DVAL1
ldr COEF0, [CPTR0], #4
ldr COEF1, [CPTR0], #4
ldr DVAL0, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
ldr DVAL1, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
smlal ULO0, UHI0, COEF0, DVAL0
smlal ULO1, UHI1, COEF1, DVAL1
ldr COEF0, [CPTR0], #4
ldr COEF1, [CPTR1], #-4
ldr DVAL0, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
ldr DVAL1, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
smlal ULO0, UHI0, COEF0, DVAL0
smlal ULO1, UHI1, COEF1, DVAL1
ldr COEF0, [CPTR1], #-4
ldr COEF1, [CPTR1], #-4
ldr DVAL0, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
ldr DVAL1, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
smlal ULO0, UHI0, COEF0, DVAL0
smlal ULO1, UHI1, COEF1, DVAL1
ldr COEF0, [CPTR1], #-4
ldr COEF1, [CPTR1], #-4
ldr DVAL0, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
ldr DVAL1, [DELAY, DOFF, lsl #2]
subs DOFF, DOFF, #32
addlt DOFF, DOFF, #320
smlal ULO0, UHI0, COEF0, DVAL0
smlal ULO1, UHI1, COEF1, DVAL1
str UHI1, [UBUF, #4*32]
str UHI0, [UBUF], #4
sub DOFF, DOFF, #1
subs K, K, #1
bne SRC_Loop_Start
ldmfd sp!, {r4-r11, pc}
.end
|
1137519-player
|
aac/armgcc/sbrqmfak.s
|
Unix Assembly
|
lgpl
| 6,695
|
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: sbr.h,v 1.2 2005/05/20 18:05:41 jrecker Exp $
*
* Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point HE-AAC decoder
* Jon Recker (jrecker@real.com)
* February 2005
*
* sbr.h - definitions of platform-specific SBR data structures, functions, and tables
**************************************************************************************/
#ifndef _SBR_H
#define _SBR_H
#include "aaccommon.h"
#include "bitstream.h"
#ifndef ASSERT
#if defined(_WIN32) && defined(_M_IX86) && (defined (_DEBUG) || defined (REL_ENABLE_ASSERTS))
#define ASSERT(x) if (!(x)) __asm int 3;
#else
#define ASSERT(x) /* do nothing */
#endif
#endif
#ifndef MAX
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
#ifndef MIN
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
#define NUM_TIME_SLOTS 16
#define SAMPLES_PER_SLOT 2 /* RATE in spec */
#define NUM_SAMPLE_RATES_SBR 9 /* downsampled (single-rate) mode unsupported, so only use Fs_sbr >= 16 kHz */
#define MAX_NUM_ENV 5
#define MAX_NUM_NOISE_FLOORS 2
#define MAX_NUM_NOISE_FLOOR_BANDS 5 /* max Nq, see 4.6.18.3.6 */
#define MAX_NUM_PATCHES 5
#define MAX_NUM_SMOOTH_COEFS 5
#define HF_GEN 8
#define HF_ADJ 2
#define MAX_QMF_BANDS 48 /* max QMF subbands covered by SBR (4.6.18.3.6) */
#define FBITS_IN_QMFA 14
#define FBITS_LOST_QMFA (1 + 2 + 3 + 2 + 1) /* 1 from cTab, 2 in premul, 3 in FFT, 2 in postmul, 1 for implicit scaling by 2.0 */
#define FBITS_OUT_QMFA (FBITS_IN_QMFA - FBITS_LOST_QMFA)
#define MIN_GBITS_IN_QMFS 2
#define FBITS_IN_QMFS FBITS_OUT_QMFA
#define FBITS_LOST_DCT4_64 (2 + 3 + 2) /* 2 in premul, 3 in FFT, 2 in postmul */
#define FBITS_OUT_DQ_ENV 29 /* dequantized env scalefactors are Q(29 - envDataDequantScale) */
#define FBITS_OUT_DQ_NOISE 24 /* range of Q_orig = [2^-24, 2^6] */
#define NOISE_FLOOR_OFFSET 6
/* see comments in ApplyBoost() */
#define FBITS_GLIM_BOOST 24
#define FBITS_QLIM_BOOST 14
#define MAX_HUFF_BITS 20
#define NUM_QMF_DELAY_BUFS 10
#define DELAY_SAMPS_QMFA (NUM_QMF_DELAY_BUFS * 32)
#define DELAY_SAMPS_QMFS (NUM_QMF_DELAY_BUFS * 128)
/* additional external symbols to name-mangle for static linking */
#define FFT32C STATNAME(FFT32C)
#define CalcFreqTables STATNAME(CalcFreqTables)
#define AdjustHighFreq STATNAME(AdjustHighFreq)
#define GenerateHighFreq STATNAME(GenerateHighFreq)
#define DecodeSBREnvelope STATNAME(DecodeSBREnvelope)
#define DecodeSBRNoise STATNAME(DecodeSBRNoise)
#define UncoupleSBREnvelope STATNAME(UncoupleSBREnvelope)
#define UncoupleSBRNoise STATNAME(UncoupleSBRNoise)
#define InvRNormalized STATNAME(InvRNormalized)
#define RatioPowInv STATNAME(RatioPowInv)
#define SqrtFix STATNAME(SqrtFix)
#define QMFAnalysis STATNAME(QMFAnalysis)
#define QMFSynthesis STATNAME(QMFSynthesis)
#define GetSampRateIdx STATNAME(GetSampRateIdx)
#define UnpackSBRHeader STATNAME(UnpackSBRHeader)
#define UnpackSBRSingleChannel STATNAME(UnpackSBRSingleChannel)
#define UnpackSBRChannelPair STATNAME(UnpackSBRChannelPair)
/* asm functions */
#define CVKernel1 STATNAME(CVKernel1)
#define CVKernel2 STATNAME(CVKernel2)
#define QMFAnalysisConv STATNAME(QMFAnalysisConv)
#define QMFSynthesisConv STATNAME(QMFSynthesisConv)
#define k0Tab STATNAME(k0Tab)
#define k2Tab STATNAME(k2Tab)
#define goalSBTab STATNAME(goalSBTab)
#define huffTabSBR STATNAME(huffTabSBR)
#define huffTabSBRInfo STATNAME(huffTabSBRInfo)
#define log2Tab STATNAME(log2Tab)
#define noiseTab STATNAME(noiseTab)
#define cTabA STATNAME(cTabA)
#define cTabS STATNAME(cTabS)
/* do y <<= n, clipping to range [-2^30, 2^30 - 1] (i.e. output has one guard bit) */
#define CLIP_2N_SHIFT30(y, n) { \
int sign = (y) >> 31; \
if (sign != (y) >> (30 - (n))) { \
(y) = sign ^ (0x3fffffff); \
} else { \
(y) = (y) << (n); \
} \
}
#define CLIP_2N(y, n) { \
int sign = (y) >> 31; \
if (sign != ((y) >> (n))) { \
(y) = sign ^ ((1 << (n)) - 1); \
} \
}
enum {
SBR_GRID_FIXFIX = 0,
SBR_GRID_FIXVAR = 1,
SBR_GRID_VARFIX = 2,
SBR_GRID_VARVAR = 3
};
enum {
HuffTabSBR_tEnv15 = 0,
HuffTabSBR_fEnv15 = 1,
HuffTabSBR_tEnv15b = 2,
HuffTabSBR_fEnv15b = 3,
HuffTabSBR_tEnv30 = 4,
HuffTabSBR_fEnv30 = 5,
HuffTabSBR_tEnv30b = 6,
HuffTabSBR_fEnv30b = 7,
HuffTabSBR_tNoise30 = 8,
HuffTabSBR_fNoise30 = 5,
HuffTabSBR_tNoise30b = 9,
HuffTabSBR_fNoise30b = 7
};
typedef struct _HuffInfo {
int maxBits; /* number of bits in longest codeword */
unsigned char count[MAX_HUFF_BITS]; /* count[i] = number of codes with length i+1 bits */
int offset; /* offset into symbol table */
} HuffInfo;
/* need one SBRHeader per element (SCE/CPE), updated only on new header */
typedef struct _SBRHeader {
int count;
unsigned char ampRes;
unsigned char startFreq;
unsigned char stopFreq;
unsigned char crossOverBand;
unsigned char resBitsHdr;
unsigned char hdrExtra1;
unsigned char hdrExtra2;
unsigned char freqScale;
unsigned char alterScale;
unsigned char noiseBands;
unsigned char limiterBands;
unsigned char limiterGains;
unsigned char interpFreq;
unsigned char smoothMode;
} SBRHeader;
/* need one SBRGrid per channel, updated every frame */
typedef struct _SBRGrid {
unsigned char frameClass;
unsigned char ampResFrame;
unsigned char pointer;
unsigned char numEnv; /* L_E */
unsigned char envTimeBorder[MAX_NUM_ENV+1]; /* t_E */
unsigned char freqRes[MAX_NUM_ENV]; /* r */
unsigned char numNoiseFloors; /* L_Q */
unsigned char noiseTimeBorder[MAX_NUM_NOISE_FLOORS+1]; /* t_Q */
unsigned char numEnvPrev;
unsigned char numNoiseFloorsPrev;
unsigned char freqResPrev;
} SBRGrid;
/* need one SBRFreq per element (SCE/CPE/LFE), updated only on header reset */
typedef struct _SBRFreq {
int kStart; /* k_x */
int nMaster;
int nHigh;
int nLow;
int nLimiter; /* N_l */
int numQMFBands; /* M */
int numNoiseFloorBands; /* Nq */
int kStartPrev;
int numQMFBandsPrev;
unsigned char freqMaster[MAX_QMF_BANDS + 1]; /* not necessary to save this after derived tables are generated */
unsigned char freqHigh[MAX_QMF_BANDS + 1];
unsigned char freqLow[MAX_QMF_BANDS / 2 + 1]; /* nLow = nHigh - (nHigh >> 1) */
unsigned char freqNoise[MAX_NUM_NOISE_FLOOR_BANDS+1];
unsigned char freqLimiter[MAX_QMF_BANDS / 2 + MAX_NUM_PATCHES]; /* max (intermediate) size = nLow + numPatches - 1 */
unsigned char numPatches;
unsigned char patchNumSubbands[MAX_NUM_PATCHES + 1];
unsigned char patchStartSubband[MAX_NUM_PATCHES + 1];
} SBRFreq;
typedef struct _SBRChan {
int reset;
unsigned char deltaFlagEnv[MAX_NUM_ENV];
unsigned char deltaFlagNoise[MAX_NUM_NOISE_FLOORS];
signed char envDataQuant[MAX_NUM_ENV][MAX_QMF_BANDS]; /* range = [0, 127] */
signed char noiseDataQuant[MAX_NUM_NOISE_FLOORS][MAX_NUM_NOISE_FLOOR_BANDS];
unsigned char invfMode[2][MAX_NUM_NOISE_FLOOR_BANDS]; /* invfMode[0/1][band] = prev/curr */
int chirpFact[MAX_NUM_NOISE_FLOOR_BANDS]; /* bwArray */
unsigned char addHarmonicFlag[2]; /* addHarmonicFlag[0/1] = prev/curr */
unsigned char addHarmonic[2][64]; /* addHarmonic[0/1][band] = prev/curr */
int gbMask[2]; /* gbMask[0/1] = XBuf[0-31]/XBuf[32-39] */
signed char laPrev;
int noiseTabIndex;
int sinIndex;
int gainNoiseIndex;
int gTemp[MAX_NUM_SMOOTH_COEFS][MAX_QMF_BANDS];
int qTemp[MAX_NUM_SMOOTH_COEFS][MAX_QMF_BANDS];
} SBRChan;
typedef struct _PSInfoSBR {
/* save for entire file */
int frameCount;
int sampRateIdx;
/* state info that must be saved for each channel */
SBRHeader sbrHdr[AAC_MAX_NCHANS];
SBRGrid sbrGrid[AAC_MAX_NCHANS];
SBRFreq sbrFreq[AAC_MAX_NCHANS];
SBRChan sbrChan[AAC_MAX_NCHANS];
/* temp variables, no need to save between blocks */
unsigned char dataExtra;
unsigned char resBitsData;
unsigned char extendedDataPresent;
int extendedDataSize;
signed char envDataDequantScale[MAX_NCHANS_ELEM][MAX_NUM_ENV];
int envDataDequant[MAX_NCHANS_ELEM][MAX_NUM_ENV][MAX_QMF_BANDS];
int noiseDataDequant[MAX_NCHANS_ELEM][MAX_NUM_NOISE_FLOORS][MAX_NUM_NOISE_FLOOR_BANDS];
int eCurr[MAX_QMF_BANDS];
unsigned char eCurrExp[MAX_QMF_BANDS];
unsigned char eCurrExpMax;
signed char la;
int crcCheckWord;
int couplingFlag;
int envBand;
int eOMGainMax;
int gainMax;
int gainMaxFBits;
int noiseFloorBand;
int qp1Inv;
int qqp1Inv;
int sMapped;
int sBand;
int highBand;
int sumEOrigMapped;
int sumECurrGLim;
int sumSM;
int sumQM;
int gLimBoost[MAX_QMF_BANDS];
int qmLimBoost[MAX_QMF_BANDS];
int smBoost[MAX_QMF_BANDS];
int smBuf[MAX_QMF_BANDS];
int qmLimBuf[MAX_QMF_BANDS];
int gLimBuf[MAX_QMF_BANDS];
int gLimFbits[MAX_QMF_BANDS];
int gFiltLast[MAX_QMF_BANDS];
int qFiltLast[MAX_QMF_BANDS];
/* large buffers */
int delayIdxQMFA[AAC_MAX_NCHANS];
int delayQMFA[AAC_MAX_NCHANS][DELAY_SAMPS_QMFA];
int delayIdxQMFS[AAC_MAX_NCHANS];
int delayQMFS[AAC_MAX_NCHANS][DELAY_SAMPS_QMFS];
int XBufDelay[AAC_MAX_NCHANS][HF_GEN][64][2];
int XBuf[32+8][64][2];
} PSInfoSBR;
/* sbrfft.c */
void FFT32C(int *x);
/* sbrfreq.c */
int CalcFreqTables(SBRHeader *sbrHdr, SBRFreq *sbrFreq, int sampRateIdx);
/* sbrhfadj.c */
void AdjustHighFreq(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch);
/* sbrhfgen.c */
void GenerateHighFreq(PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch);
/* sbrhuff.c */
void DecodeSBREnvelope(BitStreamInfo *bsi, PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch);
void DecodeSBRNoise(BitStreamInfo *bsi, PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch);
void UncoupleSBREnvelope(PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChanR);
void UncoupleSBRNoise(PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChanR);
/* sbrmath.c */
int InvRNormalized(int r);
int RatioPowInv(int a, int b, int c);
int SqrtFix(int x, int fBitsIn, int *fBitsOut);
/* sbrqmf.c */
int QMFAnalysis(int *inbuf, int *delay, int *XBuf, int fBitsIn, int *delayIdx, int qmfaBands);
void QMFSynthesis(int *inbuf, int *delay, int *delayIdx, int qmfsBands, short *outbuf, int nChans);
/* sbrside.c */
int GetSampRateIdx(int sampRate);
int UnpackSBRHeader(BitStreamInfo *bsi, SBRHeader *sbrHdr);
void UnpackSBRSingleChannel(BitStreamInfo *bsi, PSInfoSBR *psi, int chOut);
void UnpackSBRChannelPair(BitStreamInfo *bsi, PSInfoSBR *psi, int chOut);
/* sbrtabs.c */
extern const unsigned char k0Tab[NUM_SAMPLE_RATES_SBR][16];
extern const unsigned char k2Tab[NUM_SAMPLE_RATES_SBR][14];
extern const unsigned char goalSBTab[NUM_SAMPLE_RATES_SBR];
extern const HuffInfo huffTabSBRInfo[10];
extern const signed short huffTabSBR[604];
extern const int log2Tab[65];
extern const int noiseTab[512*2];
extern const int cTabA[165];
extern const int cTabS[640];
#endif /* _SBR_H */
|
1137519-player
|
aac/sbr.h
|
C
|
lgpl
| 14,039
|
/*
* fft.c
*
* Created on: 2013/02/23
* Author: Tonsuke
*/
#include "fft.h"
#include "settings.h"
/*
const static uint16_t color_bar[] = {red, yellow, blue, blue, green, green, red, red, yellow, yellow, blue, blue, green, green, red, red,\
red, yellow, blue, blue, green, green, red, red, yellow, yellow, blue, blue, green, green, red, red};
*/
//const static uint16_t skyblue_bar[] = {0xef7d, 0xe75d, 0xe75d, 0xdf5d, 0xdf5d, 0xd73d, 0xd73d, 0xcf3d, 0xcf3d, 0xc71d, 0xc71d, 0xc71d, 0xbf1d, 0xbf1d, 0xb6fd, 0xb6fd, 0xaefe, 0xaefe, 0xa6de, 0xa6de, 0x9ede, 0x9ede, 0x9ede, 0x96be, 0x96be, 0x8ebe, 0x8ebe, 0x869e, 0x869e, 0x7e9e, 0x7e9e, 0x7e9f};
//const static uint16_t skyblue_bar[] = {0xef7d, 0xef3c, 0xeefb, 0xeeba, 0xee79, 0xee38, 0xedf7, 0xedb6, 0xed75, 0xed34, 0xecf3, 0xecd2, 0xec91, 0xec50, 0xec0f, 0xebce, 0xf38e, 0xf34d, 0xf30c, 0xf2cb, 0xf28a, 0xf269, 0xf228, 0xf1e7, 0xf1a6, 0xf165, 0xf124, 0xf0e3, 0xf0a2, 0xf061, 0xf020, 0xf800};
const static uint16_t color_bar[7][32] = {
{0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, // white
0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d, 0xef7d}, \
{0xef7d, 0xe75d, 0xe75d, 0xdf5d, 0xdf5d, 0xd73d, 0xd73d, 0xcf3d, 0xcf3d, 0xc71d, 0xc71d, 0xc71d, 0xbf1d, 0xbf1d, 0xb6fd, 0xb6fd, // skyblue
0xaefe, 0xaefe, 0xa6de, 0xa6de, 0x9ede, 0x9ede, 0x9ede, 0x96be, 0x96be, 0x8ebe, 0x8ebe, 0x869e, 0x869e, 0x7e9e, 0x7e9e, 0x7e9f}, \
{0xef7d, 0xef7c, 0xef7b, 0xef7a, 0xef79, 0xef78, 0xef77, 0xef76, 0xef95, 0xef94, 0xef93, 0xef92, 0xef91, 0xef90, 0xef8f, 0xef8e, // yellow
0xf7ae, 0xf7ad, 0xf7ac, 0xf7ab, 0xf7aa, 0xf7a9, 0xf7a8, 0xf7a7, 0xf7c6, 0xf7c5, 0xf7c4, 0xf7c3, 0xf7c2, 0xf7c1, 0xf7c0, 0xffe0},
{0xef7d, 0xe77c, 0xdf7b, 0xd77a, 0xcf79, 0xc778, 0xbf77, 0xb776, 0xaf95, 0xa794, 0x9f93, 0x9792, 0x8f91, 0x8790, 0x7f8f, 0x778e, // green
0x77ae, 0x6fad, 0x67ac, 0x5fab, 0x57aa, 0x4fa9, 0x47a8, 0x3fa7, 0x37c6, 0x2fc5, 0x27c4, 0x1fc3, 0x17c2, 0x0fc1, 0x07c0, 0x07e0}, \
{0xef7d, 0xef3c, 0xeefb, 0xeeba, 0xee79, 0xee38, 0xedf7, 0xedb6, 0xed75, 0xed34, 0xecf3, 0xecd2, 0xec91, 0xec50, 0xec0f, 0xebce, // red
0xf38e, 0xf34d, 0xf30c, 0xf2cb, 0xf28a, 0xf269, 0xf228, 0xf1e7, 0xf1a6, 0xf165, 0xf124, 0xf0e3, 0xf0a2, 0xf061, 0xf020, 0xf800}, \
{0xef7d, 0xe73c, 0xdefb, 0xd6ba, 0xce79, 0xc638, 0xbdf7, 0xb5b6, 0xad75, 0xa534, 0x9cf3, 0x94d2, 0x8c91, 0x8450, 0x7c0f, 0x73ce, // black
0x738e, 0x6b4d, 0x630c, 0x5acb, 0x528a, 0x4a69, 0x4228, 0x39e7, 0x31a6, 0x2965, 0x2124, 0x18e3, 0x10a2, 0x0861, 0x0020, 0x0000}, \
{red, yellow, blue, blue, green, green, red, red, yellow, yellow, blue, blue, green, green, red, red, // colorful
red, yellow, blue, blue, green, green, red, red, yellow, yellow, blue, blue, green, green, red, red}, \
};
void FFT_Init(FFT_Struct_Typedef *FFT)
{
FFT->status = arm_cfft_radix4_init_q31(&FFT->S, FFT->length, FFT->ifftFlag, FFT->bitReverseFlag);
if(settings_group.music_conf.b.prehalve){
FFT->rightShift = 21;
} else {
FFT->rightShift = 22;
}
}
void FFT_Sample(FFT_Struct_Typedef *FFT, uint32_t *pSrc)
{
int idx = 0, i;
uint32_t sample[1];
for(i = 0;i < FFT->samples;i += (FFT->samples / FFT->length)){
sample[0] = pSrc[i] ^ 0x80008000; // unsigned to signed
FFT->left_inbuf[idx] = (*(q31_t*)&sample[0] << 16) & 0xffff0000; // Real Left
FFT->left_inbuf[idx + 1] = 0; // Imag
FFT->right_inbuf[idx] = *(q31_t*)&sample[0] & 0xffff0000; // Real Right
FFT->right_inbuf[idx + 1] = 0; // Imag
idx += 2;
}
}
void FFT_Display_Left(FFT_Struct_Typedef *FFT, drawBuff_typedef *drawBuff, uint16_t color)
{
int power, i, j;
fft_analyzer_typedef fftDrawBuff;
extern settings_group_typedef settings_group;
arm_cfft_radix4_q31(&FFT->S, FFT->left_inbuf);
arm_cmplx_mag_q31(FFT->left_inbuf, FFT->outbuf, FFT->length >> 1);
memcpy(&fftDrawBuff, &drawBuff->fft_analyzer_left, sizeof(fft_analyzer_typedef));
switch(settings_group.music_conf.b.fft_bar_type){
case 0: // Solid
for(i = 0;i < FFT->length >> 1;i++){
power = __USAT(FFT->outbuf[i] >> FFT->rightShift, 5);
for(j = 0;j < power;j++){
fftDrawBuff.p[i + (31 - j) * 32] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
}
}
break;
case 1: // V Split
for(i = 0;i < FFT->length >> 1;i += 2){
power = __USAT(FFT->outbuf[i] >> FFT->rightShift, 5);
for(j = 0;j < power;j++){
fftDrawBuff.p[i + (31 - j) * 32] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
}
}
break;
case 2: // H Split
for(i = 0;i < FFT->length >> 1;i += 2){
power = FFT->outbuf[i] >> FFT->rightShift;
power += FFT->outbuf[i + 1] >> FFT->rightShift;
power = __USAT(power >>= 1, 5);
for(j = 0;j < power;j += 2){
fftDrawBuff.p[i + (31 - j) * 32] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
fftDrawBuff.p[i + (31 - j) * 32 + 1] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
}
}
break;
case 3: // Wide
for(i = 0;i < FFT->length >> 1;i += 2){
power = FFT->outbuf[i] >> FFT->rightShift;
power += FFT->outbuf[i + 1] >> FFT->rightShift;
power = __USAT(power >>= 1, 5);
for(j = 0;j < power;j++){
fftDrawBuff.p[i + (31 - j) * 32] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
fftDrawBuff.p[i + (31 - j) * 32 + 1] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
}
}
break;
default:
break;
}
LCDPutBuffToBgImg(fftDrawBuff.x, fftDrawBuff.y, \
fftDrawBuff.width, fftDrawBuff.height, fftDrawBuff.p);
}
void FFT_Display_Right(FFT_Struct_Typedef *FFT, drawBuff_typedef *drawBuff, uint16_t color)
{
int power, i, j;
fft_analyzer_typedef fftDrawBuff;
extern settings_group_typedef settings_group;
arm_cfft_radix4_q31(&FFT->S, FFT->right_inbuf);
arm_cmplx_mag_q31(FFT->right_inbuf, FFT->outbuf, FFT->length >> 1);
memcpy(&fftDrawBuff, &drawBuff->fft_analyzer_right, sizeof(fft_analyzer_typedef));
switch(settings_group.music_conf.b.fft_bar_type){
case 0: // Solid
for(i = 0;i < FFT->length >> 1;i++){
power = __USAT(FFT->outbuf[i] >> FFT->rightShift, 5);
for(j = 0;j < power;j++){
fftDrawBuff.p[i + (31 - j) * 32] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
}
}
break;
case 1: // V Split
for(i = 0;i < FFT->length >> 1;i += 2){
power = __USAT(FFT->outbuf[i] >> FFT->rightShift, 5);
for(j = 0;j < power;j++){
fftDrawBuff.p[i + (31 - j) * 32] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
}
}
break;
case 2: // H Split
for(i = 0;i < FFT->length >> 1;i += 2){
power = FFT->outbuf[i] >> FFT->rightShift;
power += FFT->outbuf[i + 1] >> FFT->rightShift;
power = __USAT(power >>= 1, 5);
for(j = 0;j < power;j += 2){
fftDrawBuff.p[i + (31 - j) * 32] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
fftDrawBuff.p[i + (31 - j) * 32 + 1] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
}
}
break;
case 3: // Wide
for(i = 0;i < FFT->length >> 1;i += 2){
power = FFT->outbuf[i] >> FFT->rightShift;
power += FFT->outbuf[i + 1] >> FFT->rightShift;
power = __USAT(power >>= 1, 5);
for(j = 0;j < power;j++){
fftDrawBuff.p[i + (31 - j) * 32] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
fftDrawBuff.p[i + (31 - j) * 32 + 1] = color_bar[settings_group.music_conf.b.fft_bar_color_idx][j];
}
}
break;
default:
break;
}
LCDPutBuffToBgImg(fftDrawBuff.x, fftDrawBuff.y, \
fftDrawBuff.width, fftDrawBuff.height, fftDrawBuff.p);
}
|
1137519-player
|
fft.c
|
C
|
lgpl
| 7,635
|
/*
* mp3.c
*
* Created on: 2012/03/25
* Author: Tonsuke
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: RCSL 1.0/RPSL 1.0
*
* Portions Copyright (c) 1995-2002 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file, are
* subject to the current version of the RealNetworks Public Source License
* Version 1.0 (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the RealNetworks Community Source License Version 1.0
* (the "RCSL") available at http://www.helixcommunity.org/content/rcsl,
* in which case the RCSL will apply. You may also obtain the license terms
* directly from RealNetworks. You may not use this file except in
* compliance with the RPSL or, if you have a valid RCSL with RealNetworks
* applicable to this file, the RCSL. Please see the applicable RPSL or
* RCSL for the rights, obligations and limitations governing use of the
* contents of the file.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the portions
* it created.
*
* This file, and the files included with this file, is distributed and made
* available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/**************************************************************************************
* Fixed-point MP3 decoder
* Jon Recker (jrecker@real.com), Ken Cooke (kenc@real.com)
* June 2003
*
* main.c - command-line test app that uses C interface to MP3 decoder
**************************************************************************************/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "mp3dec.h"
#include "mp3common.h"
#include "mp3.h"
#include "fat.h"
#include "lcd.h"
#include "pcf_font.h"
#include "sound.h"
#include "usart.h"
#include "icon.h"
#include "xpt2046.h"
#include "settings.h"
#include "board_config.h"
#include "mjpeg.h"
#include "mpool.h"
#include "arm_math.h"
#include "fft.h"
#include "fx.h"
#define READBUF_SIZE (1024 * 10) /* feel free to change this, but keep big enough for >= one frame at high bitrates */
#define MAX_ARM_FRAMES 100
#define ARMULATE_MUL_FACT 1
typedef struct {
char head_char[4];
uint32_t flags;
uint32_t frames;
}xing_struct_typedef;
typedef struct {
char id_str[3];
uint8_t verU16[2]; // must cast to (uint16_t*)
uint8_t flag;
uint8_t p_size[4];
}id3tag_head_struct_typedef;
typedef struct {
char frameID_str[4];
uint8_t p_size[4];
uint8_t flagsU16[2];
}id3v34tag_frame_struct_typedef;
typedef struct {
char frameID_str[3];
uint8_t p_size[3];
}id3v2tag_frame_struct_typedef;
typedef struct{
uint8_t encType;
uint8_t str_p[100];
uint16_t flags;
uint8_t bom[2];
size_t size;
}id3_nameTag_struct_typedef;
id3_nameTag_struct_typedef *_id3_title, *_id3_album, *_id3_artist;
MY_FILE *_file_artwork;
uint32_t unSynchSize(void *p_size){
uint32_t frameSize;
frameSize = ((uint32_t)*(uint8_t*)p_size << 21);
frameSize |= ((uint32_t)*(uint8_t*)(p_size + 1) << 14);
frameSize |= ((uint32_t)*(uint8_t*)(p_size + 2) << 7);
frameSize |= ((uint32_t)*(uint8_t*)(p_size + 3));
return frameSize;
}
static int ID3_2v34(MY_FILE *fp, uint32_t entireTagSize, uint8_t ver)
{
uint32_t frameSize;
int tagPoint;
id3v34tag_frame_struct_typedef id3tag_frame;
id3_nameTag_struct_typedef *nameTag;
uint16_t flags;
char frameID_str[5];
uint8_t *str_p;
tagPoint = sizeof(id3tag_head_struct_typedef);
debug.printf("\r\nentireTagSize:%d", entireTagSize);
while(tagPoint < entireTagSize){
my_fread((void*)&id3tag_frame, 1, sizeof(id3v34tag_frame_struct_typedef), fp);
frameID_str[4] = '\0';
strncpy(frameID_str, id3tag_frame.frameID_str, 4);
if(frameID_str[0] < 0x20 || frameID_str[0] > 0x80){ // not ascii then break
break;
}
debug.printf("\r\n\nframeID_str:%s", frameID_str);
if(ver == 4){
frameSize = unSynchSize((void*)&id3tag_frame.p_size);
} else {
frameSize = b2l((void*)&id3tag_frame.p_size, sizeof(id3tag_frame.p_size));
}
debug.printf("\r\nsize:%d", frameSize);
flags = *(uint16_t*)&id3tag_frame.flagsU16;
debug.printf("\r\nflags:%d", flags);
tagPoint += sizeof(id3v34tag_frame_struct_typedef) + frameSize;
nameTag = '\0';
if(strncmp(frameID_str, "TIT2", 4) == 0){
nameTag = _id3_title;
} else if(strncmp(frameID_str, "TALB", 4) == 0){
nameTag = _id3_album;
} else if(strncmp(frameID_str, "TPE1", 4) == 0){
nameTag = _id3_artist;
} else if(strncmp(frameID_str, "APIC", 4) == 0){
memcpy((void*)_file_artwork, (void*)fp, sizeof(MY_FILE));
return 0;
} else {
my_fseek(fp, frameSize, SEEK_CUR);
continue;
}
if(nameTag != '\0'){
my_fread((void*)&nameTag->encType, 1, 1, fp);
frameSize -= sizeof(nameTag->encType);
if(nameTag->encType){
my_fread((void*)nameTag->bom, 1, 2, fp);
frameSize -= sizeof(nameTag->bom);
}
str_p = malloc(frameSize);
my_fread(str_p, 1, frameSize, fp);
nameTag->flags = flags;
nameTag->size = (frameSize < sizeof(nameTag->str_p) - 2 ? frameSize : sizeof(nameTag->str_p) - 2);
memcpy(nameTag->str_p, str_p, nameTag->size);
nameTag->str_p[nameTag->size] = '\0';
nameTag->str_p[nameTag->size + 1] = '\0';
free((void*)str_p);
}
}
return 0;
}
static int ID3_2v2(MY_FILE *fp, uint32_t entireTagSize)
{
uint32_t frameSize;
int tagPoint;
id3v2tag_frame_struct_typedef id3tag_frame;
id3_nameTag_struct_typedef *nameTag;
char frameID_str[4];
uint8_t *str_p;
tagPoint = sizeof(id3tag_head_struct_typedef);
while(tagPoint < entireTagSize){
my_fread((void*)&id3tag_frame, 1, sizeof(id3v2tag_frame_struct_typedef), fp);
frameID_str[3] = '\0';
strncpy(frameID_str, id3tag_frame.frameID_str, 3);
if(frameID_str[0] < 0x20 || frameID_str[0] > 0x80){ // not ascii then break
break;
}
debug.printf("\r\n\nframeID_str:%s", frameID_str);
frameSize = b2l((void*)&id3tag_frame.p_size, sizeof(id3tag_frame.p_size));
debug.printf("\r\nsize:%d", frameSize);
tagPoint += sizeof(id3v2tag_frame_struct_typedef) + frameSize;
nameTag = '\0';
if(strncmp(frameID_str, "TT2", 3) == 0){
nameTag = _id3_title;
} else if(strncmp(frameID_str, "TAL", 3) == 0){
nameTag = _id3_album;
} else if(strncmp(frameID_str, "TP1", 3) == 0){
nameTag = _id3_artist;
} else if(strncmp(frameID_str, "PIC", 3) == 0){
memcpy((void*)_file_artwork, (void*)fp, sizeof(MY_FILE));
return 0;
} else {
my_fseek(fp, frameSize, SEEK_CUR);
continue;
}
if(nameTag != '\0'){
my_fread((void*)&nameTag->encType, 1, 1, fp);
frameSize -= sizeof(nameTag->encType);
if(nameTag->encType){
my_fread((void*)nameTag->bom, 1, 2, fp);
frameSize -= sizeof(nameTag->bom);
}
str_p = malloc(frameSize);
my_fread(str_p, 1, frameSize, fp);
nameTag->size = (frameSize < sizeof(nameTag->str_p) - 2 ? frameSize : sizeof(nameTag->str_p) - 2);
memcpy(nameTag->str_p, str_p, nameTag->size);
nameTag->str_p[nameTag->size] = '\0';
nameTag->str_p[nameTag->size + 1] = '\0';
free((void*)str_p);
}
}
return 0;
}
void eliminateEndSpace(uint8_t data[], uint8_t len)
{
int i, chrCnt = 0;
for(i = len;i > 0;i--){
if(data[i - 1] != '\0' && data[i - 1] != ' '){
data[i] ='\0';
break;
}
}
for(i = 0;i < len;i++){
if(data[i] != '\0') chrCnt++;
else break;
}
if(chrCnt == 0 || chrCnt == len){
data[0] = ' ';
}
}
int ID3_1v01(MY_FILE *fp){
char tag[4];
my_fseek(fp, -127, SEEK_END);
my_fread((uint8_t*)tag, 1, 3, fp);
if(strncmp(tag, "TAG", 3) == 0){
debug.printf("\r\nID3v1.x");
my_fread(_id3_title->str_p, 1, 30, fp);
my_fread(_id3_artist->str_p, 1, 30, fp);
my_fread(_id3_album->str_p, 1, 30, fp);
_id3_title->encType = _id3_artist->encType = _id3_album->encType = 0;
eliminateEndSpace(_id3_title->str_p, 30);
eliminateEndSpace(_id3_artist->str_p, 30);
eliminateEndSpace(_id3_album->str_p, 30);
}
return 0;
}
int id3tag(MY_FILE *fp){
volatile id3tag_head_struct_typedef id3tag;
uint16_t ver;
size_t size;
my_fread((void*)&id3tag, 1, sizeof(id3tag_head_struct_typedef), fp);
if(strncmp((char*)id3tag.id_str, "ID3", 3) == 0){
ver = *(uint16_t*)&id3tag.verU16;
size = unSynchSize((void*)id3tag.p_size);
debug.printf("\r\nid3tag.version:%d", ver);
debug.printf("\r\nsize:%d", size);
switch(ver){
case 2:
ID3_2v2(fp, size);
break;
case 3:
case 4:
ID3_2v34(fp, size, ver);
break;
default:
break;
}
my_fseek(fp, size + sizeof(id3tag_head_struct_typedef), SEEK_SET);
} else {
ID3_1v01(fp);
my_fseek(fp, 0, SEEK_SET);
}
return 0;
}
void UTF16BigToLittle(uint8_t *str_p, size_t size)
{
int i;
uint8_t t_char;
for(i = 0;i < size;i += sizeof(uint16_t)){
t_char = str_p[i];
str_p[i] = str_p[i + 1];
str_p[i + 1] = t_char;
}
}
uint16_t MP3PutString(uint16_t startPosX, uint16_t endPosX, uint8_t lineCnt, id3_nameTag_struct_typedef *id3_nameTag, colors color)
{
uint16_t len = 0;
if(!id3_nameTag->encType){
len = LCDPutStringSJISN(startPosX, endPosX, lineCnt, id3_nameTag->str_p, color);
} else { // UTF-16
if(id3_nameTag->bom[0] == 0xfe && id3_nameTag->bom[1] == 0xff){ // UTF-16BE
UTF16BigToLittle(id3_nameTag->str_p, id3_nameTag->size); // big to little
}
len = LCDPutStringLFN(startPosX, endPosX, lineCnt, id3_nameTag->str_p, color);
}
return len;
}
uint16_t MP3GetStringPixelLength(id3_nameTag_struct_typedef *id3_nameTag, uint16_t font_width)
{
uint16_t len = 0;
if(!id3_nameTag->encType){
len = LCDGetStringSJISPixelLength(id3_nameTag->str_p, font_width);
} else { // UTF-16
if(id3_nameTag->bom[0] == 0xfe && id3_nameTag->bom[1] == 0xff){ // UTF-16BE
UTF16BigToLittle(id3_nameTag->str_p, id3_nameTag->size); // big to little
}
len = LCDGetStringLFNPixelLength(id3_nameTag->str_p, font_width);
}
return len;
}
static int FillReadBuffer(unsigned char *readBuf, unsigned char *readPtr, int bufSize, int bytesLeft, MY_FILE *infile)
{
int nRead;
/* move last, small chunk from end of buffer to start, then fill with new data */
memmove(readBuf, readPtr, bytesLeft);
nRead = my_fread(readBuf + bytesLeft, 1, bufSize - bytesLeft, infile);
/* zero-pad to avoid finding false sync word after last frame (from old data in readBuf) */
if (nRead < bufSize - bytesLeft)
memset(readBuf + bytesLeft + nRead, 0, bufSize - bytesLeft - nRead);
return nRead;
}
int MP3FindXingWord(unsigned char *buf, int nBytes)
{
int i;
for (i = 0; i < nBytes - 3; i++) {
if ((buf[i+0] == 'X') && (buf[i+1] == 'i') && (buf[i+2] == 'n') && (buf[i+3] == 'g'))
return i;
}
return -1;
}
int MP3FindInfoWord(unsigned char *buf, int nBytes)
{
int i;
for (i = 0; i < nBytes - 3; i++) {
if ((buf[i+0] == 'I') && (buf[i+1] == 'n') && (buf[i+2] == 'f') && (buf[i+3] == 'o'))
return i;
}
return -1;
}
int PlayMP3(int id)
{
time.flags.enable = 0;
TouchPenIRQ_Disable();
TOUCH_PINIRQ_DISABLE;
touch.func = touch_empty_func;
int i;
int bytesLeft, nRead, err, offset, outOfData, eofReached;
unsigned char *readPtr;
unsigned char readBuf[READBUF_SIZE];
short *outbuf;
uint32_t *pabuf;
int totalSec, remainTotalSec, media_data_totalBytes, minute, sec;
// drawBuff_typedef *drawBuff = (drawBuff_typedef*)jFrameMem;
drawBuff_typedef dbuf, *drawBuff;
drawBuff = &dbuf;
_drawBuff = drawBuff;
int curX = 0, prevX = 0, ret = 0;
char timeStr[20];
uint8_t buf[512], hasXing = 0, hasInfo = 0;
uint32_t seekBytes, count = 0, seekBytesSyncWord = 0;
int xingSeekBytes = 0, infoSeekBytes = 0, header_offset;
float duration;
MP3FrameInfo info;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
void *putCharTmp = '\0', *putWideCharTmp = '\0';
id3_nameTag_struct_typedef title, album, artist;
_id3_title = &title, _id3_album = &album, _id3_artist = &artist;
uint16_t xTag = 110, yTag = 67, disp_limit = 300, strLen = 0, yPos;
MY_FILE *infile = '\0', file_artwork;
file_artwork.clusterOrg = 0;
_file_artwork = &file_artwork;
music_src_p.curX = &curX;
music_src_p.prevX = &prevX;
music_src_p.media_data_totalBytes = &media_data_totalBytes;
music_src_p.totalSec = &totalSec;
music_src_p.drawBuff = drawBuff;
music_src_p.fp = infile;
putCharTmp = LCD_FUNC.putChar;
putWideCharTmp = LCD_FUNC.putWideChar;
if(!pcf_font.c_loaded){
LCD_FUNC.putChar = PCFPutChar16px;
LCD_FUNC.putWideChar = PCFPutChar16px;
} else {
LCD_FUNC.putChar = C_PCFPutChar16px;
LCD_FUNC.putWideChar = C_PCFPutChar16px;
}
disp_limit = 288;
LCDPutBgImgMusic();
infile = my_fopen(id);
if(infile == '\0'){
LCDStatusStruct.waitExitKey = 0;
ret = -1;
goto EXIT_PROCESS;
}
MP3FrameInfo mp3FrameInfo;
HMP3Decoder hMP3Decoder;
memset(&mp3FrameInfo, '\0', sizeof(mp3FrameInfo));
if ( (hMP3Decoder = MP3InitDecoder()) == 0 ){
LCDStatusStruct.waitExitKey = 0;
ret = -1;
goto EXIT_PROCESS;
}
_id3_title->str_p[0] = _id3_album->str_p[0] = _id3_artist->str_p[0] = '\0';
id3tag(infile);
/*
if(_id3_title->str_p[0] != '\0'){
debug.printf("\r\n\ntitle found\r\nsize:%d\r\nencType:%d", _id3_title->size, _id3_title->encType);
debug.printf("\r\n%04x", *(uint32_t*)_id3_title->str_p);
debug.printf("\r\n%04x", *(uint32_t*)&_id3_title->str_p[4]);
}
if(_id3_album->str_p[0] != '\0'){
debug.printf("\r\n\nalbum found\r\nsize:%d\r\nencType:%d", _id3_album->size, _id3_album->encType);
debug.printf("\r\n%04x", *(uint32_t*)_id3_album->str_p);
}
if(_id3_artist->str_p[0] != '\0'){
debug.printf("\r\n\nartist found\r\nsize:%d\r\nencType:%d", _id3_artist->size, _id3_artist->encType);
debug.printf("\r\n%04x", *(uint32_t*)_id3_artist->str_p);
}
*/
if(!_id3_album->str_p[0] && !_id3_artist->str_p[0]){
yTag += 20;
} else if(!_id3_album->str_p[0] || !_id3_artist->str_p[0]){
yTag += 10;
}
if(_id3_title->str_p[0] != 0){
strLen = MP3GetStringPixelLength(_id3_title, 16);
if((xTag + strLen) < LCD_WIDTH){
disp_limit = LCD_WIDTH - 1;
} else {
disp_limit = LCD_WIDTH - 20;
yTag -= 8;
}
strLen = MP3GetStringPixelLength(_id3_album, 12);
if((xTag + strLen) > (LCD_WIDTH - 20)){
yTag -= 6;
}
LCDGotoXY(xTag + 1, yTag + 1);
MP3PutString(xTag + 1, disp_limit, 2, _id3_title, BLACK);
LCDGotoXY(xTag, yTag);
yPos = MP3PutString(xTag, disp_limit - 1, 2, _id3_title, WHITE);
yTag += 20 + yPos;
} else {
uint8_t strNameLFN[80];
if(setLFNname(strNameLFN, id, LFN_WITHOUT_EXTENSION, sizeof(strNameLFN))){
strLen = LCDGetStringLFNPixelLength(strNameLFN, 16);
if((xTag + strLen) < LCD_WIDTH){
disp_limit = LCD_WIDTH - 1;
} else {
disp_limit = LCD_WIDTH - 20;
yTag -= 10;
}
LCDGotoXY(xTag + 1, yTag + 1);
LCDPutStringLFN(xTag + 1, disp_limit, 2, strNameLFN, BLACK);
LCDGotoXY(xTag, yTag);
LCDPutStringLFN(xTag, disp_limit - 1, 2, strNameLFN, WHITE);
} else {
char strNameSFN[9];
memset(strNameSFN, '\0', sizeof(strNameSFN));
setSFNname(strNameSFN, id);
LCDGotoXY(xTag + 1, yTag + 1);
LCDPutString(strNameSFN, BLACK);
LCDGotoXY(xTag, yTag);
LCDPutString(strNameSFN, WHITE);
}
yTag += 20;
}
LCD_FUNC.putChar = putCharTmp;
LCD_FUNC.putWideChar = putWideCharTmp;
disp_limit = 300;
if(_id3_album->str_p[0] != 0){
LCDGotoXY(xTag + 1, yTag + 1);
MP3PutString(xTag + 1, LCD_WIDTH - 20, 2, _id3_album, BLACK);
LCDGotoXY(xTag, yTag);
yPos = MP3PutString(xTag, LCD_WIDTH - 21, 2, _id3_album, WHITE);
yTag += 20 + yPos;
}
if(_id3_artist->str_p[0] != 0){
LCDGotoXY(xTag + 1, yTag + 1);
MP3PutString(xTag + 1, disp_limit, 1, _id3_artist, BLACK);
LCDGotoXY(xTag, yTag);
MP3PutString(xTag, disp_limit - 1, 1, _id3_artist, WHITE);
}
dispArtWork(_file_artwork);
LCDPutIcon(0, 155, 320, 80, music_underbar_320x80, music_underbar_320x80_alpha);
bytesLeft = 0;
outOfData = 0;
eofReached = 0;
readPtr = readBuf;
nRead = 0;
seekBytes = infile->seekBytes;
while(!eofReached){
/* somewhat arbitrary trigger to refill buffer - should always be enough for a full frame */
if (bytesLeft < 2*MAINBUF_SIZE && !eofReached) {
nRead = FillReadBuffer(readBuf, readPtr, READBUF_SIZE, bytesLeft, infile);
bytesLeft += nRead;
readPtr = readBuf;
if (nRead == 0){
eofReached = 1;
break;
}
}
if((header_offset = (MP3FindXingWord(readPtr, bytesLeft))) != -1){
xingSeekBytes = header_offset + seekBytes;
hasXing = 1;
}
if((header_offset = (MP3FindInfoWord(readPtr, bytesLeft))) != -1){
infoSeekBytes = header_offset + seekBytes;
hasInfo = 1;
}
/* find start of next MP3 frame - assume EOF if no sync found */
offset = MP3FindSyncWord(readPtr, bytesLeft);
if (offset < 0) {
bytesLeft = 0;
readPtr = readBuf;
seekBytes = infile->seekBytes;
continue;
} else {
my_fseek(infile, seekBytes + offset, SEEK_SET);
my_fread(buf, 1, 4, infile);
if(UnpackFrameHeader((MP3DecInfo*)hMP3Decoder, buf) != -1){
MP3GetLastFrameInfo(hMP3Decoder, &info);
if(info.bitrate){
if(!count){
memcpy(&mp3FrameInfo, &info, sizeof(MP3FrameInfo));
debug.printf("\r\n\nmp3FrameInfo");
debug.printf("\r\nbitrate:%d", mp3FrameInfo.bitrate);
debug.printf("\r\nnChans:%d", mp3FrameInfo.nChans);
debug.printf("\r\nsamprate:%d", mp3FrameInfo.samprate);
debug.printf("\r\nbitsPerSample:%d", mp3FrameInfo.bitsPerSample);
debug.printf("\r\noutputSamps:%d", mp3FrameInfo.outputSamps);
debug.printf("\r\nlayer:%d", mp3FrameInfo.layer);
debug.printf("\r\nversion:%d", mp3FrameInfo.version);
seekBytesSyncWord = seekBytes + offset;
}
if(++count >= 2){
break;
}
}
}
bytesLeft = 0;
readPtr = readBuf;
seekBytes = infile->seekBytes;
continue;
}
}
debug.printf("\r\nseekBytesSyncWord:%d", seekBytesSyncWord);
media_data_totalBytes = infile->fileSize - seekBytesSyncWord;
debug.printf("\r\nmedia_data_totalBytes:%d", media_data_totalBytes);
if(hasXing){
debug.printf("\r\nXing");
}
if(hasInfo){
debug.printf("\r\nInfo");
}
if(hasInfo){
hasXing = 1;
xingSeekBytes = infoSeekBytes;
}
if(hasXing){
debug.printf("\r\nxingSeekBytes:%d", xingSeekBytes);
xing_struct_typedef xing_struct;
my_fseek(infile, xingSeekBytes, SEEK_SET);
my_fread((uint8_t*)&xing_struct, 1, 12, infile);
if((strncmp(xing_struct.head_char, "Xing", 4) != 0) && (strncmp(xing_struct.head_char, "Info", 4) != 0)){
goto CALC_CBR_DURATION;
}
debug.printf("\r\ncalc VBR duration");
xing_struct.flags = b2l(&xing_struct.flags, sizeof(xing_struct.flags));
if(!(xing_struct.flags & 0x0001)){ // has frames?
goto CALC_CBR_DURATION;
}
xing_struct.frames = b2l(&xing_struct.frames, sizeof(xing_struct.frames));
duration = (float)xing_struct.frames * ((float)(mp3FrameInfo.outputSamps / mp3FrameInfo.nChans) / (float)mp3FrameInfo.samprate) + 0.5f;
minute = (float)duration / 60.0f;
sec = (int)((((float)duration / 60.0f) - (float)minute) * 60.0f);
} else {
CALC_CBR_DURATION:
duration = (float)media_data_totalBytes / (float)mp3FrameInfo.bitrate * 8.0f + 0.5f;
minute = (float)duration / 60.0f;
sec = (int)((((float)duration / 60.0f) - (float)minute) * 60.0f);
}
char s[20];
SPRINTF(s, "%d/%d", id, fat.fileCnt - 1);
LCDGotoXY(21, MUSIC_INFO_POS_Y + 1);
LCDPutString(s, BLACK);
LCDGotoXY(20, MUSIC_INFO_POS_Y);
LCDPutString(s, WHITE);
if(settings_group.music_conf.b.musicinfo){
LCDGotoXY(71, MUSIC_INFO_POS_Y + 1);
LCDPutString("MP3", BLACK);
LCDGotoXY(70, MUSIC_INFO_POS_Y);
LCDPutString("MP3", WHITE);
LCDGotoXY(111, MUSIC_INFO_POS_Y + 1);
LCDPutString(mp3FrameInfo.nChans == 2 ? "Stereo" : "Mono", BLACK);
LCDGotoXY(110, MUSIC_INFO_POS_Y);
LCDPutString(mp3FrameInfo.nChans == 2 ? "Stereo" : "Mono", WHITE);
SPRINTF(s, "%dkbps", mp3FrameInfo.bitrate / 1000);
LCDGotoXY(171, MUSIC_INFO_POS_Y + 1);
LCDPutString(s, BLACK);
LCDGotoXY(170, MUSIC_INFO_POS_Y);
LCDPutString(s, WHITE);
SPRINTF(s, "%dHz", mp3FrameInfo.samprate);
LCDGotoXY(241, MUSIC_INFO_POS_Y + 1);
LCDPutString(s, BLACK);
LCDGotoXY(240, MUSIC_INFO_POS_Y);
LCDPutString(s, WHITE);
}
putCharTmp = LCD_FUNC.putChar;
putWideCharTmp = LCD_FUNC.putWideChar;
if(!pcf_font.c_loaded){
LCD_FUNC.putChar = PCFPutCharCache;
LCD_FUNC.putWideChar = PCFPutCharCache;
extern uint16_t cursorRAM[];
PCFSetGlyphCacheStartAddress((void*)cursorRAM);
PCFCachePlayTimeGlyphs(12);
} else {
LCD_FUNC.putChar = C_PCFPutChar;
LCD_FUNC.putWideChar = C_PCFPutChar;
}
debug.printf("\r\n%d:%02d", minute, sec);
totalSec = duration;
// time elapsed
drawBuff->timeElapsed.x = 14;
drawBuff->timeElapsed.y = 188;
drawBuff->timeElapsed.width = 50;
drawBuff->timeElapsed.height = 13;
LCDStoreBgImgToBuff(drawBuff->timeElapsed.x, drawBuff->timeElapsed.y, \
drawBuff->timeElapsed.width, drawBuff->timeElapsed.height, drawBuff->timeElapsed.p);
// time remain
drawBuff->timeRemain.x = totalSec < 6000 ? 268 : 260;
drawBuff->timeRemain.y = 188;
drawBuff->timeRemain.width = 50;
drawBuff->timeRemain.height = 13;
LCDStoreBgImgToBuff(drawBuff->timeRemain.x, drawBuff->timeRemain.y, \
drawBuff->timeRemain.width, drawBuff->timeRemain.height, drawBuff->timeRemain.p);
drawBuff->posision.x = 0;
drawBuff->posision.y = 168;
drawBuff->posision.width = 16;
drawBuff->posision.height = 16;
LCDStoreBgImgToBuff(drawBuff->posision.x, drawBuff->posision.y, \
drawBuff->posision.width, drawBuff->posision.height, drawBuff->posision.p);
drawBuff->navigation.x = 142;
drawBuff->navigation.y = 189;
drawBuff->navigation.width = 32;
drawBuff->navigation.height = 32;
LCDStoreBgImgToBuff(drawBuff->navigation.x, drawBuff->navigation.y, \
drawBuff->navigation.width, drawBuff->navigation.height, drawBuff->navigation.p);
drawBuff->fft_analyzer_left.x = FFT_ANALYZER_LEFT_POS_X;
drawBuff->fft_analyzer_left.y = FFT_ANALYZER_LEFT_POS_Y;
drawBuff->fft_analyzer_left.width = 32;
drawBuff->fft_analyzer_left.height = 32;
LCDStoreBgImgToBuff(drawBuff->fft_analyzer_left.x, drawBuff->fft_analyzer_left.y, \
drawBuff->fft_analyzer_left.width, drawBuff->fft_analyzer_left.height, drawBuff->fft_analyzer_left.p);
drawBuff->fft_analyzer_right.x = FFT_ANALYZER_RIGHT_POS_X;
drawBuff->fft_analyzer_right.y = FFT_ANALYZER_RIGHT_POS_Y;
drawBuff->fft_analyzer_right.width = 32;
drawBuff->fft_analyzer_right.height = 32;
LCDStoreBgImgToBuff(drawBuff->fft_analyzer_right.x, drawBuff->fft_analyzer_right.y, \
drawBuff->fft_analyzer_right.width, drawBuff->fft_analyzer_right.height, drawBuff->fft_analyzer_right.p);
drawBuff->navigation_loop.x = 277;
drawBuff->navigation_loop.y = 207;
drawBuff->navigation_loop.width = 24;
drawBuff->navigation_loop.height = 18;
LCDStoreBgImgToBuff(drawBuff->navigation_loop.x, drawBuff->navigation_loop.y, \
drawBuff->navigation_loop.width, drawBuff->navigation_loop.height, drawBuff->navigation_loop.p);
Update_Navigation_Loop_Icon(navigation_loop_mode);
LCDPutIcon(drawBuff->navigation.x, drawBuff->navigation.y, \
drawBuff->navigation.width, drawBuff->navigation.height, \
navigation_pause_patch_32x32, navigation_pause_patch_32x32_alpha);
/* Update Bass Boost Icon */
drawBuff->bass_boost.x = 10;
drawBuff->bass_boost.y = 3;
drawBuff->bass_boost.width = 24;
drawBuff->bass_boost.height = 18;
LCDStoreBgImgToBuff(drawBuff->bass_boost.x, drawBuff->bass_boost.y, \
drawBuff->bass_boost.width, drawBuff->bass_boost.height, drawBuff->bass_boost.p);
Update_Bass_Boost_Icon(bass_boost_mode);
/* Update Reverb Effect Icon */
drawBuff->reverb_effect.x = 60;
drawBuff->reverb_effect.y = 2;
drawBuff->reverb_effect.width = 24;
drawBuff->reverb_effect.height = 18;
LCDStoreBgImgToBuff(drawBuff->reverb_effect.x, drawBuff->reverb_effect.y, \
drawBuff->reverb_effect.width, drawBuff->reverb_effect.height, drawBuff->reverb_effect.p);
Update_Reverb_Effect_Icon(reverb_effect_mode);
/* Update Vocal Canceler Icon */
drawBuff->vocal_cancel.x = 107;
drawBuff->vocal_cancel.y = 5;
drawBuff->vocal_cancel.width = 24;
drawBuff->vocal_cancel.height = 18;
LCDStoreBgImgToBuff(drawBuff->vocal_cancel.x, drawBuff->vocal_cancel.y, \
drawBuff->vocal_cancel.width, drawBuff->vocal_cancel.height, drawBuff->vocal_cancel.p);
Update_Vocal_Canceler_Icon(vocal_cancel_mode);
debug.printf("\r\nsampleRate:%d", mp3FrameInfo.samprate);
my_fseek(infile, seekBytesSyncWord, SEEK_SET);
int curXprev, position_changed = 0, cnt = 0;
uint32_t noerror_cnt = 0;
float *fabuf, *fbbuf;
float *float_buf = (float*)mempool;
int fbuf_len = (MAX_NCHAN * MAX_NGRAN * MAX_NSAMP) * mp3FrameInfo.nChans;
memset(float_buf, '\0', fbuf_len * sizeof(float));
uint8_t SOUND_BUFFER[9216];
dac_intr.buff = SOUND_BUFFER;
dac_intr.bufferSize = (MAX_NCHAN * MAX_NGRAN * MAX_NSAMP) * sizeof(int16_t) * mp3FrameInfo.nChans;
int SoundDMAHalfBlocks = dac_intr.bufferSize / 2 / (sizeof(uint16_t) * 2);
int delay_buffer_filled = 0, boost = 0, loop_icon_touched = 0, loop_icon_cnt = 0;
/* variables for reverb effect
* delay_buffer is allocated in CCM.(64KB)
* Maximum length Stereo 16bit(4bytes/sample)
* 0.371s@44100Hz 0.341s@48000Hz */
delay_buffer_typedef delay_buffer;
delay_buffer.ptr = (uint32_t*)CCM_BASE;
delay_buffer.size = 65536 / sizeof(uint32_t);
delay_buffer.idx = 0;
IIR_Filter_Struct_Typedef IIR;
IIR.delay_buffer = &delay_buffer;
IIR.sbuf_size = (MAX_NCHAN * MAX_NGRAN * MAX_NSAMP) * mp3FrameInfo.nChans;
IIR.num_blocks = SoundDMAHalfBlocks;
IIR.fs = mp3FrameInfo.samprate;
IIR.number = bass_boost_mode;
boost = bass_boost_mode;
IIR_Set_Params(&IIR);
REVERB_Struct_Typedef RFX;
RFX.delay_buffer = &delay_buffer;
RFX.num_blocks = SoundDMAHalfBlocks;
RFX.fs = mp3FrameInfo.samprate;
RFX.number = reverb_effect_mode;
REVERB_Set_Prams(&RFX);
FFT_Struct_Typedef FFT;
FFT.ifftFlag = 0;
FFT.bitReverseFlag = 1;
FFT.length = 64;
FFT.samples = dac_intr.bufferSize / (sizeof(int16_t) * mp3FrameInfo.nChans) / 2;
if(mp3FrameInfo.nChans < 2){
FFT.samples >>= 1;
}
FFT_Init(&FFT);
bytesLeft = 0;
outOfData = 0;
eofReached = 0;
readPtr = readBuf;
nRead = 0;
position_changed = 0;
noerror_cnt = 0;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable the TIM1 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_TIM10_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* 1s = 1 / F_CPU(168MHz) * (167 + 1) * (99 + 1) * (9999 + 1) TIM1フレームレート計測用 */
TIM_TimeBaseInitStructure.TIM_Period = 9999;
TIM_TimeBaseInitStructure.TIM_Prescaler = 99;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = (SystemCoreClock / 1000000UL) - 1; // 168 - 1
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStructure);
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);
SOUNDInitDAC(mp3FrameInfo.samprate);
SOUNDDMAConf((void*)&DAC->DHR12LD, sizeof(int16_t) * mp3FrameInfo.nChans, sizeof(int16_t) * mp3FrameInfo.nChans);
DMA_ITConfig(DMA1_Stream1, DMA_IT_TC | DMA_IT_HT, ENABLE);
music_play.currentTotalSec = 0;
music_play.comp = 0;
music_play.update = 1;
DMA_Cmd(DMA1_Stream1, ENABLE);
TIM_Cmd(TIM1, ENABLE);
while(!eofReached && LCDStatusStruct.waitExitKey){
if(loop_icon_touched && TP_PEN_INPUT_BB == Bit_SET){
if(--loop_icon_cnt <= 0){
loop_icon_touched = 0;
}
}
if(SOUND_DMA_HALF_TRANS_BB){ // Half
SOUND_DMA_CLEAR_HALF_TRANS_BB = 1;
outbuf = (short*)dac_intr.buff;
pabuf = (uint32_t*)outbuf;
fabuf = (float*)float_buf;
fbbuf = (float*)&float_buf[fbuf_len >> 1];
} else if(SOUND_DMA_FULL_TRANS_BB){ // Full
SOUND_DMA_CLEAR_FULL_TRANS_BB = 1;
outbuf = (short*)&dac_intr.buff[dac_intr.bufferSize >> 1];
pabuf = (uint32_t*)outbuf;
fabuf = (float*)&float_buf[fbuf_len >> 1];
fbbuf = (float*)float_buf;
} else {
continue;
}
if(!position_changed && cnt++ > 5){
AUDIO_OUT_ENABLE;
}
/* somewhat arbitrary trigger to refill buffer - should always be enough for a full frame */
if (bytesLeft < 2*MAINBUF_SIZE && !eofReached) {
nRead = FillReadBuffer(readBuf, readPtr, READBUF_SIZE, bytesLeft, infile);
bytesLeft += nRead;
readPtr = readBuf;
if (nRead == 0){
eofReached = 1;
break;
}
}
if(TP_PEN_INPUT_BB == Bit_RESET && !loop_icon_touched){ // タッチパネルが押されたか?
curXprev = curX;
ret = musicPause();
if(ret >= 30){
switch(ret){
case 31:
IIR.number = bass_boost_mode;
boost = 1;
break;
case 32:
RFX.number = reverb_effect_mode;
break;
default:
break;
}
loop_icon_touched = 1;
loop_icon_cnt = 10000;
goto EXIT_TP;
}
if(ret != RET_PLAY_NORM){
goto END_MP3;
}
if(curX == curXprev){
goto SKIP_SEEK;
}
my_fseek(infile, seekBytesSyncWord + music_src_p.offset, SEEK_SET);
bytesLeft = 0;
eofReached = 0;
readPtr = readBuf;
err = 0;
music_play.currentTotalSec = totalSec * (float)(infile->seekBytes - seekBytesSyncWord) / (float)media_data_totalBytes;
position_changed = 1;
noerror_cnt = 0;
SKIP_SEEK:
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
music_play.update = 0, cnt = 0;
DMA_ITConfig(DMA1_Stream1, DMA_IT_TC | DMA_IT_HT, ENABLE);
DMA_Cmd(DMA1_Stream1, ENABLE);
if(music_play.currentTotalSec == 0){
my_fseek(infile, seekBytesSyncWord, SEEK_SET);
bytesLeft = 0;
outOfData = 0;
eofReached = 0;
readPtr = readBuf;
nRead = 0;
continue;
}
}
EXIT_TP:
/* find start of next MP3 frame - assume EOF if no sync found */
offset = MP3FindSyncWord(readPtr, bytesLeft);
if (offset < 0) {
debug.printf("\r\nno sync found");
bytesLeft = 0;
readPtr = readBuf;
continue;
}
readPtr += offset;
bytesLeft -= offset;
/* decode one MP3 frame - if offset < 0 then bytesLeft was less than a full frame */
err = MP3Decode(hMP3Decoder, &readPtr, &bytesLeft, outbuf, 0);
/* signed samples to unsigned and store delay buffer */
for(i = 0;i < SoundDMAHalfBlocks;i++){
if(vocal_cancel_mode){ // vocal cancel
pabuf[i] = __PKHBT(__QASX(pabuf[i], pabuf[i]), __QSAX(pabuf[i], pabuf[i]), 0);
}
if(settings_group.music_conf.b.prehalve){ // pre halve
pabuf[i] = __SHADD16(0, pabuf[i]); // LR right shift 1bit
}
pabuf[i] ^= 0x80008000; // signed to unsigned
delay_buffer.ptr[delay_buffer.idx++] = pabuf[i];
if(delay_buffer.idx >= delay_buffer.size){
delay_buffer.idx = 0;
delay_buffer_filled = 1;
}
}
/* IIR filtering */
if(delay_buffer_filled && !position_changed && boost){
IIR_Filter(&IIR, pabuf, fabuf, fbbuf);
}
/* Reverb effect */
if(delay_buffer_filled && !position_changed && reverb_effect_mode){ // Reverb effect
REVERB(&RFX, pabuf);
}
if(!position_changed && settings_group.music_conf.b.fft){
/* sample audio data for FFT calcuration */
FFT_Sample(&FFT, pabuf);
/* FFT analyzer left */
FFT_Display_Left(&FFT, drawBuff, 0xef7d);
/* FFT analyzer right */
FFT_Display_Right(&FFT, drawBuff, 0xef7d);
}
if (err) {
noerror_cnt = 0;
/* error occurred */
switch (err) {
case ERR_MP3_INDATA_UNDERFLOW:
debug.printf("\r\nERR_MP3_INDATA_UNDERFLOW");
break;
case ERR_MP3_MAINDATA_UNDERFLOW:
/* do nothing - next call to decode will provide more mainData */
debug.printf("\r\nERR_MP3_MAINDATA_UNDERFLOW");
break;
case ERR_MP3_FREE_BITRATE_SYNC:
debug.printf("\r\nERR_MP3_FREE_BITRATE_SYNC");
break;
case ERR_MP3_INVALID_FRAMEHEADER:
case ERR_MP3_INVALID_HUFFCODES:
debug.printf("\r\nERR_MP3_INVALID_(FRAMEHEADER | HUFFCODES)");
bytesLeft = 0;
readPtr = readBuf;
continue;
default:
debug.printf("\r\nerr:%d", err);
break;
}
} else {
noerror_cnt++;
}
if(position_changed && noerror_cnt >= 15){
position_changed = 0;
AUDIO_OUT_ENABLE;
}
if(music_play.update && music_play.comp == 0){ // update time remain
music_play.comp = 1;
remainTotalSec = -abs(music_play.currentTotalSec - totalSec);
setStrSec(timeStr, remainTotalSec);
LCDPutBuffToBgImg(drawBuff->timeRemain.x, drawBuff->timeRemain.y, \
drawBuff->timeRemain.width, drawBuff->timeRemain.height, drawBuff->timeRemain.p);
LCDGotoXY(drawBuff->timeRemain.x + 1, drawBuff->timeRemain.y + 1);
LCDPutString(timeStr, BLACK);
LCDGotoXY(drawBuff->timeRemain.x, drawBuff->timeRemain.y);
LCDPutString(timeStr, WHITE);
continue;
}
if(music_play.update && music_play.comp == 1){ // update time elapsed
music_play.comp = 2;
setStrSec(timeStr, music_play.currentTotalSec);
LCDPutBuffToBgImg(drawBuff->timeElapsed.x, drawBuff->timeElapsed.y, \
drawBuff->timeElapsed.width, drawBuff->timeElapsed.height, drawBuff->timeElapsed.p);
LCDGotoXY(drawBuff->timeElapsed.x + 1, drawBuff->timeElapsed.y + 1);
LCDPutString(timeStr, BLACK);
LCDGotoXY(drawBuff->timeElapsed.x, drawBuff->timeElapsed.y);
LCDPutString(timeStr, WHITE);
continue;
}
if(music_play.update && music_play.comp == 2){ // update seek circle
music_play.update = 0;
LCDPutBuffToBgImg(prevX, drawBuff->posision.y, \
drawBuff->posision.width, drawBuff->posision.height, drawBuff->posision.p);
curX = (LCD_WIDTH - (33)) * (float)((float)(infile->seekBytes - seekBytesSyncWord) / (float)media_data_totalBytes) + 8;
LCDStoreBgImgToBuff(curX, drawBuff->posision.y, \
drawBuff->posision.width, drawBuff->posision.height, drawBuff->posision.p);
LCDPutIcon(curX, drawBuff->posision.y, \
drawBuff->posision.width, drawBuff->posision.height, seek_circle_16x16, seek_circle_16x16_alpha);
prevX = curX;
continue;
}
}
if(!eofReached && !LCDStatusStruct.waitExitKey){
ret = RET_PLAY_STOP;
} else {
ret = RET_PLAY_NORM;
}
END_MP3:
MP3FreeDecoder(hMP3Decoder);
EXIT_PROCESS:
DMA_ITConfig(DMA1_Stream1, DMA_IT_TC | DMA_IT_HT, DISABLE);
DMA_Cmd(DMA1_Stream1, DISABLE);
AUDIO_OUT_SHUTDOWN;
/* Disable the TIM1 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_TIM10_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
NVIC_Init(&NVIC_InitStructure);
my_fclose(infile);
LCDStatusStruct.waitExitKey = 0;
LCD_FUNC.putChar = putCharTmp;
LCD_FUNC.putWideChar = putWideCharTmp;
TOUCH_PINIRQ_ENABLE;
TouchPenIRQ_Enable();
time.prevTime = time.curTime;
time.flags.enable = 1;
return ret;
}
|
1137519-player
|
mp3.c
|
C
|
lgpl
| 35,170
|
/*
* mpool.c
*
* Created on: 2011/05/14
* Author: Tonsuke
*/
#include "mpool.h"
#include "fat.h"
#include <stdlib.h>
void create_mpool(){
mpool_struct.mem_seek = 0;
}
void* mpool_alloc(uint32_t sizeofmemory){
uint32_t current_seek;
current_seek = mpool_struct.mem_seek;
mpool_struct.mem_seek += sizeofmemory;
return (void*)(mempool + current_seek);
}
void mpool_destroy(){
}
void* jmemread(MY_FILE *fp, size_t *nbytes, int32_t n)
{
if(n <= 0){
*nbytes = 0;
return 0;
}
void *ret_buf;
if(fp->fileSize < (fp->seekBytes + n)){
n = fp->fileSize - fp->seekBytes;
}
ret_buf = (void*)((char*)CCM_BASE + fp->seekBytes);
fp->seekBytes += n;
*nbytes = n;
return ret_buf;
}
|
1137519-player
|
mpool.c
|
C
|
lgpl
| 706
|
/*
* sound.c
*
* Created on: 2011/03/12
* Author: Tonsuke
*/
#include "sound.h"
#include "lcd.h"
#include "icon.h"
#include "xpt2046.h"
#include "aac.h"
#include "mp3.h"
#include "settings.h"
#include "board_config.h"
#include "pcf_font.h"
#include "mpool.h"
#include "arm_math.h"
#include "fft.h"
#include "fx.h"
uint8_t navigation_loop_mode;
uint8_t bass_boost_mode;
uint8_t reverb_effect_mode;
uint8_t vocal_cancel_mode;
music_play_typedef music_play;
void TIM1_UP_TIM10_IRQHandler(void)
{
if(TIM_GetITStatus(TIM1, TIM_IT_Update)){
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
music_play.currentTotalSec++;
music_play.update = 1;
music_play.comp = 0;
}
}
void DAC_Buffer_Process_Stereo_S16bit_PhotoFrame()
{
int i, halfBufferSize = dac_intr.bufferSize >> 1;
uint32_t *pabuf;
uint8_t *outbuf;
if(SOUND_DMA_HALF_TRANS_BB){ // Half
SOUND_DMA_CLEAR_HALF_TRANS_BB = 1;
outbuf = (uint8_t*)dac_intr.buff;
pabuf = (uint32_t*)outbuf;
} else if(SOUND_DMA_FULL_TRANS_BB) { // Full
SOUND_DMA_CLEAR_FULL_TRANS_BB = 1;
outbuf = (uint8_t*)&dac_intr.buff[halfBufferSize];
pabuf = (uint32_t*)outbuf;
}
my_fread(outbuf, 1, halfBufferSize, dac_intr.fp);
for(i = 0;i < halfBufferSize >> 2;i += 8){ // signed to unsigned
pabuf[0] ^= 0x80008000;
pabuf[1] ^= 0x80008000;
pabuf[2] ^= 0x80008000;
pabuf[3] ^= 0x80008000;
pabuf[4] ^= 0x80008000;
pabuf[5] ^= 0x80008000;
pabuf[6] ^= 0x80008000;
pabuf[7] ^= 0x80008000;
pabuf += 8;
}
dac_intr.sound_reads += halfBufferSize;
if(dac_intr.sound_reads > (halfBufferSize * 10)){
AUDIO_OUT_ENABLE;
}
if(dac_intr.sound_reads >= dac_intr.contentSize){
NVIC_InitTypeDef NVIC_InitStructure;
DMA_ITConfig(DMA1_Stream1, DMA_IT_TC | DMA_IT_HT, DISABLE);
DMA_Cmd(DMA1_Stream1, DISABLE);
AUDIO_OUT_SHUTDOWN;
/* Disable DMA1_Stream1 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = DMA1_Stream1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
NVIC_Init(&NVIC_InitStructure);
my_fclose(dac_intr.fp);
dac_intr.fp = '\0';
dac_intr.comp = 1;
}
}
void DAC_Buffer_Process_Stereo_S16bit()
{
int i, halfBufferSize = dac_intr.bufferSize >> 1;
uint32_t *pabuf;
uint8_t *outbuf;
if(SOUND_DMA_HALF_TRANS_BB){ // Half
SOUND_DMA_CLEAR_HALF_TRANS_BB = 1;
outbuf = (uint8_t*)dac_intr.buff;
pabuf = (uint32_t*)outbuf;
} else if(SOUND_DMA_FULL_TRANS_BB) { // Full
SOUND_DMA_CLEAR_FULL_TRANS_BB = 1;
outbuf = (uint8_t*)&dac_intr.buff[halfBufferSize];
pabuf = (uint32_t*)outbuf;
}
my_fread(outbuf, 1, halfBufferSize, dac_intr.fp);
for(i = 0;i < halfBufferSize >> 2;i += 8){ // signed to unsigned
pabuf[0] ^= 0x80008000;
pabuf[1] ^= 0x80008000;
pabuf[2] ^= 0x80008000;
pabuf[3] ^= 0x80008000;
pabuf[4] ^= 0x80008000;
pabuf[5] ^= 0x80008000;
pabuf[6] ^= 0x80008000;
pabuf[7] ^= 0x80008000;
pabuf += 8;
}
dac_intr.sound_reads += halfBufferSize;
}
void DAC_Buffer_Process_Mono_U8bit()
{
int halfBufferSize = dac_intr.bufferSize >> 1;
uint8_t *outbuf;
if(SOUND_DMA_HALF_TRANS_BB){ // Half
SOUND_DMA_CLEAR_HALF_TRANS_BB = 1;
outbuf = (uint8_t*)dac_intr.buff;
} else if(SOUND_DMA_FULL_TRANS_BB) { // Full
SOUND_DMA_CLEAR_FULL_TRANS_BB = 1;
outbuf = (uint8_t*)&dac_intr.buff[halfBufferSize];
}
my_fread(outbuf, 1, halfBufferSize, dac_intr.fp);
dac_intr.sound_reads += halfBufferSize;
}
void DMA1_Stream1_IRQHandler(void)
{
dac_intr.func();
}
void SOUNDDMAConf(void *dacOutputReg, size_t blockSize, size_t periphDataSize)
{
DMA_InitTypeDef DMA_InitStructure;
/*!< DMA1 Channel7 Stream1 disable */
DMA_Cmd(DMA1_Stream1, DISABLE);
DMA_DeInit(DMA1_Stream1);
/*!< DMA1 Channel7 Config */
DMA_InitStructure.DMA_Channel = DMA_Channel_7;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)dacOutputReg;
DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)dac_intr.buff;
DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
DMA_InitStructure.DMA_BufferSize = dac_intr.bufferSize / blockSize;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = (periphDataSize > 0)?0x400 * periphDataSize:0;
DMA_InitStructure.DMA_MemoryDataSize = (periphDataSize > 0)?0x400 * periphDataSize:0;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull;
DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_INC4;
DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_INC4;
DMA_Init(DMA1_Stream1, &DMA_InitStructure);
}
void SOUNDInitDAC(uint32_t sampleRate)
{
GPIO_InitTypeDef GPIO_InitStructure;
DAC_InitTypeDef DAC_InitStructure;
// CS43L22Init();
RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC | RCC_APB1Periph_TIM6, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA1 | RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOC, ENABLE);
// PC5 MAX4410 Audio Amp Shutdown
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOC, &GPIO_InitStructure); // 初期化関数を読み出します。
AUDIO_OUT_SHUTDOWN;
// PA4 PA5 DAC_OUT1 DAC_OUT2
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure); // 初期化関数を読み出します。
DAC_DeInit();
DAC_InitStructure.DAC_Trigger = DAC_Trigger_T6_TRGO;
DAC_InitStructure.DAC_WaveGeneration = DAC_WaveGeneration_None;
DAC_InitStructure.DAC_LFSRUnmask_TriangleAmplitude = DAC_LFSRUnmask_Bit0;
DAC_InitStructure.DAC_OutputBuffer = DAC_OutputBuffer_Enable;
DAC_Init(DAC_Channel_1, &DAC_InitStructure);
DAC_Init(DAC_Channel_2, &DAC_InitStructure);
DAC_DMACmd(DAC_Channel_1, ENABLE);
DAC_DMACmd(DAC_Channel_2, ENABLE);
DAC_Cmd(DAC_Channel_1, ENABLE);
DAC_Cmd(DAC_Channel_2, ENABLE);
TIM6->ARR = ((SystemCoreClock / 4) * 2) / sampleRate - 1;
TIM6->PSC = 0;
TIM6->CR1 |= _BV(7);
TIM6->CR2 |= TIM_TRGOSource_Update;
TIM6->DIER |= TIM_DMA_Update | _BV(0); // Interrupt Enable;
TIM6->CR1 |= _BV(0);
}
void setStrSec(char *timeStr, int totalSec)
{
int minute, sec, it = 0, temp;
const char asciiTable[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
if(totalSec < 0){
timeStr[it++] = '-';
totalSec = abs(totalSec);
}
minute = totalSec / 60;
sec = totalSec % 60;
if((temp = minute / 100) > 0){
timeStr[it++] = asciiTable[temp];
timeStr[it++] = asciiTable[(minute % 100) / 10];
} else if((temp = minute / 10) > 0) {
timeStr[it++] = asciiTable[temp];
}
timeStr[it++] = asciiTable[minute % 10];
timeStr[it++] = ':';
timeStr[it++] = asciiTable[sec / 10];
timeStr[it++] = asciiTable[sec % 10];
timeStr[it] = '\0';
}
int PlaySoundPhotoFrame(int id)
{
int ret;
WAVEFormatStruct wav;
WAVEFormatHeaderStruct wavHeader;
WAVEFormatChunkStruct wavChunk;
char str[10];
NVIC_InitTypeDef NVIC_InitStructure;
MY_FILE *infile;
if(!(infile = my_fopen(id))){
ret = RET_PLAY_STOP;
goto EXIT_WAV;
}
my_fread(&wavHeader, 1, sizeof(WAVEFormatHeaderStruct), infile);
debug.printf("\r\n\n[WAVE]");
if(strncmp(wavHeader.headStrRIFF, "RIFF", 4) != 0){
debug.printf("\r\nNot contain RIFF chunk");
ret = RET_PLAY_STOP;
goto END_WAV;
}
debug.printf("\r\nFile Size:%d", wavHeader.fileSize);
if(strncmp(wavHeader.headStrWAVE, "WAVE", 4) != 0){
debug.printf("\r\nThis is not WAVE file.");
ret = RET_PLAY_STOP;
goto END_WAV;
}
int restBytes = wavHeader.fileSize;
while(1){ // loop until format chunk is found
my_fread(&wavChunk, 1, sizeof(WAVEFormatChunkStruct), infile);
if(strncmp(wavChunk.chunkfmt, "fmt ", 4) == 0){
break;
}
memset(str, '\0', sizeof(str));
debug.printf("\r\n\nchunkType:%s", strncpy(str, wavChunk.chunkfmt, sizeof(wavChunk.chunkfmt)));
debug.printf("\r\nchunkSize:%d", wavChunk.chunkSize);
restBytes = restBytes - wavChunk.chunkSize - sizeof(WAVEFormatChunkStruct);
if(restBytes <= 0){
debug.printf("\r\nNot Found Format Chunk.");
ret = RET_PLAY_STOP;
goto END_WAV;
}
my_fseek(infile, wavChunk.chunkSize, SEEK_CUR);
}
my_fread(&wav, 1, sizeof(WAVEFormatStruct), infile);
my_fseek(infile, wavChunk.chunkSize - sizeof(WAVEFormatStruct), SEEK_CUR);
restBytes = restBytes - wavChunk.chunkSize - sizeof(WAVEFormatChunkStruct);
while(1){ // loop until data chunk is found
my_fread(&wavChunk, 1, sizeof(WAVEFormatChunkStruct), infile);
if(strncmp(wavChunk.chunkfmt, "data", 4) == 0){
break;
}
memset(str, '\0', sizeof(str));
debug.printf("\r\n\nchunkType:%s", strncpy(str, wavChunk.chunkfmt, sizeof(wavChunk.chunkfmt)));
debug.printf("\r\nchunkSize:%d", wavChunk.chunkSize);
restBytes = restBytes - wavChunk.chunkSize - sizeof(WAVEFormatChunkStruct);
if(restBytes <= 0){
debug.printf("\r\nNot Found Format Chunk.");
ret = RET_PLAY_STOP;
goto END_WAV;
}
my_fseek(infile, wavChunk.chunkSize, SEEK_CUR);
}
memset(str, '\0', sizeof(str));
debug.printf("\r\n\nchunkType:%s", strncpy(str, wavChunk.chunkfmt, sizeof(wavChunk.chunkfmt)));
debug.printf("\r\nchunkSize:%d", wavChunk.chunkSize);
debug.printf("\r\n\nformatID:%d", wav.formatID);
debug.printf("\r\nNum Channel:%d", wav.numChannel);
debug.printf("\r\nSampling Rate:%d", wav.sampleRate);
debug.printf("\r\nData Speed:%d", wav.dataSpeed);
debug.printf("\r\nBlock Size:%d", wav.blockSize);
debug.printf("\r\nBit Per Sample:%d", wav.bitPerSample);
debug.printf("\r\nBytes Wave Data:%d", wavChunk.chunkSize);
dac_intr.fp = infile;
dac_intr.buff = (uint8_t*)cursorRAM;//SOUND_BUFFER;
dac_intr.bufferSize = sizeof(cursorRAM);
dac_intr.contentSize = infile->fileSize - infile->seekBytes;
dac_intr.comp = 0;
my_fread(dac_intr.buff, 1, dac_intr.bufferSize, dac_intr.fp);
dac_intr.sound_reads = dac_intr.bufferSize;
if(wav.bitPerSample == 8){
dac_intr.func = DAC_Buffer_Process_Mono_U8bit;
} else {
dac_intr.func = DAC_Buffer_Process_Stereo_S16bit_PhotoFrame;
}
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA1, ENABLE);
// Enable DMA1_Stream1 gloabal Interrupt
NVIC_InitStructure.NVIC_IRQChannel = DMA1_Stream1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
SOUNDInitDAC(wav.sampleRate);
SOUNDDMAConf((void*)&DAC->DHR12LD, wav.blockSize, (wav.bitPerSample / 8) * wav.numChannel);
DMA_ITConfig(DMA1_Stream1, DMA_IT_TC | DMA_IT_HT, ENABLE);
DMA_Cmd(DMA1_Stream1, ENABLE);
END_WAV:
EXIT_WAV:
/* Disable DMA1_Stream1 gloabal Interrupt */
// NVIC_InitStructure.NVIC_IRQChannel = DMA1_Stream1_IRQn;
// NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
// NVIC_Init(&NVIC_InitStructure);
// my_fclose(infile);
return 0;
}
int PlaySound(int id)
{
time.flags.enable = 0;
TouchPenIRQ_Disable();
TOUCH_PINIRQ_DISABLE;
touch.func = touch_empty_func;
int i;
uint32_t *pabuf;
uint8_t *outbuf;
char str[10];
int totalSec, remainTotalSec, media_data_totalBytes;
int curX = 0, prevX = 0;
volatile int ret = RET_PLAY_NORM;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
void *putCharTmp = '\0', *putWideCharTmp = '\0';
drawBuff_typedef dbuf, *drawBuff;
drawBuff = &dbuf;
_drawBuff = drawBuff;
char timeStr[20];
WAVEFormatStruct wav;
WAVEFormatHeaderStruct wavHeader;
WAVEFormatChunkStruct wavChunk;
MY_FILE *infile, file_covr;
if(!(infile = my_fopen(id))){
ret = RET_PLAY_STOP;
goto EXIT_WAV;
}
my_fread(&wavHeader, 1, sizeof(WAVEFormatHeaderStruct), infile);
debug.printf("\r\n\n[WAVE]");
if(strncmp(wavHeader.headStrRIFF, "RIFF", 4) != 0){
debug.printf("\r\nNot contain RIFF chunk");
ret = RET_PLAY_STOP;
goto END_WAV;
}
debug.printf("\r\nFile Size:%d", wavHeader.fileSize);
if(strncmp(wavHeader.headStrWAVE, "WAVE", 4) != 0){
debug.printf("\r\nThis is not WAVE file.");
ret = RET_PLAY_STOP;
goto END_WAV;
}
int restBytes = wavHeader.fileSize;
while(1){ // loop until format chunk is found
my_fread(&wavChunk, 1, sizeof(WAVEFormatChunkStruct), infile);
if(strncmp(wavChunk.chunkfmt, "fmt ", 4) == 0){
break;
}
memset(str, '\0', sizeof(str));
debug.printf("\r\n\nchunkType:%s", strncpy(str, wavChunk.chunkfmt, sizeof(wavChunk.chunkfmt)));
debug.printf("\r\nchunkSize:%d", wavChunk.chunkSize);
restBytes = restBytes - wavChunk.chunkSize - sizeof(WAVEFormatChunkStruct);
if(restBytes <= 0){
debug.printf("\r\nNot Found Format Chunk.");
ret = RET_PLAY_STOP;
goto END_WAV;
}
my_fseek(infile, wavChunk.chunkSize, SEEK_CUR);
}
my_fread(&wav, 1, sizeof(WAVEFormatStruct), infile);
my_fseek(infile, wavChunk.chunkSize - sizeof(WAVEFormatStruct), SEEK_CUR);
restBytes = restBytes - wavChunk.chunkSize - sizeof(WAVEFormatChunkStruct);
while(1){ // loop until data chunk is found
my_fread(&wavChunk, 1, sizeof(WAVEFormatChunkStruct), infile);
if(strncmp(wavChunk.chunkfmt, "data", 4) == 0){
break;
}
memset(str, '\0', sizeof(str));
debug.printf("\r\n\nchunkType:%s", strncpy(str, wavChunk.chunkfmt, sizeof(wavChunk.chunkfmt)));
debug.printf("\r\nchunkSize:%d", wavChunk.chunkSize);
restBytes = restBytes - wavChunk.chunkSize - sizeof(WAVEFormatChunkStruct);
if(restBytes <= 0){
debug.printf("\r\nNot Found Format Chunk.");
ret = RET_PLAY_STOP;
goto END_WAV;
}
my_fseek(infile, wavChunk.chunkSize, SEEK_CUR);
}
music_src_p.curX = &curX;
music_src_p.prevX = &prevX;
music_src_p.media_data_totalBytes = &media_data_totalBytes;
music_src_p.totalSec = &totalSec;
music_src_p.drawBuff = drawBuff;
music_src_p.fp = infile;
LCDPutBgImgMusic();
file_covr.clusterOrg = 0;
dispArtWork(&file_covr);
LCDPutIcon(0, 155, 320, 80, music_underbar_320x80, music_underbar_320x80_alpha);
memset(str, '\0', sizeof(str));
debug.printf("\r\n\nchunkType:%s", strncpy(str, wavChunk.chunkfmt, sizeof(wavChunk.chunkfmt)));
debug.printf("\r\nchunkSize:%d", wavChunk.chunkSize);
debug.printf("\r\n\nformatID:%d", wav.formatID);
debug.printf("\r\nNum Channel:%d", wav.numChannel);
debug.printf("\r\nSampling Rate:%d", wav.sampleRate);
debug.printf("\r\nData Speed:%d", wav.dataSpeed);
debug.printf("\r\nBlock Size:%d", wav.blockSize);
debug.printf("\r\nBit Per Sample:%d", wav.bitPerSample);
debug.printf("\r\nBytes Wave Data:%d", wavChunk.chunkSize);
uint32_t data_offset = infile->seekBytes;
if(wav.bitPerSample != 16){
debug.printf("\r\n**Bit Per Sample must be 16bit**");
debug.printf("\r\ndata offset:%d", data_offset);
ret = RET_PLAY_STOP;
goto END_WAV;
}
int xTag = 110, yTag = 87, disp_limit = 300, strLen;
putCharTmp = LCD_FUNC.putChar;
putWideCharTmp = LCD_FUNC.putWideChar;
if(!pcf_font.c_loaded){
LCD_FUNC.putChar = PCFPutChar16px;
LCD_FUNC.putWideChar = PCFPutChar16px;
} else {
LCD_FUNC.putChar = C_PCFPutChar16px;
LCD_FUNC.putWideChar = C_PCFPutChar16px;
}
disp_limit = 288;
uint8_t strNameLFN[80];
if(setLFNname(strNameLFN, id, LFN_WITHOUT_EXTENSION, sizeof(strNameLFN))){
strLen = LCDGetStringLFNPixelLength(strNameLFN, 16);
if((xTag + strLen) < LCD_WIDTH){
disp_limit = LCD_WIDTH - 1;
} else {
disp_limit = LCD_WIDTH - 20;
yTag -= 10;
}
LCDGotoXY(xTag + 1, yTag + 1);
LCDPutStringLFN(xTag + 1, disp_limit, 2, strNameLFN, BLACK);
LCDGotoXY(xTag, yTag);
LCDPutStringLFN(xTag, disp_limit - 1, 2, strNameLFN, WHITE);
} else {
char strNameSFN[9];
memset(strNameSFN, '\0', sizeof(strNameSFN));
setSFNname(strNameSFN, id);
LCDGotoXY(xTag + 1, yTag + 1);
LCDPutString(strNameSFN, BLACK);
LCDGotoXY(xTag, yTag);
LCDPutString(strNameSFN, WHITE);
}
LCD_FUNC.putChar = putCharTmp;
LCD_FUNC.putWideChar = putWideCharTmp;
char s[20];
SPRINTF((char*)s, "%d/%d", id, fat.fileCnt - 1);
LCDGotoXY(21, MUSIC_INFO_POS_Y + 1);
LCDPutString((char*)s, BLACK);
LCDGotoXY(20, MUSIC_INFO_POS_Y);
LCDPutString((char*)s, WHITE);
if(settings_group.music_conf.b.musicinfo){
LCDGotoXY(71, MUSIC_INFO_POS_Y + 1);
LCDPutString("WAV", BLACK);
LCDGotoXY(70, MUSIC_INFO_POS_Y);
LCDPutString("WAV", WHITE);
LCDGotoXY(111, MUSIC_INFO_POS_Y + 1);
LCDPutString(wav.numChannel == 2 ? "Stereo" : "Mono", BLACK);
LCDGotoXY(110, MUSIC_INFO_POS_Y);
LCDPutString(wav.numChannel == 2 ? "Stereo" : "Mono", WHITE);
SPRINTF(s, "%1.2fMbps", (float)(wav.dataSpeed * 8) / 1000000.0f);
LCDGotoXY(171, MUSIC_INFO_POS_Y + 1);
LCDPutString(s, BLACK);
LCDGotoXY(170, MUSIC_INFO_POS_Y);
LCDPutString(s, WHITE);
SPRINTF(s, "%dHz", (int)wav.sampleRate);
LCDGotoXY(241, MUSIC_INFO_POS_Y + 1);
LCDPutString(s, BLACK);
LCDGotoXY(240, MUSIC_INFO_POS_Y);
LCDPutString(s, WHITE);
}
putCharTmp = LCD_FUNC.putChar;
putWideCharTmp = LCD_FUNC.putWideChar;
if(!pcf_font.c_loaded){
LCD_FUNC.putChar = PCFPutCharCache;
LCD_FUNC.putWideChar = PCFPutCharCache;
extern uint16_t cursorRAM[];
PCFSetGlyphCacheStartAddress((void*)cursorRAM);
PCFCachePlayTimeGlyphs(12);
} else {
LCD_FUNC.putChar = C_PCFPutChar;
LCD_FUNC.putWideChar = C_PCFPutChar;
}
media_data_totalBytes = wavChunk.chunkSize;
totalSec = wavChunk.chunkSize / wav.dataSpeed;
setStrSec(timeStr, totalSec);
debug.printf("\r\nplay time:%s", timeStr);
// time elapsed
drawBuff->timeElapsed.x = 14;
drawBuff->timeElapsed.y = 188;
drawBuff->timeElapsed.width = 50;
drawBuff->timeElapsed.height = 13;
LCDStoreBgImgToBuff(drawBuff->timeElapsed.x, drawBuff->timeElapsed.y, \
drawBuff->timeElapsed.width, drawBuff->timeElapsed.height, drawBuff->timeElapsed.p);
// time remain
drawBuff->timeRemain.x = totalSec < 6000 ? 268 : 260;
drawBuff->timeRemain.y = 188;
drawBuff->timeRemain.width = 50;
drawBuff->timeRemain.height = 13;
LCDStoreBgImgToBuff(drawBuff->timeRemain.x, drawBuff->timeRemain.y, \
drawBuff->timeRemain.width, drawBuff->timeRemain.height, drawBuff->timeRemain.p);
drawBuff->posision.x = 0;
drawBuff->posision.y = 168;
drawBuff->posision.width = 16;
drawBuff->posision.height = 16;
LCDStoreBgImgToBuff(drawBuff->posision.x, drawBuff->posision.y, \
drawBuff->posision.width, drawBuff->posision.height, drawBuff->posision.p);
drawBuff->navigation.x = 142;
drawBuff->navigation.y = 189;
drawBuff->navigation.width = 32;
drawBuff->navigation.height = 32;
LCDStoreBgImgToBuff(drawBuff->navigation.x, drawBuff->navigation.y, \
drawBuff->navigation.width, drawBuff->navigation.height, drawBuff->navigation.p);
drawBuff->fft_analyzer_left.x = FFT_ANALYZER_LEFT_POS_X;
drawBuff->fft_analyzer_left.y = FFT_ANALYZER_LEFT_POS_Y;
drawBuff->fft_analyzer_left.width = 32;
drawBuff->fft_analyzer_left.height = 32;
LCDStoreBgImgToBuff(drawBuff->fft_analyzer_left.x, drawBuff->fft_analyzer_left.y, \
drawBuff->fft_analyzer_left.width, drawBuff->fft_analyzer_left.height, drawBuff->fft_analyzer_left.p);
drawBuff->fft_analyzer_right.x = FFT_ANALYZER_RIGHT_POS_X;
drawBuff->fft_analyzer_right.y = FFT_ANALYZER_RIGHT_POS_Y;
drawBuff->fft_analyzer_right.width = 32;
drawBuff->fft_analyzer_right.height = 32;
LCDStoreBgImgToBuff(drawBuff->fft_analyzer_right.x, drawBuff->fft_analyzer_right.y, \
drawBuff->fft_analyzer_right.width, drawBuff->fft_analyzer_right.height, drawBuff->fft_analyzer_right.p);
drawBuff->navigation_loop.x = 277;
drawBuff->navigation_loop.y = 207;
drawBuff->navigation_loop.width = 24;
drawBuff->navigation_loop.height = 18;
LCDStoreBgImgToBuff(drawBuff->navigation_loop.x, drawBuff->navigation_loop.y, \
drawBuff->navigation_loop.width, drawBuff->navigation_loop.height, drawBuff->navigation_loop.p);
switch(navigation_loop_mode){
case NAV_ONE_PLAY_EXIT: // 1 play exit
LCDPutIcon(_drawBuff->navigation_loop.x, _drawBuff->navigation_loop.y, _drawBuff->navigation_loop.width, _drawBuff->navigation_loop.height, \
navigation_bar_24x18, navigation_bar_24x18_alpha);
break;
case NAV_PLAY_ENTIRE: // play entire in directry
LCDPutIcon(_drawBuff->navigation_loop.x, _drawBuff->navigation_loop.y, _drawBuff->navigation_loop.width, _drawBuff->navigation_loop.height, \
navigation_entire_loop_24x18, navigation_entire_loop_24x18_alpha);
break;
case NAV_INFINITE_PLAY_ENTIRE: // infinite play entire in directry
LCDPutIcon(_drawBuff->navigation_loop.x, _drawBuff->navigation_loop.y, _drawBuff->navigation_loop.width, _drawBuff->navigation_loop.height, \
navigation_infinite_entire_loop_24x18, navigation_infinite_entire_loop_24x18_alpha);
break;
case NAV_INFINITE_ONE_PLAY: // infinite 1 play
LCDPutIcon(_drawBuff->navigation_loop.x, _drawBuff->navigation_loop.y, _drawBuff->navigation_loop.width, _drawBuff->navigation_loop.height, \
navigation_one_loop_24x18, navigation_one_loop_24x18_alpha);
break;
case NAV_SHUFFLE_PLAY: // shuffle
LCDPutIcon(_drawBuff->navigation_loop.x, _drawBuff->navigation_loop.y, _drawBuff->navigation_loop.width, _drawBuff->navigation_loop.height, \
navigation_shuffle_24x18, navigation_shuffle_24x18_alpha);
break;
default:
break;
}
LCDPutIcon(drawBuff->navigation.x, drawBuff->navigation.y, \
drawBuff->navigation.width, drawBuff->navigation.height, \
navigation_pause_patch_32x32, navigation_pause_patch_32x32_alpha);
/* Update Bass Boost Icon */
drawBuff->bass_boost.x = 10;
drawBuff->bass_boost.y = 3;
drawBuff->bass_boost.width = 24;
drawBuff->bass_boost.height = 18;
LCDStoreBgImgToBuff(drawBuff->bass_boost.x, drawBuff->bass_boost.y, \
drawBuff->bass_boost.width, drawBuff->bass_boost.height, drawBuff->bass_boost.p);
Update_Bass_Boost_Icon(bass_boost_mode);
/* Update Reverb Effect Icon */
drawBuff->reverb_effect.x = 60;
drawBuff->reverb_effect.y = 2;
drawBuff->reverb_effect.width = 24;
drawBuff->reverb_effect.height = 18;
LCDStoreBgImgToBuff(drawBuff->reverb_effect.x, drawBuff->reverb_effect.y, \
drawBuff->reverb_effect.width, drawBuff->reverb_effect.height, drawBuff->reverb_effect.p);
Update_Reverb_Effect_Icon(reverb_effect_mode);
/* Update Vocal Canceler Icon */
drawBuff->vocal_cancel.x = 107;
drawBuff->vocal_cancel.y = 5;
drawBuff->vocal_cancel.width = 24;
drawBuff->vocal_cancel.height = 18;
LCDStoreBgImgToBuff(drawBuff->vocal_cancel.x, drawBuff->vocal_cancel.y, \
drawBuff->vocal_cancel.width, drawBuff->vocal_cancel.height, drawBuff->vocal_cancel.p);
Update_Vocal_Canceler_Icon(vocal_cancel_mode);
uint8_t SOUND_BUFFER[9216];
dac_intr.fp = infile;
dac_intr.buff = SOUND_BUFFER;
dac_intr.bufferSize = sizeof(SOUND_BUFFER);
int SoundDMAHalfBlocks = (dac_intr.bufferSize / (sizeof(int16_t) * 2)) / 2;
int loop_icon_touched = 0, loop_icon_cnt = 0, boost = 0;
int delay_buffer_filled = 0, DMA_Half_Filled = 0;
float *fabuf, *fbbuf;
float *float_buf = (float*)mempool;
int fbuf_len = dac_intr.bufferSize / 2;
memset(float_buf, '\0', fbuf_len * sizeof(float));
/* variables for reverb effect
* delay_buffer is allocated in CCM.(64KB)
* Maximum length Stereo 16bit(4bytes/sample)
* 0.371s@44100Hz 0.341s@48000Hz */
delay_buffer_typedef delay_buffer;
delay_buffer.ptr = (uint32_t*)CCM_BASE;
delay_buffer.size = 65536 / sizeof(uint32_t);
delay_buffer.idx = 0;
IIR_Filter_Struct_Typedef IIR;
IIR.delay_buffer = &delay_buffer;
IIR.sbuf_size = dac_intr.bufferSize / 2;
IIR.num_blocks = SoundDMAHalfBlocks;
IIR.fs = wav.sampleRate;
IIR.number = bass_boost_mode;
boost = bass_boost_mode;
IIR_Set_Params(&IIR);
REVERB_Struct_Typedef RFX;
RFX.delay_buffer = &delay_buffer;
RFX.num_blocks = SoundDMAHalfBlocks;
RFX.fs = wav.sampleRate;
RFX.number = reverb_effect_mode;
REVERB_Set_Prams(&RFX);
FFT_Struct_Typedef FFT;
FFT.ifftFlag = 0;
FFT.bitReverseFlag = 1;
FFT.length = 64;
FFT.samples = dac_intr.bufferSize / ((wav.bitPerSample / 8) * wav.numChannel) / 2;
if(wav.numChannel < 2){
FFT.samples >>= 1;
}
FFT_Init(&FFT);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
/* Enable the TIM1 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_TIM10_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* 1s = 1 / F_CPU(168MHz) * (167 + 1) * (99 + 1) * (9999 + 1) TIM1フレームレート計測用 */
TIM_TimeBaseInitStructure.TIM_Period = 9999;
TIM_TimeBaseInitStructure.TIM_Prescaler = 99;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = (SystemCoreClock / 1000000UL) - 1; // 168 - 1
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStructure);
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);
int curXprev, cnt = 0;
music_play.currentTotalSec = 0;
music_play.comp = 0;
music_play.update = 1;
outbuf = (uint8_t*)&dac_intr.buff[0];
my_fread(outbuf, 1, dac_intr.bufferSize, dac_intr.fp);
// dac_intr.sound_reads = 0;
SOUNDInitDAC(wav.sampleRate);
SOUNDDMAConf((void*)&DAC->DHR12LD, wav.blockSize, (wav.bitPerSample / 8) * wav.numChannel);
DMA_ITConfig(DMA1_Stream1, DMA_IT_TC | DMA_IT_HT, DISABLE);
DMA_Cmd(DMA1_Stream1, ENABLE);
TIM_Cmd(TIM1, ENABLE);
while((infile->seekBytes < infile->fileSize) && LCDStatusStruct.waitExitKey){
if(loop_icon_touched && TP_PEN_INPUT_BB == Bit_SET){
if(--loop_icon_cnt <= 0){
loop_icon_touched = 0;
}
}
if(TP_PEN_INPUT_BB == Bit_RESET && DMA_Half_Filled && !loop_icon_touched){ // Touch pannel tapped?
curXprev = curX;
ret = musicPause();
if(ret >= 30){
switch(ret){
case 31:
IIR.number = bass_boost_mode;
boost = 1;
break;
case 32:
RFX.number = reverb_effect_mode;
break;
default:
break;
}
loop_icon_touched = 1;
loop_icon_cnt = 10000;
goto EXIT_TP;
}
if(ret != RET_PLAY_NORM){
goto EXIT_WAV;
}
if(curX == curXprev){
goto SKIP_SEEK;
}
// my_fseek(infile, (music_src_p.offset & 0xfffffff0) + sizeof(WAVEFormatStruct), SEEK_SET);
my_fseek(infile, (music_src_p.offset & 0xfffffff0) + data_offset, SEEK_SET);
music_play.currentTotalSec = totalSec * (float)infile->seekBytes / (float)media_data_totalBytes;
SKIP_SEEK:
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
music_play.update = 0;
// DMA_ITConfig(DMA1_Stream1, DMA_IT_TC | DMA_IT_HT, ENABLE);
DMA_Cmd(DMA1_Stream1, ENABLE);
AUDIO_OUT_ENABLE;
}
EXIT_TP:
if(SOUND_DMA_HALF_TRANS_BB){ // Half
SOUND_DMA_CLEAR_HALF_TRANS_BB = 1;
outbuf = (uint8_t*)dac_intr.buff;
pabuf = (uint32_t*)outbuf;
fabuf = (float*)float_buf;
fbbuf = (float*)&float_buf[fbuf_len >> 1];
} else if(SOUND_DMA_FULL_TRANS_BB){ // Full
SOUND_DMA_CLEAR_FULL_TRANS_BB = 1;
outbuf = (uint8_t*)&dac_intr.buff[dac_intr.bufferSize >> 1];
pabuf = (uint32_t*)outbuf;
fabuf = (float*)&float_buf[fbuf_len >> 1];
fbbuf = (float*)float_buf;
} else {
DMA_Half_Filled = 0;
continue;
}
DMA_Half_Filled = 1;
if(cnt++ > 5){
AUDIO_OUT_ENABLE;
}
my_fread(outbuf, 1, dac_intr.bufferSize >> 1, dac_intr.fp);
/* signed samples to unsigned and store delay buffer */
for(i = 0;i < SoundDMAHalfBlocks;i++){
if(vocal_cancel_mode){ // vocal cancel
pabuf[i] = __PKHBT(__QASX(pabuf[i], pabuf[i]), __QSAX(pabuf[i], pabuf[i]), 0);
}
if(settings_group.music_conf.b.prehalve){ // pre halve
pabuf[i] = __SHADD16(0, pabuf[i]); // LR right shift 1bit
}
pabuf[i] ^= 0x80008000; // signed to unsigned
delay_buffer.ptr[delay_buffer.idx++] = pabuf[i];
if(delay_buffer.idx >= delay_buffer.size){
delay_buffer.idx = 0;
delay_buffer_filled = 1;
}
}
dac_intr.sound_reads += dac_intr.bufferSize >> 1;
/* IIR filtering */
if(delay_buffer_filled && boost){
IIR_Filter(&IIR, pabuf, fabuf, fbbuf);
}
/* Reverb effect */
if(delay_buffer_filled && reverb_effect_mode){
REVERB(&RFX, pabuf);
}
if(settings_group.music_conf.b.fft){
/* sample audio data for FFT calcuration */
FFT_Sample(&FFT, pabuf);
/* FFT analyzer left */
FFT_Display_Left(&FFT, drawBuff, 0xef7d);
/* FFT analyzer right */
FFT_Display_Right(&FFT, drawBuff, 0xef7d);
}
if(music_play.update && music_play.comp == 0){ // update time remain
music_play.comp = 1;
remainTotalSec = -abs(music_play.currentTotalSec - totalSec);
setStrSec(timeStr, remainTotalSec);
LCDPutBuffToBgImg(drawBuff->timeRemain.x, drawBuff->timeRemain.y, \
drawBuff->timeRemain.width, drawBuff->timeRemain.height, drawBuff->timeRemain.p);
LCDGotoXY(drawBuff->timeRemain.x + 1, drawBuff->timeRemain.y + 1);
LCDPutString(timeStr, BLACK);
LCDGotoXY(drawBuff->timeRemain.x, drawBuff->timeRemain.y);
LCDPutString(timeStr, WHITE);
continue;
}
if(music_play.update && music_play.comp == 1){ // update time elapsed
music_play.comp = 2;
setStrSec(timeStr, music_play.currentTotalSec);
LCDPutBuffToBgImg(drawBuff->timeElapsed.x, drawBuff->timeElapsed.y, \
drawBuff->timeElapsed.width, drawBuff->timeElapsed.height, drawBuff->timeElapsed.p);
LCDGotoXY(drawBuff->timeElapsed.x + 1, drawBuff->timeElapsed.y + 1);
LCDPutString(timeStr, BLACK);
LCDGotoXY(drawBuff->timeElapsed.x, drawBuff->timeElapsed.y);
LCDPutString(timeStr, WHITE);
continue;
}
if(music_play.update && music_play.comp == 2){ // update seek circle
music_play.update = 0;
LCDPutBuffToBgImg(prevX, drawBuff->posision.y, \
drawBuff->posision.width, drawBuff->posision.height, drawBuff->posision.p);
curX = (LCD_WIDTH - (33)) * (float)((float)(infile->seekBytes - sizeof(WAVEFormatStruct)) / (float)media_data_totalBytes) + 8;
LCDStoreBgImgToBuff(curX, drawBuff->posision.y, \
drawBuff->posision.width, drawBuff->posision.height, drawBuff->posision.p);
LCDPutIcon(curX, drawBuff->posision.y, \
drawBuff->posision.width, drawBuff->posision.height, seek_circle_16x16, seek_circle_16x16_alpha);
prevX = curX;
continue;
}
}
DMA_ITConfig(DMA1_Stream1, DMA_IT_TC | DMA_IT_HT, DISABLE);
DMA_Cmd(DMA1_Stream1, DISABLE);
AUDIO_OUT_SHUTDOWN;
if((infile->seekBytes < infile->fileSize) && !LCDStatusStruct.waitExitKey){
ret = RET_PLAY_STOP;
} else {
ret = RET_PLAY_NORM;
}
EXIT_WAV:
LCD_FUNC.putChar = putCharTmp;
LCD_FUNC.putWideChar = putWideCharTmp;
END_WAV:
/* Disable the TIM1 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_TIM10_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
NVIC_Init(&NVIC_InitStructure);
/* Disable DMA1_Stream1 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = DMA1_Stream1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
NVIC_Init(&NVIC_InitStructure);
my_fclose(infile);
LCDStatusStruct.waitExitKey = 0;
TOUCH_PINIRQ_ENABLE;
TouchPenIRQ_Enable();
time.prevTime = time.curTime;
time.flags.enable = 1;
return ret;
}
void musicTouch()
{
static int prevPosX;
if((touch.posX > (_drawBuff->navigation.x - 5) && touch.posX < (_drawBuff->navigation.x + _drawBuff->navigation.width + 5)) && \
(touch.posY > (_drawBuff->navigation.y - 5) && touch.posY < (_drawBuff->navigation.y + _drawBuff->navigation.height + 5))){ //
LCDPutBuffToBgImg(142, 189, 32, 32, _drawBuff->navigation.p);
LCDPutIcon(142, 189, 32, 32, navigation_pause_patch_32x32, navigation_pause_patch_32x32_alpha);
music_src_p.done = 1;
return;
}
if((touch.posX > 10 && touch.posX < 50) && (touch.posY > 193 && touch.posY < 235)){ // 停止アイコン
debug.printf("\r\nplay abort");
music_src_p.done = -1;
return;
}
if((touch.posX > 180 && touch.posX < 230) && (touch.posY > 190 && touch.posY < 230)){ // 次へアイコン
debug.printf("\r\nplay abort & next");
music_src_p.done = -2;
return;
}
if((touch.posX > 90 && touch.posX < 140) && (touch.posY > 190 && touch.posY < 230)){ // 前へアイコン
debug.printf("\r\nplay abort & prev");
music_src_p.done = -3;
return;
}
if((touch.posX > (_drawBuff->navigation_loop.x - 15) && touch.posX < (_drawBuff->navigation_loop.x + _drawBuff->navigation_loop.width + 15)) && \
(touch.posY > (_drawBuff->navigation_loop.y - 10) && touch.posY < (_drawBuff->navigation_loop.y + _drawBuff->navigation_loop.height + 10))){ //
Update_Navigation_Loop_Icon(navigation_loop_mode = ++navigation_loop_mode % 5);
while(GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_4) == Bit_RESET);
return;
}
if(prevPosX == touch.posX){
return;
}
prevPosX = touch.posX;
if(touch.posY > (_drawBuff->posision.y + _drawBuff->posision.height))
{
return;
}
int remainTotalSec;
char timeStr[20];
*music_src_p.curX = touch.posX - 20;
*music_src_p.curX = *music_src_p.curX < (LCD_WIDTH - 20 - 1) ? *music_src_p.curX : (LCD_WIDTH - 20 - 1);
*music_src_p.curX = *music_src_p.curX > 6 ? *music_src_p.curX : 6;
music_play.currentTotalSec = (float)((float)(*music_src_p.curX - 6) / (float)(LCD_WIDTH - (30))) * *music_src_p.totalSec;
music_src_p.offset = (float)((float)(*music_src_p.curX - 6) / (float)(LCD_WIDTH - (30))) * *music_src_p.media_data_totalBytes;
// position icon
LCDPutBuffToBgImg(*music_src_p.prevX, _drawBuff->posision.y, \
_drawBuff->posision.width, _drawBuff->posision.height, music_src_p.drawBuff->posision.p);
LCDStoreBgImgToBuff(*music_src_p.curX, _drawBuff->posision.y, \
_drawBuff->posision.width, _drawBuff->posision.height, music_src_p.drawBuff->posision.p);
LCDPutIcon(*music_src_p.curX, _drawBuff->posision.y, \
_drawBuff->posision.width, _drawBuff->posision.height, seek_circle_16x16, seek_circle_16x16_alpha);
*music_src_p.prevX = *music_src_p.curX;
// time remain
remainTotalSec = abs(music_play.currentTotalSec - *music_src_p.totalSec) * -1;
setStrSec(timeStr, remainTotalSec);
LCDPutBuffToBgImg(music_src_p.drawBuff->timeRemain.x, music_src_p.drawBuff->timeRemain.y, \
music_src_p.drawBuff->timeRemain.width, music_src_p.drawBuff->timeRemain.height, \
music_src_p.drawBuff->timeRemain.p);
LCDGotoXY(music_src_p.drawBuff->timeRemain.x + 1, music_src_p.drawBuff->timeRemain.y + 1);
LCDPutString(timeStr, BLACK);
LCDGotoXY(music_src_p.drawBuff->timeRemain.x, music_src_p.drawBuff->timeRemain.y);
LCDPutString(timeStr, WHITE);
// time elapsed
setStrSec(timeStr, music_play.currentTotalSec);
LCDPutBuffToBgImg(music_src_p.drawBuff->timeElapsed.x, music_src_p.drawBuff->timeElapsed.y, \
music_src_p.drawBuff->timeElapsed.width, music_src_p.drawBuff->timeElapsed.height, \
music_src_p.drawBuff->timeElapsed.p);
LCDGotoXY(music_src_p.drawBuff->timeElapsed.x + 1, music_src_p.drawBuff->timeElapsed.y + 1);
LCDPutString(timeStr, BLACK);
LCDGotoXY(music_src_p.drawBuff->timeElapsed.x, music_src_p.drawBuff->timeElapsed.y);
LCDPutString(timeStr, WHITE);
return;
}
int musicPause()
{
int ret = RET_PLAY_NORM;
touch.cnt = 0, touch.aveX = 0, touch.aveY = 0;
extern settings_group_typedef settings_group;
extern settings_item_typedef settings_item_fft_bar_type;
extern settings_item_typedef settings_item_fft_color_type;
while(touch.cnt++ < 600){
touch.adX = GET_X_AXIS();
touch.adY = GET_Y_AXIS();
touch.aveX += ((int)(touch.adX - touch.cal->x[2]) * 10) / touch.cal->xStep + 15;
touch.aveY += ((int)(touch.adY - touch.cal->y[0]) * 10) / touch.cal->yStep + 15;
}
touch.posX = touch.aveX / 600;
touch.posY = touch.aveY / 600;
if(touch.posX < 0) touch.posX = 0;
if(touch.posX > 319) touch.posX = 319;
if(touch.posY < 0) touch.posY = 0;
if(touch.posY > 239) touch.posY = 239;
if((touch.posX > (_drawBuff->navigation_loop.x - 10) && touch.posX < (_drawBuff->navigation_loop.x + _drawBuff->navigation_loop.width + 10)) && \
(touch.posY > (_drawBuff->navigation_loop.y - 10) && touch.posY < (_drawBuff->navigation_loop.y + _drawBuff->navigation_loop.height + 10))){ //
Update_Navigation_Loop_Icon(navigation_loop_mode = ++navigation_loop_mode % 5);
return 30;
}
if((touch.posX > (_drawBuff->bass_boost.x - 10) && touch.posX < (_drawBuff->bass_boost.x + _drawBuff->bass_boost.width + 10)) && \
(touch.posY > (_drawBuff->bass_boost.y - 10) && touch.posY < (_drawBuff->bass_boost.y + _drawBuff->bass_boost.height + 10))){ //
Update_Bass_Boost_Icon(bass_boost_mode = ++bass_boost_mode % 4);
return 31;
}
if((touch.posX > (_drawBuff->reverb_effect.x - 10) && touch.posX < (_drawBuff->reverb_effect.x + _drawBuff->reverb_effect.width + 10)) && \
(touch.posY > (_drawBuff->reverb_effect.y - 10) && touch.posY < (_drawBuff->reverb_effect.y + _drawBuff->reverb_effect.height + 10))){ //
Update_Reverb_Effect_Icon(reverb_effect_mode = ++reverb_effect_mode % 4);
return 32;
}
if((touch.posX > (_drawBuff->vocal_cancel.x - 5) && touch.posX < (_drawBuff->vocal_cancel.x + _drawBuff->vocal_cancel.width + 5)) && \
(touch.posY > (_drawBuff->vocal_cancel.y - 10) && touch.posY < (_drawBuff->vocal_cancel.y + _drawBuff->vocal_cancel.height + 10))){ //
Update_Vocal_Canceler_Icon(vocal_cancel_mode = ++vocal_cancel_mode % 2);
return 33;
}
if((touch.posX > (_drawBuff->fft_analyzer_left.x - 5) && touch.posX < (_drawBuff->fft_analyzer_left.x + _drawBuff->fft_analyzer_left.width + 5)) && \
(touch.posY > (_drawBuff->fft_analyzer_left.y - 10) && touch.posY < (_drawBuff->fft_analyzer_left.y + _drawBuff->fft_analyzer_left.height + 10))){ //
if(++settings_group.music_conf.b.fft_bar_color_idx >= settings_item_fft_color_type.item_count){
settings_group.music_conf.b.fft_bar_color_idx = 0;
}
return 34;
}
if((touch.posX > (_drawBuff->fft_analyzer_right.x + 5) && touch.posX < (_drawBuff->fft_analyzer_right.x + _drawBuff->fft_analyzer_right.width + 5)) && \
(touch.posY > (_drawBuff->fft_analyzer_right.y - 10) && touch.posY < (_drawBuff->fft_analyzer_right.y + _drawBuff->fft_analyzer_right.height + 10))){ //
if(++settings_group.music_conf.b.fft_bar_type >= settings_item_fft_bar_type.item_count){
settings_group.music_conf.b.fft_bar_type = 0;
}
return 35;
}
if(touch.posY < (_drawBuff->posision.y - 10)){
return 30;
}
DMA_Cmd(DMA1_Stream1, DISABLE);
DMA_ITConfig(DMA1_Stream1, DMA_IT_TC | DMA_IT_HT, DISABLE);
AUDIO_OUT_SHUTDOWN;
// clear FFT analyzer left
LCDPutBuffToBgImg(_drawBuff->fft_analyzer_left.x, _drawBuff->fft_analyzer_left.y, \
_drawBuff->fft_analyzer_left.width, _drawBuff->fft_analyzer_left.height, _drawBuff->fft_analyzer_left.p);
// clear FFT analyzer right
LCDPutBuffToBgImg(_drawBuff->fft_analyzer_right.x, _drawBuff->fft_analyzer_right.y, \
_drawBuff->fft_analyzer_right.width, _drawBuff->fft_analyzer_right.height, _drawBuff->fft_analyzer_right.p);
if((touch.posX > 10 && touch.posX < 50) && (touch.posY > 193 && touch.posY < 235)){ // 停止アイコン
debug.printf("\r\nplay abort");
return RET_PLAY_STOP;
}
if((touch.posX > 180 && touch.posX < 230) && (touch.posY > 190 && touch.posY < 230)){ // 次へアイコン
debug.printf("\r\nplay abort & next");
return RET_PLAY_NEXT;
}
if((touch.posX > 90 && touch.posX < 140) && (touch.posY > 190 && touch.posY < 230)){ // 前へアイコン
debug.printf("\r\nplay abort & prev");
return RET_PLAY_PREV;
}
debug.printf("\r\npaused");
LCDPutBuffToBgImg(_drawBuff->navigation.x, _drawBuff->navigation.y, \
_drawBuff->navigation.width, _drawBuff->navigation.height, _drawBuff->navigation.p);
LCDPutIcon(_drawBuff->navigation.x, _drawBuff->navigation.y, \
_drawBuff->navigation.width, _drawBuff->navigation.height, \
navigation_playing_patch_32x32, navigation_playing_patch_32x32_alpha);
touch.func = musicTouch;
music_src_p.done = 0;
music_src_p.offset = 0;
TOUCH_PINIRQ_ENABLE;
TouchPenIRQ_Enable();
while(music_src_p.done == 0){};
TouchPenIRQ_Disable();
TOUCH_PINIRQ_DISABLE;
touch.func = touch_empty_func;
if(music_src_p.done != 1){
return music_src_p.done;
}
return ret;
}
void make_shuffle_table(unsigned int seed){
int i, j;
uint8_t rnd;
static uint8_t rand_table[256];
srand(seed);
if(!shuffle_play.flag_make_rand){
shuffle_play.pRandIdEntry = rand_table;
shuffle_play.flag_make_rand = 1;
}
shuffle_play.pRandIdEntry[1] = rand() % (fat.fileCnt - 1) + 1;
for(j = 2;j <= (fat.fileCnt - 1);j++){
LOOP:
rnd = rand() % (fat.fileCnt - 1) + 1;
for(i = 1;i < j;i++){
if(shuffle_play.pRandIdEntry[i] == rnd){
goto LOOP;
}
}
shuffle_play.pRandIdEntry[j] = rnd;
}
}
int PlayMusic(int id){
int idNext, idCopy = id;
unsigned int seed;
if(navigation_loop_mode == NAV_SHUFFLE_PLAY){
if(!shuffle_play.mode_changed){
idNext = id;
if(++idNext >= fat.fileCnt){
idNext = 1;
}
seed = TIM8->CNT;
do{
make_shuffle_table(seed);
seed += 100;
}while((id == shuffle_play.pRandIdEntry[idNext]) && (fat.fileCnt > 2));
}
if(shuffle_play.play_continuous){
id = shuffle_play.pRandIdEntry[id];
}
shuffle_play.mode_changed = 1;
}
shuffle_play.play_continuous = 1;
uint16_t entryPointOffset = getListEntryPoint(id);
if(fbuf[entryPointOffset + 8] != 0x20){
char fileTypeStr[4];
memset(fileTypeStr, '\0', sizeof(fileTypeStr));
strncpy(fileTypeStr, (char*)&fbuf[entryPointOffset + 8], 3);
if(strcmp(fileTypeStr, "MP4") == 0 || \
strcmp(fileTypeStr, "M4A") == 0 || \
strcmp(fileTypeStr, "M4P") == 0)
{
return PlayAAC(id);
} else if(strcmp(fileTypeStr, "MP3") == 0){
return PlayMP3(id);
} else if(strcmp(fileTypeStr, "WAV") == 0){
return PlaySound(id);
} else if(strcmp(fileTypeStr, "MOV") == 0){
return PlayMotionJpeg(id);
}
}
id = idCopy;
if((navigation_loop_mode == NAV_INFINITE_PLAY_ENTIRE) || (navigation_loop_mode == NAV_SHUFFLE_PLAY) || id <= fat.fileCnt){
LCDStatusStruct.waitExitKey = 1;
return RET_PLAY_NEXT;
} else {
LCDStatusStruct.waitExitKey = 0;
return RET_PLAY_INVALID;
}
}
|
1137519-player
|
sound.c
|
C
|
lgpl
| 42,284
|
.section ".rodata"
.balign 2
.global internal_flash_pcf_font
internal_flash_pcf_font:
.incbin "mplus_1c_bold_basic_latin.pcf"
.global _sizeof_internal_flash_pcf_font
.set _sizeof_internal_flash_pcf_font, . - internal_flash_pcf_font
.balign 2
.global video_info_board_170x170
video_info_board_170x170:
.incbin "video_info_board_170x170.bin"
.global _sizeof_video_info_board_170x170
.set _sizeof_video_info_board_170x170, . - video_info_board_170x170
.balign 2
.global video_info_board_170x170_alpha
video_info_board_170x170_alpha:
.incbin "video_info_board_170x170_alpha.bin"
.global _sizeof_video_info_board_170x170_alpha
.set _sizeof_video_info_board_170x170_alpha, . - video_info_board_170x170_alpha
.balign 2
.global video_info_26x24
video_info_26x24:
.incbin "video_info_26x24.bin"
.global _sizeof_video_info_26x24
.set _sizeof_video_info_26x24, . - video_info_26x24
.balign 2
.global video_info_26x24_alpha
video_info_26x24_alpha:
.incbin "video_info_26x24_alpha.bin"
.global _sizeof_video_info_26x24_alpha
.set _sizeof_video_info_26x24_alpha, . - video_info_26x24_alpha
.balign 2
.global music_underbar_320x80
music_underbar_320x80:
.incbin "music_underbar_320x80.bin"
.global _sizeof_music_underbar_320x80
.set _sizeof_music_underbar_320x80, . - music_underbar_320x80
.balign 2
.global music_underbar_320x80_alpha
music_underbar_320x80_alpha:
.incbin "music_underbar_320x80_alpha.bin"
.global _sizeof_music_underbar_320x80_alpha
.set _sizeof_music_underbar_320x80_alpha, . - music_underbar_320x80_alpha
.balign 2
.global music_art_default_74x74
music_art_default_74x74:
.incbin "music_art_default_74x74.bin"
.global _sizeof_music_art_default_74x74
.set _sizeof_music_art_default_74x74, . - music_art_default_74x74
.balign 2
.global seek_circle_16x16
seek_circle_16x16:
.incbin "seek_circle_16x16.bin"
.global _sizeof_seek_circle_16x16
.set _sizeof_seek_circle_16x16, . - seek_circle_16x16
.balign 2
.global seek_circle_16x16_alpha
seek_circle_16x16_alpha:
.incbin "seek_circle_16x16_alpha.bin"
.global _sizeof_seek_circle_16x16_alpha
.set _sizeof_seek_circle_16x16_alpha, . - seek_circle_16x16_alpha
.balign 2
.global play_icon_40x40
play_icon_40x40:
.incbin "play_icon_40x40.bin"
.global _sizeof_play_icon_40x40
.set _sizeof_play_icon_40x40, . - play_icon_40x40
.balign 2
.global play_icon_40x40_alpha
play_icon_40x40_alpha:
.incbin "play_icon_40x40_alpha.bin"
.global _sizeof_play_icon_40x40_alpha
.set _sizeof_play_icon_40x40_alpha, . - play_icon_40x40_alpha
.balign 2
.global abort_icon_40x40
abort_icon_40x40:
.incbin "abort_icon_40x40.bin"
.global _sizeof_abort_icon_40x40
.set _sizeof_abort_icon_40x40, . - abort_icon_40x40
.balign 2
.global next_right_32x17
next_right_32x17:
.incbin "next_right_32x17.bin"
.global _sizeof_next_right_32x17
.set _sizeof_next_right_32x17, . - next_right_32x17
.balign 2
.global next_right_32x17_alpha
next_right_32x17_alpha:
.incbin "next_right_32x17_alpha.bin"
.global _sizeof_next_right_32x17_alpha
.set _sizeof_next_right_32x17_alpha, . -next_right_32x17_alpha
.balign 2
.global next_left_32x17
next_left_32x17:
.incbin "next_left_32x17.bin"
.global _sizeof_next_left_32x17
.set _sizeof_next_left_32x17, . -next_left_32x17
.balign 2
.global next_left_32x17_alpha
next_left_32x17_alpha:
.incbin "next_left_32x17_alpha.bin"
.global _sizeof_next_left_32x17_alpha
.set _sizeof_next_left_32x17_alpha, . -next_left_32x17_alpha
.balign 2
.global exit_play_20x13
exit_play_20x13:
.incbin "exit_play_20x13.bin"
.global _sizeof_exit_play_20x13
.set _sizeof_exit_play_20x13, . -exit_play_20x13
.balign 2
.global exit_play_20x13_alpha
exit_play_20x13_alpha:
.incbin "exit_play_20x13_alpha.bin"
.global _sizeof_exit_play_20x13_alpha
.set _sizeof_exit_play_20x13_alpha, . -exit_play_20x13_alpha
.balign 2
.global menubar_320x22
menubar_320x22:
.incbin "menubar_320x22.bin"
.global _sizeof_menubar_320x22
.set _sizeof_menubar_320x22, . -menubar_320x22
.balign 2
.global menubar_320x22_alpha
menubar_320x22_alpha:
.incbin "menubar_320x22_alpha.bin"
.global _sizeof_menubar_320x22_alpha
.set _sizeof_menubar_320x22_alpha, . -menubar_320x22_alpha
.balign 2
.global pic_right_arrow_30x30
pic_right_arrow_30x30:
.incbin "pic_right_arrow_30x30.bin"
.global _sizeof_pic_right_arrow_30x30
.set _sizeof_pic_right_arrow_30x30, . -pic_right_arrow_30x30
.balign 2
.global pic_right_arrow_30x30_alpha
pic_right_arrow_30x30_alpha:
.incbin "pic_right_arrow_30x30_alpha.bin"
.global _sizeof_pic_right_arrow_30x30_alpha
.set _sizeof_pic_right_arrow_30x30_alpha, . -pic_right_arrow_30x30_alpha
.balign 2
.global pic_left_arrow_30x30
pic_left_arrow_30x30:
.incbin "pic_left_arrow_30x30.bin"
.global _sizeof_pic_left_arrow_30x30
.set _sizeof_pic_left_arrow_30x30, . -pic_left_arrow_30x30
.balign 2
.global pic_left_arrow_30x30_alpha
pic_left_arrow_30x30_alpha:
.incbin "pic_left_arrow_30x30_alpha.bin"
.global _sizeof_pic_left_arrow_30x30_alpha
.set _sizeof_pic_left_arrow_30x30_alpha, . -pic_left_arrow_30x30_alpha
.balign 2
.global bass_base_24x18
bass_base_24x18:
.incbin "bass_base_24x18.bin"
.global _sizeof_bass_base_24x18
.set _sizeof_bass_base_24x18, . -bass_base_24x18
.balign 2
.global bass_base_24x18_alpha
bass_base_24x18_alpha:
.incbin "bass_base_24x18_alpha.bin"
.global _sizeof_bass_base_24x18_alpha
.set _sizeof_bass_base_24x18_alpha, . -bass_base_24x18_alpha
.balign 2
.global bass_level1_24x18
bass_level1_24x18:
.incbin "bass_level1_24x18.bin"
.global _sizeof_bass_level1_24x18
.set _sizeof_bass_level1_24x18, . -bass_level1_24x18
.balign 2
.global bass_level1_24x18_alpha
bass_level1_24x18_alpha:
.incbin "bass_level1_24x18_alpha.bin"
.global _sizeof_bass_level1_24x18_alpha
.set _sizeof_bass_level1_24x18_alpha, . -bass_level1_24x18_alpha
.balign 2
.global bass_level2_24x18
bass_level2_24x18:
.incbin "bass_level2_24x18.bin"
.global _sizeof_bass_level2_24x18
.set _sizeof_bass_level2_24x18, . -bass_level2_24x18
.balign 2
.global bass_level2_24x18_alpha
bass_level2_24x18_alpha:
.incbin "bass_level2_24x18_alpha.bin"
.global _sizeof_bass_level2_24x18_alpha
.set _sizeof_bass_level2_24x18_alpha, . -bass_level2_24x18_alpha
.balign 2
.global bass_level3_24x18
bass_level3_24x18:
.incbin "bass_level3_24x18.bin"
.global _sizeof_bass_level3_24x18
.set _sizeof_bass_level3_24x18, . -bass_level3_24x18
.balign 2
.global bass_level3_24x18_alpha
bass_level3_24x18_alpha:
.incbin "bass_level3_24x18_alpha.bin"
.global _sizeof_bass_level3_24x18_alpha
.set _sizeof_bass_level3_24x18_alpha, . -bass_level3_24x18_alpha
.balign 2
.global reverb_base_24x18
reverb_base_24x18:
.incbin "reverb_base_24x18.bin"
.global _sizeof_reverb_base_24x18
.set _sizeof_reverb_base_24x18, . -reverb_base_24x18
.balign 2
.global reverb_base_24x18_alpha
reverb_base_24x18_alpha:
.incbin "reverb_base_24x18_alpha.bin"
.global _sizeof_reverb_base_24x18_alpha
.set _sizeof_reverb_base_24x18_alpha, . -reverb_base_24x18_alpha
.balign 2
.global reverb_level1_24x18
reverb_level1_24x18:
.incbin "reverb_level1_24x18.bin"
.global _sizeof_reverb_level1_24x18
.set _sizeof_reverb_level1_24x18, . -reverb_level1_24x18
.balign 2
.global reverb_level1_24x18_alpha
reverb_level1_24x18_alpha:
.incbin "reverb_level1_24x18_alpha.bin"
.global _sizeof_reverb_level1_24x18_alpha
.set _sizeof_reverb_level1_24x18_alpha, . -reverb_level1_24x18_alpha
.balign 2
.global reverb_level2_24x18
reverb_level2_24x18:
.incbin "reverb_level2_24x18.bin"
.global _sizeof_reverb_level2_24x18
.set _sizeof_reverb_level2_24x18, . -reverb_level2_24x18
.balign 2
.global reverb_level2_24x18_alpha
reverb_level2_24x18_alpha:
.incbin "reverb_level2_24x18_alpha.bin"
.global _sizeof_reverb_level2_24x18_alpha
.set _sizeof_reverb_level2_24x18_alpha, . -reverb_level2_24x18_alpha
.balign 2
.global reverb_level3_24x18
reverb_level3_24x18:
.incbin "reverb_level3_24x18.bin"
.global _sizeof_reverb_level3_24x18
.set _sizeof_reverb_level3_24x18, . -reverb_level3_24x18
.balign 2
.global reverb_level3_24x18_alpha
reverb_level3_24x18_alpha:
.incbin "reverb_level3_24x18_alpha.bin"
.global _sizeof_reverb_level3_24x18_alpha
.set _sizeof_reverb_level3_24x18_alpha, . -reverb_level3_24x18_alpha
.balign 2
.global vocal_base_24x18
vocal_base_24x18:
.incbin "vocal_base_24x18.bin"
.global _sizeof_vocal_base_24x18
.set _sizeof_vocal_base_24x18, . -vocal_base_24x18
.balign 2
.global vocal_base_24x18_alpha
vocal_base_24x18_alpha:
.incbin "vocal_base_24x18_alpha.bin"
.global _sizeof_vocal_base_24x18_alpha
.set _sizeof_vocal_base_24x18_alpha, . -vocal_base_24x18_alpha
.balign 2
.global vocal_canceled_24x18
vocal_canceled_24x18:
.incbin "vocal_canceled_24x18.bin"
.global _sizeof_vocal_canceled_24x18
.set _sizeof_vocal_canceled_24x18, . -vocal_canceled_24x18
.balign 2
.global vocal_canceled_24x18_alpha
vocal_canceled_24x18_alpha:
.incbin "vocal_canceled_24x18_alpha.bin"
.global _sizeof_vocal_canceled_24x18_alpha
.set _sizeof_vocal_canceled_24x18_alpha, . -vocal_canceled_24x18_alpha
.balign 2
.global radiobutton_checked_22x22
radiobutton_checked_22x22:
.incbin "radiobutton_checked_22x22.bin"
.global _sizeof_radiobutton_checked_22x22
.set _sizeof_radiobutton_checked_22x22, . -radiobutton_checked_22x22
.balign 2
.global radiobutton_unchecked_22x22
radiobutton_unchecked_22x22:
.incbin "radiobutton_unchecked_22x22.bin"
.global _sizeof_radiobutton_unchecked_22x22
.set _sizeof_radiobutton_unchecked_22x22, . -radiobutton_unchecked_22x22
.balign 2
.global radiobutton_22x22_alpha
radiobutton_22x22_alpha:
.incbin "radiobutton_22x22_alpha.bin"
.global _sizeof_radiobutton_22x22_alpha
.set _sizeof_radiobutton_22x22_alpha, . -radiobutton_22x22_alpha
.balign 2
.global card_22x22
card_22x22:
.incbin "card_22x22.bin"
.global _sizeof_card_22x22
.set _sizeof_card_22x22, . -card_22x22
.balign 2
.global card_22x22_alpha
card_22x22_alpha:
.incbin "card_22x22_alpha.bin"
.global _sizeof_card_22x22_alpha
.set _sizeof_card_22x22_alpha, . -card_22x22_alpha
.balign 2
.global cpu_22x22
cpu_22x22:
.incbin "cpu_22x22.bin"
.global _sizeof_cpu_22x22
.set _sizeof_cpu_22x22, . -cpu_22x22
.balign 2
.global cpu_22x22_alpha
cpu_22x22_alpha:
.incbin "cpu_22x22_alpha.bin"
.global _sizeof_cpu_22x22_alpha
.set _sizeof_cpu_22x22_alpha, . -cpu_22x22_alpha
.balign 2
.global display_22x22
display_22x22:
.incbin "display_22x22.bin"
.global _sizeof_display_22x22
.set _sizeof_display_22x22, . -display_22x22
.balign 2
.global display_22x22_alpha
display_22x22_alpha:
.incbin "display_22x22_alpha.bin"
.global _sizeof_display_22x22_alpha
.set _sizeof_display_22x22_alpha, . -display_22x22_alpha
.balign 2
.global debug_22x22
debug_22x22:
.incbin "debug_22x22.bin"
.global _sizeof_debug_22x22
.set _sizeof_debug_22x22, . -debug_22x22
.balign 2
.global debug_22x22_alpha
debug_22x22_alpha:
.incbin "debug_22x22_alpha.bin"
.global _sizeof_debug_22x22_alpha
.set _sizeof_debug_22x22_alpha, . -debug_22x22_alpha
.balign 2
.global info_22x22
info_22x22:
.incbin "info_22x22.bin"
.global _sizeof_info_22x22
.set _sizeof_info_22x22, . -info_22x22
.balign 2
.global info_22x22_alpha
info_22x22_alpha:
.incbin "info_22x22_alpha.bin"
.global _sizeof_info_22x22_alpha
.set _sizeof_info_22x22_alpha, . -info_22x22_alpha
.balign 2
.global parent_arrow_22x22
parent_arrow_22x22:
.incbin "parent_arrow_22x22.bin"
.global _sizeof_parent_arrow_22x22
.set _sizeof_parent_arrow_22x22, . -parent_arrow_22x22
.balign 2
.global parent_arrow_22x22_alpha
parent_arrow_22x22_alpha:
.incbin "parent_arrow_22x22_alpha.bin"
.global _sizeof_parent_arrow_22x22_alpha
.set _sizeof_parent_arrow_22x22_alpha, . -parent_arrow_22x22_alpha
.balign 2
.global select_22x22
select_22x22:
.incbin "select_22x22.bin"
.global _sizeof_select_22x22
.set _sizeof_select_22x22, . -select_22x22
.balign 2
.global select_22x22_alpha
select_22x22_alpha:
.incbin "select_22x22_alpha.bin"
.global _sizeof_select_22x22_alpha
.set _sizeof_select_22x22_alpha, . -select_22x22_alpha
.balign 2
.global usb_22x22
usb_22x22:
.incbin "usb_22x22.bin"
.global _sizeof_usb_22x22
.set _sizeof_usb_22x22, . -usb_22x22
.balign 2
.global usb_22x22_alpha
usb_22x22_alpha:
.incbin "usb_22x22_alpha.bin"
.global _sizeof_usb_22x22_alpha
.set _sizeof_usb_22x22_alpha, . -usb_22x22_alpha
.balign 2
.global connect_22x22
connect_22x22:
.incbin "connect_22x22.bin"
.global _sizeof_connect_22x22
.set _sizeof_connect_22x22, . -connect_22x22
.balign 2
.global connect_22x22_alpha
connect_22x22_alpha:
.incbin "connect_22x22_alpha.bin"
.global _sizeof_connect_22x22_alpha
.set _sizeof_connect_22x22_alpha, . -connect_22x22_alpha
.balign 2
.global jpeg_22x22
jpeg_22x22:
.incbin "jpeg_22x22.bin"
.global _sizeof_jpeg_22x22
.set _sizeof_jpeg_22x22, . -jpeg_22x22
.balign 2
.global jpeg_22x22_alpha
jpeg_22x22_alpha:
.incbin "jpeg_22x22_alpha.bin"
.global _sizeof_jpeg_22x22_alpha
.set _sizeof_jpeg_22x22_alpha, . -jpeg_22x22_alpha
.balign 2
.global settings_22x22
settings_22x22:
.incbin "settings_22x22.bin"
.global _sizeof_settings_22x22
.set _sizeof_settings_22x22, . -settings_22x22
.balign 2
.global settings_22x22_alpha
settings_22x22_alpha:
.incbin "settings_22x22_alpha.bin"
.global _sizeof_settings_22x22_alpha
.set _sizeof_settings_22x22_alpha, . -settings_22x22_alpha
.balign 2
.global folder_22x22
folder_22x22:
.incbin "folder_22x22.bin"
.global _sizeof_folder_22x22
.set _sizeof_folder_22x22, . -folder_22x22
.balign 2
.global folder_22x22_alpha
folder_22x22_alpha:
.incbin "folder_22x22_alpha.bin"
.global _sizeof_folder_22x22_alpha
.set _sizeof_folder_22x22_alpha, . -folder_22x22_alpha
.balign 2
.global onpu_22x22
onpu_22x22:
.incbin "onpu_22x22.bin"
.global _sizeof_onpu_22x22
.set _sizeof_onpu_22x22, . -onpu_22x22
.balign 2
.global onpu_22x22_alpha
onpu_22x22_alpha:
.incbin "onpu_22x22_alpha.bin"
.global _sizeof_onpu_22x22_alpha
.set _sizeof_onpu_22x22_alpha, . -onpu_22x22_alpha
.balign 2
.global movie_22x22
movie_22x22:
.incbin "movie_22x22.bin"
.global _sizeof_movie_22x22
.set _sizeof_movie_22x22, . -movie_22x22
.balign 2
.global movie_22x22_alpha
movie_22x22_alpha:
.incbin "movie_22x22_alpha.bin"
.global _sizeof_movie_22x22_alpha
.set _sizeof_movie_22x22_alpha, . -movie_22x22_alpha
.balign 2
.global font_22x22
font_22x22:
.incbin "font_22x22.bin"
.global _sizeof_font_22x22
.set _sizeof_font_22x22, . -font_22x22
.balign 2
.global font_22x22_alpha
font_22x22_alpha:
.incbin "font_22x22_alpha.bin"
.global _sizeof_font_22x22_alpha
.set _sizeof_font_22x22_alpha, . -font_22x22_alpha
.balign 2
.global archive_22x22
archive_22x22:
.incbin "archive_22x22.bin"
.global _sizeof_archive_22x22
.set _sizeof_archive_22x22, . -archive_22x22
.balign 2
.global archive_22x22_alpha
archive_22x22_alpha:
.incbin "archive_22x22_alpha.bin"
.global _sizeof_archive_22x22_alpha
.set _sizeof_archive_22x22_alpha, . -archive_22x22_alpha
.balign 2
.global scrollbar_top_6x7
scrollbar_top_6x7:
.incbin "scrollbar_top_6x7.bin"
.global _sizeof_scrollbar_top_6x7
.set _sizeof_scrollbar_top_6x7, . -scrollbar_top_6x7
.balign 2
.global scrollbar_top_6x7_alpha
scrollbar_top_6x7_alpha:
.incbin "scrollbar_top_6x7_alpha.bin"
.global _sizeof_scrollbar_top_6x7_alpha
.set _sizeof_scrollbar_top_6x7_alpha, . -scrollbar_top_6x7_alpha
.balign 2
.global scrollbar_6x204
scrollbar_6x204:
.incbin "scrollbar_6x204.bin"
.global _sizeof_scrollbar_6x204
.set _sizeof_scrollbar_6x204, . -scrollbar_6x204
.balign 2
.global scrollbar_6x204_alpha
scrollbar_6x204_alpha:
.incbin "scrollbar_6x204_alpha.bin"
.global _sizeof_scrollbar_6x204_alpha
.set _sizeof_scrollbar_6x204_alpha, . -scrollbar_6x204_alpha
.balign 2
.global scrollbar_bottom_6x7
scrollbar_bottom_6x7:
.incbin "scrollbar_bottom_6x7.bin"
.global _sizeof_scrollbar_bottom_6x7
.set _sizeof_scrollbar_bottom_6x7, . -scrollbar_bottom_6x7
.balign 2
.global scrollbar_bottom_6x7_alpha
scrollbar_bottom_6x7_alpha:
.incbin "scrollbar_bottom_6x7_alpha.bin"
.global _sizeof_scrollbar_bottom_6x7_alpha
.set _sizeof_scrollbar_bottom_6x7_alpha, . -scrollbar_bottom_6x7_alpha
.balign 2
.global scrollbar_hline_6x1
scrollbar_hline_6x1:
.incbin "scrollbar_hline_6x1.bin"
.global _sizeof_scrollbar_hline_6x1
.set _sizeof_scrollbar_hline_6x1, . -scrollbar_hline_6x1
.balign 2
.global scrollbar_hline_6x1_alpha
scrollbar_hline_6x1_alpha:
.incbin "scrollbar_hline_6x1_alpha.bin"
.global _sizeof_scrollbar_hline_6x1_alpha
.set _sizeof_scrollbar_hline_6x1_alpha, . -scrollbar_hline_6x1_alpha
.balign 2
.global pic_pref_30x30
pic_pref_30x30:
.incbin "pic_pref_30x30.bin"
.global _sizeof_pic_pref_30x30
.set _sizeof_pic_pref_30x30, . -pic_pref_30x30
.balign 2
.global pic_pref_30x30_alpha
pic_pref_30x30_alpha:
.incbin "pic_pref_30x30_alpha.bin"
.global _sizeof_pic_pref_30x30_alpha
.set _sizeof_pic_pref_30x30_alpha, . -pic_pref_30x30_alpha
.balign 2
.global copy_image_to_100x24
copy_image_to_100x24:
.incbin "copy_image_to_100x24.bin"
.global _sizeof_copy_image_to_100x24
.set _sizeof_copy_image_to_100x24, . -copy_image_to_100x24
.balign 2
.global copy_image_to_100x24_alpha
copy_image_to_100x24_alpha:
.incbin "copy_image_to_100x24_alpha.bin"
.global _sizeof_copy_image_to_100x24_alpha
.set _sizeof_copy_image_to_100x24_alpha, . -copy_image_to_100x24_alpha
.balign 2
.global copy_image_to_music_100x24
copy_image_to_music_100x24:
.incbin "copy_image_to_music_100x24.bin"
.global _sizeof_copy_image_to_music_100x24
.set _sizeof_copy_image_to_music_100x24, . -copy_image_to_music_100x24
.balign 2
.global copy_image_to_filer_100x24
copy_image_to_filer_100x24:
.incbin "copy_image_to_filer_100x24.bin"
.global _sizeof_copy_image_to_filer_100x24
.set _sizeof_copy_image_to_filer_100x24, . -copy_image_to_filer_100x24
.balign 2
.global navigation_playing_patch_32x32
navigation_playing_patch_32x32:
.incbin "navigation_playing_patch_32x32.bin"
.global _sizeof_navigation_playing_patch_32x32
.set _sizeof_navigation_playing_patch_32x32, . -navigation_playing_patch_32x32
.balign 2
.global navigation_playing_patch_32x32_alpha
navigation_playing_patch_32x32_alpha:
.incbin "navigation_playing_patch_32x32_alpha.bin"
.global _sizeof_navigation_playing_patch_32x32_alpha
.set _sizeof_navigation_playing_patch_32x32_alpha, . -navigation_playing_patch_32x32_alpha
.balign 2
.global navigation_pause_patch_32x32
navigation_pause_patch_32x32:
.incbin "navigation_pause_patch_32x32.bin"
.global _sizeof_navigation_pause_patch_32x32
.set _sizeof_navigation_pause_patch_32x32, . -navigation_pause_patch_32x32
.balign 2
.global navigation_pause_patch_32x32_alpha
navigation_pause_patch_32x32_alpha:
.incbin "navigation_pause_patch_32x32_alpha.bin"
.global _sizeof_navigation_pause_patch_32x32_alpha
.set _sizeof_navigation_pause_patch_32x32_alpha, . -navigation_pause_patch_32x32_alpha
.balign 2
.global navigation_bar_24x18
navigation_bar_24x18:
.incbin "navigation_bar_24x18.bin"
.global _sizeof_navigation_bar_24x18
.set _sizeof_navigation_bar_24x18, . -navigation_bar_24x18
.balign 2
.global navigation_bar_24x18_alpha
navigation_bar_24x18_alpha:
.incbin "navigation_bar_24x18_alpha.bin"
.global _sizeof_navigation_bar_24x18_alpha
.set _sizeof_navigation_bar_24x18_alpha, . -navigation_bar_24x18_alpha
.balign 2
.global navigation_entire_loop_24x18
navigation_entire_loop_24x18:
.incbin "navigation_entire_loop_24x18.bin"
.global _sizeof_navigation_entire_loop_24x18
.set _sizeof_navigation_entire_loop_24x18, . -navigation_entire_loop_24x18
.balign 2
.global navigation_entire_loop_24x18_alpha
navigation_entire_loop_24x18_alpha:
.incbin "navigation_entire_loop_24x18_alpha.bin"
.global _sizeof_navigation_entire_loop_24x18_alpha
.set _sizeof_navigation_entire_loop_24x18_alpha, . -navigation_entire_loop_24x18_alpha
.balign 2
.global navigation_infinite_entire_loop_24x18
navigation_infinite_entire_loop_24x18:
.incbin "navigation_infinite_entire_loop_24x18.bin"
.global _sizeof_navigation_infinite_entire_loop_24x18
.set _sizeof_navigation_infinite_entire_loop_24x18, . -navigation_infinite_entire_loop_24x18
.balign 2
.global navigation_infinite_entire_loop_24x18_alpha
navigation_infinite_entire_loop_24x18_alpha:
.incbin "navigation_infinite_entire_loop_24x18_alpha.bin"
.global _sizeof_navigation_infinite_entire_loop_24x18_alpha
.set _sizeof_navigation_infinite_entire_loop_24x18_alpha, . -navigation_infinite_entire_loop_24x18_alpha
.balign 2
.global navigation_one_loop_24x18
navigation_one_loop_24x18:
.incbin "navigation_one_loop_24x18.bin"
.global _sizeof_navigation_one_loop_24x18
.set _sizeof_navigation_one_loop_24x18, . -navigation_one_loop_24x18
.balign 2
.global navigation_one_loop_24x18_alpha
navigation_one_loop_24x18_alpha:
.incbin "navigation_one_loop_24x18_alpha.bin"
.global _sizeof_navigation_one_loop_24x18_alpha
.set _sizeof_navigation_one_loop_24x18_alpha, . -navigation_one_loop_24x18_alpha
.balign 2
.global navigation_shuffle_24x18
navigation_shuffle_24x18:
.incbin "navigation_shuffle_24x18.bin"
.global _sizeof_navigation_shuffle_24x18
.set _sizeof_navigation_shuffle_24x18, . -navigation_shuffle_24x18
.balign 2
.global navigation_shuffle_24x18_alpha
navigation_shuffle_24x18_alpha:
.incbin "navigation_shuffle_24x18_alpha.bin"
.global _sizeof_navigation_shuffle_24x18_alpha
.set _sizeof_navigation_shuffle_24x18_alpha, . -navigation_shuffle_24x18_alpha
.section ".text"
|
1137519-player
|
images.s
|
Unix Assembly
|
lgpl
| 21,124
|
#include "stm32f4xx_conf.h"
#include "lcd.h"
#include "usart.h"
#include "delay.h"
#include <string.h>
#include "xmodem.h"
volatile uint32_t timeout;
volatile uint8_t Crcflg, seqno;
void TIM2_IRQHandler(void){
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
timeout++;
}
int16_t usart_polling_timeout(uint32_t t) /* タイムアウト付きUSARTポーリング */
{
while(!(USART3->SR & USART_FLAG_RXNE)){
if(timeout > t) return -1;
}
return USART3->DR;
}
void xmodem_init()
{
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
/* Enable the TIM2 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* 1Hz = CK_INT(F_APB1(F_CPU(168MHz) / APB_PSC(4)) * 2) / TIM_PSC(10000) */
/* CK_INT = F_CPU(168MHz) / APB_PSC(4) * 2 = 84MHz */
/* COUNT10ms = 10ms / 1/84MHz = 840000 */
TIM_TimeBaseInitStructure.TIM_Period = ((SystemCoreClock / 4) * 2) / 10000 - 1;
TIM_TimeBaseInitStructure.TIM_Prescaler = 100 - 1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);
TIM_Cmd(TIM2, ENABLE);
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
TIM_ITConfig(TIM2, TIM_IT_Update, DISABLE);
}
int xmodem_start_session()
{
NVIC_InitTypeDef NVIC_InitStructure;
uint8_t retry = 0;
seqno = 1;
debug.printf("\r\nstarting session...\r\n");
USART_ITConfig(USART3, USART_IT_RXNE, DISABLE); /* USART受信割り込み一時停止 */
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); /* TIM2割り込み許可 */
WAIT_NACK:
timeout = 0;
switch(usart_polling_timeout(WAIT_NACK_TIMEOUT)){ /* 接続要求待ち */
case NAK: /* NAK受信 Checksum ブロック送信へ*/
Crcflg = FALSE;
return 1;
case 'C': /* C文字受信 CRC ブロック送信へ*/
Crcflg = TRUE;
return 1;
case CAN: /* CANまたはETX受信 XMODEM終了 */
case ETX:
break;
case -1: /* タイムアウト 接続要求待ちへ */
default:
if(++retry <= WAIT_NACK_RETRY) goto WAIT_NACK;
break;
}
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE); /* USART受信割り込み再開 */
TIM_ITConfig(TIM2, TIM_IT_Update, DISABLE); /* TIM2割り込み停止 */
/* Disable the TIM2 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
NVIC_Init(&NVIC_InitStructure);
return (-1);
}
int xmodem_transmit(void* p, uint32_t blocks) /* XMODEM送信ルーチン */
{
register uint32_t i, n;
uint8_t xbuf[133], *buf = (uint8_t*)p;
uint8_t retry = 0;
uint16_t crc;
//mmcBlockRead((uint8_t*)fbuf, sector);
for(n = 0;n < blocks;n++){ /* n個のブロックを送信 */
REQ_NACK:
xbuf[HEAD] = SOH; /* SOH付加 */
xbuf[SEQ] = seqno; /* 現在のシーケンス番号付加 */
xbuf[COM] = seqno ^ 255; /* シーケンス番号の補数付加 */
memcpy((uint8_t*)&xbuf[DAT], (uint8_t*)&buf[n * 128], 128);
if(!Crcflg) { /* Checksum計算 */
xbuf[CHK] = 0;
for(i = DAT;i < CHK;i++)
xbuf[CHK] += xbuf[i];
for(i = HEAD;i <= CHK;i++) /* ブロック送出 */
USARTPutData(xbuf[i]);
}
else{ /* CRC計算 */
crc = 0;
for(i = DAT;i < CHK;i++)
// crc = _crc_xmodem_update(crc, xbuf[i]); /* CRCコード生成 */
xbuf[CRCH] = (crc >> 8) & 0x00FF;
xbuf[CRCL] = crc & 0x00FF;
for(i = HEAD;i <= CRCL;i++) /* ブロック送出 */
USARTPutData(xbuf[i]);
}
WAIT_ACK:
timeout = 0;
switch(usart_polling_timeout(WAIT_ACK_TIMEOUT)){ /* ACK応答待ち */
case ACK: /* ACK受信 次のシーケンスへ */
retry = 0;
break;
case NAK: /* NAK受信 ブロック再送 */
if(++retry < REQ_NACK_RETRY) goto REQ_NACK;
goto END;
case CAN: /* CAN受信 XMODEM終了 */
goto END;
case -1: /* タイムアウト CAN送信後 XMODEM終了*/
default:
if(++retry <= WAIT_ACK_RETRY) goto WAIT_ACK;
goto CAN_END;
}
seqno++; /* 次のシーケンス番号に更新 */
retry = 0;
}
return 0;
CAN_END:
USARTPutData(CAN); /* CANを送信して終了 */
END:
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE); /* USART受信割り込み再開 */
TIM_ITConfig(TIM2, TIM_IT_Update, DISABLE); /* TIM2割り込み停止 */
Delayms(100);
return -1;
}
void xmodem_end_session()
{
NVIC_InitTypeDef NVIC_InitStructure;
USARTPutData(EOT); /* ブロック送信完了 EOT送出 */
timeout = 0;
while(usart_polling_timeout(100) != ACK); /* ACK応答待ち */
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE); /* USART受信割り込み再開 */
TIM_ITConfig(TIM2, TIM_IT_Update, DISABLE); /* TIM2割り込み停止 */
/* Disable the TIM2 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
NVIC_Init(&NVIC_InitStructure);
Delayms(100);
}
void xput()
{
const uint8_t bmp_header[] = {
0x42, 0x4d, 0x46, 0x58, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00, 0x38, 0x00,
0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x03, 0x00,
0x00, 0x00, 0x00, 0x58, 0x02, 0x00, 0x13, 0x0b, 0x00, 0x00, 0x13, 0x0b, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x1f, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
uint8_t buf[1024];
int totalPixel = LCD_WIDTH * LCD_HEIGHT + sizeof(bmp_header) / sizeof(uint16_t);
register int i, n, x, y;
uint16_t *p_ram;
debug.printf("\r\nXMODEM");
xmodem_init();
if(xmodem_start_session() == -1){
debug.printf("\r\nsesson timeout...");
return;
}
memcpy((uint8_t*)buf, (uint8_t*)bmp_header, sizeof(bmp_header));
p_ram = (uint16_t*)&buf[sizeof(bmp_header)];
n = ( sizeof(buf) - sizeof(bmp_header) ) / sizeof(uint16_t);
x = 0, y = LCD_HEIGHT - 1;
LCDSetWindowArea(0 ,0, LCD_WIDTH, LCD_HEIGHT);
LCDSetGramAddr(0, LCD_HEIGHT - 1);
LCDPutCmd(0x0022);
LCD->RAM;
do{
for(i = 0;i < n;i++){
*p_ram++ = LCD->RAM;
if(++x >= LCD_WIDTH){
x = 0;
if(--y < 0) y = LCD_HEIGHT - 1;
LCDSetGramAddr(x, y);
LCDPutCmd(0x0022);
LCD->RAM;
}
}
xmodem_transmit((uint8_t*)buf, sizeof(buf) / 128);
totalPixel -= n;
n = sizeof(buf) / sizeof(uint16_t);
p_ram = (uint16_t*)buf;
}while(totalPixel > 0);
xmodem_end_session();
}
|
1137519-player
|
xmodem.c
|
C
|
lgpl
| 6,671
|
/*
* sd.h
*
* Created on: 2011/02/22
* Author: masayuki
*/
#ifndef SD_H_
#define SD_H_
#include "stm32f4xx_conf.h"
#include "fat.h"
/* --- STA Register ---*/
/* Alias word address of RXFIFOHF bit */
#define STA_OFFSET (SDIO_BASE + 0x34)
#define RXFIFOHF_BitNumber 0x0F
#define STA_RXFIFOHF_BB_FLAG (*(uint32_t *)(PERIPH_BB_BASE + (STA_OFFSET * 32) + (RXFIFOHF_BitNumber * 4)))
/* Alias word address of RXDAVL bit */
#define RXDAVL_BitNumber 0x15
#define STA_RXDAVL_BB_FLAG (*(uint32_t *)(PERIPH_BB_BASE + (STA_OFFSET * 32) + (RXDAVL_BitNumber * 4)))
#define SDIO_CMD_STATUS_MASK (SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT | SDIO_FLAG_CCRCFAIL)
#define SDIO_BLOCK_READ_STATUS_MASK (SDIO_FLAG_DATAEND | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_RXOVERR | SDIO_FLAG_STBITERR)
#define CSD_VER_1XX 0
#define CSD_VER_2XX 1
typedef struct{
uint8_t speedClass, csdVer, specVer, busWidth;
uint32_t tranSpeed, maxClkFreq;
uint32_t rca;
uint32_t c_size, c_size_mult, read_bl_len, totalBlocks;
}card_info_typedef;
extern volatile card_info_typedef cardInfo;
static const char specVer[3][9] = {"1.0-1.01", "1.10", "2.00"};
static const char busWidth[6][10] = {"1bit", "", "", "", "", "1bit/4bit"};
static const int tranUnit[] = {100, 1000, 10000, 100000};
static const float timeVal[] = {0, 1.0, 1.2, 1.3, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 7.0, 8.0};
extern int SDInit(void);
uint32_t SDSendCMD(int cmdIdx, uint32_t arg, uint32_t resType, uint32_t *resbuf);
extern inline uint32_t SDBlockRead(void *buf, uint32_t blockAddress);
extern inline uint32_t SDMultiBlockRead(void *buf, uint32_t blockAddress, uint32_t count);
extern int SD_Switch_BusWidth(int width);
#endif /* SD_H_ */
|
1137519-player
|
sd.h
|
C
|
lgpl
| 1,749
|
/*
* fat.h
*
* Created on: 2011/02/27
* Author: Tonsuke
*/
#ifndef C_FILE_H_
#define C_FILE_H_
#include "stm32f4xx_conf.h"
#include <stddef.h>
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
typedef volatile struct C_FILE {
size_t fileSize, \
seekBytes, \
c_file_addr;
} C_FILE;
extern C_FILE* c_fopen(uint32_t fileAddr, size_t fileSize);
extern void c_fclose(C_FILE *fp);
extern int c_fseek(C_FILE *fp, int64_t offset, int whence);
extern size_t c_fread(void *buf, size_t size, size_t count, C_FILE *fp);
#endif /* FAT_H_ */
|
1137519-player
|
cfile.h
|
C
|
lgpl
| 586
|
/**
******************************************************************************
* @file stm32f4_discovery.h
* @author MCD Application Team
* @version V1.1.0
* @date 28-October-2011
* @brief This file contains definitions for STM32F4-Discovery Kit's Leds and
* push-button hardware resources.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4_DISCOVERY_H
#define __STM32F4_DISCOVERY_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx.h"
#include "stm32f4xx_conf.h"
/** @addtogroup Utilities
* @{
*/
/** @addtogroup STM32F4_DISCOVERY
* @{
*/
/** @addtogroup STM32F4_DISCOVERY_LOW_LEVEL
* @{
*/
/** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Exported_Types
* @{
*/
typedef enum
{
LED4 = 0,
LED3 = 1,
LED5 = 2,
LED6 = 3
} Led_TypeDef;
typedef enum
{
BUTTON_USER = 0,
} Button_TypeDef;
typedef enum
{
BUTTON_MODE_GPIO = 0,
BUTTON_MODE_EXTI = 1
} ButtonMode_TypeDef;
/**
* @}
*/
/** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Exported_Constants
* @{
*/
/** @addtogroup STM32F4_DISCOVERY_LOW_LEVEL_LED
* @{
*/
#define LEDn 4
#define LED4_PIN GPIO_Pin_12
#define LED4_GPIO_PORT GPIOD
#define LED4_GPIO_CLK RCC_AHB1Periph_GPIOD
#define LED3_PIN GPIO_Pin_13
#define LED3_GPIO_PORT GPIOD
#define LED3_GPIO_CLK RCC_AHB1Periph_GPIOD
#define LED5_PIN GPIO_Pin_14
#define LED5_GPIO_PORT GPIOD
#define LED5_GPIO_CLK RCC_AHB1Periph_GPIOD
#define LED6_PIN GPIO_Pin_15
#define LED6_GPIO_PORT GPIOD
#define LED6_GPIO_CLK RCC_AHB1Periph_GPIOD
/**
* @}
*/
/** @addtogroup STM32F4_DISCOVERY_LOW_LEVEL_BUTTON
* @{
*/
#define BUTTONn 1
/**
* @brief Wakeup push-button
*/
#define USER_BUTTON_PIN GPIO_Pin_0
#define USER_BUTTON_GPIO_PORT GPIOA
#define USER_BUTTON_GPIO_CLK RCC_AHB1Periph_GPIOA
#define USER_BUTTON_EXTI_LINE EXTI_Line0
#define USER_BUTTON_EXTI_PORT_SOURCE EXTI_PortSourceGPIOA
#define USER_BUTTON_EXTI_PIN_SOURCE EXTI_PinSource0
#define USER_BUTTON_EXTI_IRQn EXTI0_IRQn
/**
* @}
*/
/** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32F4_DISCOVERY_LOW_LEVEL_Exported_Functions
* @{
*/
void STM_EVAL_LEDInit(Led_TypeDef Led);
void STM_EVAL_LEDOn(Led_TypeDef Led);
void STM_EVAL_LEDOff(Led_TypeDef Led);
void STM_EVAL_LEDToggle(Led_TypeDef Led);
void STM_EVAL_PBInit(Button_TypeDef Button, ButtonMode_TypeDef Button_Mode);
uint32_t STM_EVAL_PBGetState(Button_TypeDef Button);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32F4_DISCOVERY_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
|
1137519-player
|
stm32f4_discovery.h
|
C
|
lgpl
| 4,129
|
/*
* mp3.h
*
* Created on: 2012/03/25
* Author: Tonsuke
*/
#ifndef MP3_H_
#define MP3_H_
#include "stm32f4xx_conf.h"
extern int PlayMP3(int id);
#endif /* MP3_H_ */
|
1137519-player
|
mp3.h
|
C
|
lgpl
| 181
|
{\rtf1\ansi\ansicpg932\cocoartf1187\cocoasubrtf370
\cocoascreenfonts1{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fnil\fcharset0 Monaco;}
{\colortbl;\red255\green255\blue255;\red0\green0\blue128;}
\paperw11900\paperh16840\margl1440\margr1440\vieww29100\viewh5100\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\f0\fs24 \cf0 CC=arm-none-eabi-gcc ANSIFLAGS= CFLAGS="-mcpu=
\f1\fs22 cortex-m4 -mthumb -\cf2 mfpu\cf0 =fpv4-sp-d16 -mfloat-\cf2 abi\cf0 =softfp -mlittle-endian -mthumb-interwork
\f0\fs24 -Os -I../ -I../lib/STM32F4xx_StdPeriph_Driver/inc -I../lib/CMSIS/ST/STM32F4xx/Include -I../lib/CMSIS/Include -I/usr/local/arm/arm-none-eabi/include" LDFLAGS="-L../ -L../lib/STM32F4xx_StdPeriph_Driver -L../lib/CMSIS/ST/STM32F4xx -L/usr/local/arm/arm-none-eabi/lib/thumb2 -L/usr/local/arm/lib/gcc/arm-none-eabi/4.4.1/thumb2" LIBS="-lmain
\f1\fs22 -lstd -lcm4 -lc -lgcc
\f0\fs24 " ./configure --host=arm-none-eabi\
\
CC=arm-none-eabi-gcc ANSIFLAGS= CFLAGS="-mcpu=
\f1\fs22 cortex-m4 -mthumb -\cf2 mfpu\cf0 =fpv4-sp-d16 -mfloat-\cf2 abi\cf0 =hard -mlittle-endian -mthumb-interwork
\f0\fs24 -Os -I../ -I../lib/STM32F4xx_StdPeriph_Driver/inc -I../lib/CMSIS/ST/STM32F4xx/Include -I../lib/CMSIS/Include -I/usr/local/arm/arm-none-eabi/include" LDFLAGS="-L../ -L../lib/STM32F4xx_StdPeriph_Driver -L../lib/CMSIS/ST/STM32F4xx -L
\f1\fs22 /usr/local/arm/arm-none-eabi/lib/thumb/cortex-m4/float-abi-hard/fpuv4-sp-d16
\f0\fs24 -L
\f1\fs22 /usr/local/arm/lib/gcc/arm-none-eabi/4.6.2/thumb/cortex-m4/float-abi-hard/fpuv4-sp-d16
\f0\fs24 " LIBS="-lmain
\f1\fs22 -lstd -lcm4 -lc -lgcc
\f0\fs24 " ./configure --host=arm-none-eabi\
\
CC=arm-none-eabi-gcc ANSIFLAGS= CFLAGS="-mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=softfp -mlittle-endian -mthumb-interwork -O3 -I/usr/local/arm/arm-none-eabi/include" LDFLAGS="-L/usr/local/arm/arm-none-eabi/lib/thumb2 -L/usr/local/arm/lib/gcc/arm-none-eabi/4.4.1/thumb2" LIBS=" -lc -lgcc" ./configure --host=arm-none-eabi --build=i686-apple-darwin12.2.1\
\
\
CC=arm-none-eabi-gcc ANSIFLAGS= CFLAGS="-g
\f1\fs22 -\cf2 mcpu\cf0 =cortex-m4 -mthumb -\cf2 mfpu\cf0 =fpv4-sp-d16 -\cf2 march\cf0 =armv7e-m -\cf2 mtune\cf0 =cortex-m4 -mfloat-\cf2 abi\cf0 =softfp -mlittle-endian -mthumb-interwork
\f0\fs24 -O3 -I../ -I../lib/STM32F4xx_StdPeriph_Driver/inc -I../lib/CMSIS/ST/STM32F4xx/Include -I../lib/CMSIS/Include -I/usr/local/arm/arm-none-eabi/include" LDFLAGS="-L../ -L../lib/STM32F4xx_StdPeriph_Driver -L../lib/CMSIS/ST/STM32F4xx -L
\f1\fs22 /usr/local/arm/arm-none-eabi/lib/thumb/cortex-m4
\f0\fs24 -L
\f1\fs22 /usr/local/arm/lib/gcc/arm-none-eabi/4.6.2/thumb/cortex-m4
\f0\fs24 " LIBS="-lmain
\f1\fs22 -lstd -lcm4 -lc -lgcc
\f0\fs24 " ./configure --host=arm-none-eabi\
}
|
1137519-player
|
libjpeg_configure_stm32f4.rtf
|
Rich Text Format
|
lgpl
| 2,776
|
/*
* lcd.c
*
* Created on: 2011/02/19
* Author: masayuki
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "lcd.h"
#include "pcf_font.h"
#include "xpt2046.h"
#include "fat.h"
#include "usart.h"
#include "sound.h"
#include "delay.h"
#include "mpool.h"
#include "board_config.h"
#include "jerror.h"
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#include "sjis2utf16.h"
#include "settings.h"
#include "sd.h"
#undef ENABLE_BGIMG
#ifdef ENABLE_BGIMG
#include "bgimage.h"
#endif
volatile time_typedef time;
volatile cursor_typedef cursor;
volatile LCDStatusStruct_typedef LCDStatusStruct;
LCD_FUNC_typedef LCD_FUNC;
void DMA_ProgressBar_Conf(){
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
TIM_DeInit(TIM1);
TIM_TimeBaseInitStructure.TIM_Period = 5 - 1; // 50ms
TIM_TimeBaseInitStructure.TIM_Prescaler = 10000 - 1; // 10ms
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = (SystemCoreClock / 1000000UL) - 1; // 1us
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset;
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Disable;
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;
TIM_OC3Init(TIM1, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Disable);
TIM_SetCompare3(TIM1, 1);
TIM_Cmd(TIM1, ENABLE);
TIM_DMACmd(TIM1, TIM_DMA_CC3, ENABLE);
DMA_InitTypeDef DMA_InitStructure;
DMA_ClearFlag(DMA2_Stream6, DMA_FLAG_FEIF6 | DMA_FLAG_DMEIF6 | DMA_FLAG_TEIF6 | DMA_FLAG_HTIF6 | DMA_FLAG_TCIF6);
/*!< DMA2 Channel6 disable */
DMA_Cmd(DMA2_Stream6, DISABLE);
DMA_DeInit(DMA2_Stream6);
/*!< DMA2 Channel6 Config */
DMA_InitStructure.DMA_Channel = DMA_Channel_6;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&LCD->RAM;
DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)&progress_circular_bar_16x16x12_buff;
DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
DMA_InitStructure.DMA_BufferSize = sizeof(progress_circular_bar_16x16x12_buff) / sizeof(progress_circular_bar_16x16x12_buff[0]);
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full;
DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_INC4;
DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_INC4;
DMA_Init(DMA2_Stream6, &DMA_InitStructure);
//DMA_ITConfig(DMA2_Stream2, DMA_IT_TC, ENABLE);
/*!< DMA2 Channel7 enable */
DMA_Cmd(DMA2_Stream6, ENABLE);
}
void LCDBackLightInit()
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
/* LCD_BKPWM */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_TIM4);
TIM_DeInit(TIM4);
TIM_TimeBaseInitStructure.TIM_Period = 1000 - 1; // 100KHz
TIM_TimeBaseInitStructure.TIM_Prescaler = ((SystemCoreClock / 4) * 2) / 1000000 - 1; // 1MHz
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OC2Init(TIM4, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM4, TIM_OCPreload_Enable);
TIM_BDTRInitTypeDef bdtr;
TIM_BDTRStructInit(&bdtr);
bdtr.TIM_AutomaticOutput = TIM_AutomaticOutput_Enable;
TIM_BDTRConfig(TIM1, &bdtr);
TIM_ARRPreloadConfig(TIM4, ENABLE);
TIM_Cmd(TIM4, ENABLE);
TIM_SetCompare2(TIM4, (int)(1000 * (float)settings_group.disp_conf.brightness / 100.0f) - 1);
}
void LCDBackLightDisable()
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_DeInit(TIM4);
/* LCD_BKPWM */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_ResetBits(GPIOB, GPIO_Pin_7);
}
void LCDBackLightTimerInit(){
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM8, ENABLE);
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM8_UP_TIM13_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_DeInit(TIM8);
/* 1s = 1 / F_CPU(168MHz) * (167 + 1) * (99 + 1) * (9999 + 1) TIM1フレームレート計測用 */
TIM_TimeBaseInitStructure.TIM_Period = 9999;
TIM_TimeBaseInitStructure.TIM_Prescaler = 99;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = (SystemCoreClock / 1000000UL) - 1;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM8, &TIM_TimeBaseInitStructure);
TIM_ClearITPendingBit(TIM8, TIM_IT_Update);
TIM_ITConfig(TIM8, TIM_IT_Update, ENABLE);
TIM_SetCounter(TIM8, 0);
TIM_Cmd(TIM8, ENABLE);
}
void LCDBackLightTimerDeInit(){
TIM_ClearITPendingBit(TIM8, TIM_IT_Update);
TIM_ITConfig(TIM8, TIM_IT_Update, DISABLE);
TIM_DeInit(TIM8);
}
void LCDPeripheralInit(void)
{
/*-- GPIOs Configuration -----------------------------------------------------*/
/*
+-------------------+--------------------+------------------+------------------+
+ LCD pins assignment +
+-------------------+--------------------+------------------+------------------+
| PD0 <-> FSMC_D2 | | PD11 <-> FSMC_A16| PD7 <-> FSMC_NE1 |
| PD1 <-> FSMC_D3 | | | |
| PD4 <-> FSMC_NOE | PE7 <-> FSMC_D4 | | |
| PD5 <-> FSMC_NWE | PE8 <-> FSMC_D5 | | |
| PD8 <-> FSMC_D13 | PE9 <-> FSMC_D6 | | |
| PD9 <-> FSMC_D14 | PE10 <-> FSMC_D7 | | |
| PD10 <-> FSMC_D15 | PE11 <-> FSMC_D8 | | |
| | PE12 <-> FSMC_D9 | |------------------+
| | PE13 <-> FSMC_D10 | |
| PD14 <-> FSMC_D0 | PE14 <-> FSMC_D11 | |
| PD15 <-> FSMC_D1 | PE15 <-> FSMC_D12 |------------------+
+-------------------+--------------------+
PD3 <-> RESET
*/
FSMC_NORSRAMInitTypeDef FSMC_NORSRAMInitStructure;
FSMC_NORSRAMTimingInitTypeDef p;
GPIO_InitTypeDef GPIO_InitStructure;
/*
NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
*/
RCC_AHB3PeriphClockCmd(RCC_AHB3Periph_FSMC, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD | RCC_AHB1Periph_GPIOE, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE);
// RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM8, ENABLE);
/* RESET */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/* GPIOD Configuration */
GPIO_PinAFConfig(GPIOD, GPIO_PinSource0, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource1, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource4, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource5, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource7, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource8, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource9, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource10, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource11, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource14, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource15, GPIO_AF_FSMC);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_4 | GPIO_Pin_5 | \
GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | \
GPIO_Pin_11 | GPIO_Pin_14 | GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/* GPIOE Configuration */
GPIO_PinAFConfig(GPIOE, GPIO_PinSource7, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource8, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource9, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource10, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource11, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource12, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource13, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource14, GPIO_AF_FSMC);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource15, GPIO_AF_FSMC);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | \
GPIO_Pin_11 | GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | \
GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOE, &GPIO_InitStructure);
/*-- FSMC Configuration ----------------------------------------------------*/
p.FSMC_AddressSetupTime = 10; // 8 // 6 // OC 10
p.FSMC_AddressHoldTime = 0; // 0 // 0 // OC 0
p.FSMC_DataSetupTime = 10; // 5 // 5 // OC 10
p.FSMC_BusTurnAroundDuration = 0; // 0
p.FSMC_CLKDivision = 0;
p.FSMC_DataLatency = 0;
p.FSMC_AccessMode = FSMC_AccessMode_A;
FSMC_NORSRAMInitStructure.FSMC_Bank = FSMC_Bank1_NORSRAM1;
FSMC_NORSRAMInitStructure.FSMC_DataAddressMux = FSMC_DataAddressMux_Disable;
FSMC_NORSRAMInitStructure.FSMC_MemoryType = FSMC_MemoryType_NOR;
FSMC_NORSRAMInitStructure.FSMC_MemoryDataWidth = FSMC_MemoryDataWidth_16b;
FSMC_NORSRAMInitStructure.FSMC_BurstAccessMode = FSMC_BurstAccessMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_AsynchronousWait = FSMC_AsynchronousWait_Disable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignalPolarity = FSMC_WaitSignalPolarity_Low;
FSMC_NORSRAMInitStructure.FSMC_WrapMode = FSMC_WrapMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignalActive = FSMC_WaitSignalActive_BeforeWaitState;
FSMC_NORSRAMInitStructure.FSMC_WriteOperation = FSMC_WriteOperation_Enable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignal = FSMC_WaitSignal_Disable;
FSMC_NORSRAMInitStructure.FSMC_ExtendedMode = FSMC_ExtendedMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WriteBurst = FSMC_WriteBurst_Disable;
FSMC_NORSRAMInitStructure.FSMC_ReadWriteTimingStruct = &p;
FSMC_NORSRAMInitStructure.FSMC_WriteTimingStruct = &p;
FSMC_NORSRAMInit(&FSMC_NORSRAMInitStructure);
/* Enable FSMC Bank1_NOR Bank */
FSMC_NORSRAMCmd(FSMC_Bank1_NORSRAM1, ENABLE);
time.curTime = 0;
time.prevTime = 0;
time.flags.dimLight = 0;
time.flags.stop_mode = 0;
time.flags.enable = 1;
}
void MergeCircularProgressBar(int8_t menubar){
int i, j, k, l;
float alpha_ratio;
uint16_t progress_circular_bar_temp[16 * 16];
uint16_t alpha, data, bgdata, Ra, Ga, Ba, Rb, Gb, Bb, \
*d = (uint16_t*)progress_circular_bar_16x16x12, \
*a = (uint16_t*)progress_circular_bar_16x16_alpha;
k = 0;
for(j = PROGRESS_CIRCULAR_POS_Y;j < (PROGRESS_CIRCULAR_POS_Y + PROGRESS_CIRCULAR_HEIGHT);j++){
for(i = PROGRESS_CIRCULAR_POS_X;i < (PROGRESS_CIRCULAR_POS_X + PROGRESS_CIRCULAR_WIDTH);i++){
progress_circular_bar_temp[k++] = menubar ? menubar_320x22[i + j * 320] : colorc[BLACK];
}
}
k = 0;
for(l = 0;l < PROGRESS_CIRCULAR_FRAMES;l++){
a = (uint16_t*)progress_circular_bar_16x16_alpha;
for(i = 0;i < PROGRESS_CIRCULAR_HEIGHT;i++){
for(j = 0;j < PROGRESS_CIRCULAR_WIDTH;j++){
bgdata = progress_circular_bar_temp[k % (PROGRESS_CIRCULAR_WIDTH * PROGRESS_CIRCULAR_HEIGHT)];
data = *d++, alpha = *a++;
Ga = (alpha & 0x07e0) >> 5;
alpha_ratio = (float)((float)Ga / 63.0f);
// Foreground Image
Ra = (data & 0xf800) >> 11;
Ga = (data & 0x07e0) >> 5;
Ba = (data & 0x001f);
Ra *= alpha_ratio;
Ga *= alpha_ratio;
Ba *= alpha_ratio;
// Background Image
Rb = (bgdata & 0xf800) >> 11;
Gb = (bgdata & 0x07e0) >> 5;
Bb = (bgdata & 0x001f);
Rb *= (1.0f - alpha_ratio);
Gb *= (1.0f - alpha_ratio);
Bb *= (1.0f - alpha_ratio);
// Add colors
Ra += Rb;
Ga += Gb;
Ba += Bb;
progress_circular_bar_16x16x12_buff[k++] = (Ra << 11) | (Ga << 5) | Ba;
}
}
}
}
void LCDCheckPattern(){
int i, j, k;
LCDSetGramAddr(0, 0);
LCDPutCmd(0x0022);
for(k = 0;k < 6;k++){
for(j = 0;j < 8 * 20;j++){
for(i = 0;i < 20;i++){
LCDPutData(0x0000); // 0xa800
}
for(i = 0;i < 20;i++){
LCDPutData(0xa800);
}
}
for(j = 0;j < 8 * 20;j++){
for(i = 0;i < 20;i++){
LCDPutData(0xa800);
}
for(i = 0;i < 20;i++){
LCDPutData(0x0000);
}
}
}
}
void LCDInit(void)
{
LCDPeripheralInit();
clx = cly = 0;
LCD_CNT_PORT->ODR |= _BV(LCD_RESET);
Delayms(10);
LCD_CNT_PORT->ODR &= ~_BV(LCD_RESET);
Delayms(10);
LCD_CNT_PORT->ODR |= _BV(LCD_RESET);
Delayms(10);
LCDPutCmd(0x0000);LCDPutData(0x0001);
LCDPutCmd(0x0003);LCDPutData(0xA8A8);
LCDPutCmd(0x000C);LCDPutData(0x0000);
LCDPutCmd(0x000D);LCDPutData(0x000a);
LCDPutCmd(0x000E);LCDPutData(0x2B00);
LCDPutCmd(0x001E);LCDPutData(0x00B8);
LCDPutCmd(0x0001);LCDPutData(0x2B3F);
LCDPutCmd(0x0002);LCDPutData(0x0600);
LCDPutCmd(0x0010);LCDPutData(0x0000);
LCDPutCmd(0x0011);LCDPutData(0x6058); // AM:Vertical 0x6068
LCDPutCmd(0x0005);LCDPutData(0x0000);
LCDPutCmd(0x0006);LCDPutData(0x0000);
LCDPutCmd(0x0016);LCDPutData(0xEF1C);
LCDPutCmd(0x0017);LCDPutData(0x0003);
LCDPutCmd(0x0007);LCDPutData(0x0233);
LCDPutCmd(0x000B);LCDPutData(0x0000);
LCDPutCmd(0x000F);LCDPutData(0x0000);
LCDPutCmd(0x0041);LCDPutData(0x0000);
LCDPutCmd(0x0042);LCDPutData(0x0000);
LCDPutCmd(0x0048);LCDPutData(0x0000);
LCDPutCmd(0x0049);LCDPutData(0x013F);
LCDPutCmd(0x004A);LCDPutData(0x0000);
LCDPutCmd(0x004B);LCDPutData(0x0000);
LCDPutCmd(0x0044);LCDPutData(0xEF00);
LCDPutCmd(0x0045);LCDPutData(0x0000);
LCDPutCmd(0x0046);LCDPutData(0x013F);
LCDPutCmd(0x0030);LCDPutData(0x0707);
LCDPutCmd(0x0031);LCDPutData(0x0204);
LCDPutCmd(0x0032);LCDPutData(0x0204);
LCDPutCmd(0x0033);LCDPutData(0x0502);
LCDPutCmd(0x0034);LCDPutData(0x0507);
LCDPutCmd(0x0035);LCDPutData(0x0204);
LCDPutCmd(0x0036);LCDPutData(0x0204);
LCDPutCmd(0x0037);LCDPutData(0x0502);
LCDPutCmd(0x003A);LCDPutData(0x0302);
LCDPutCmd(0x003B);LCDPutData(0x0302);
LCDPutCmd(0x0023);LCDPutData(0x0000);
LCDPutCmd(0x0024);LCDPutData(0x0000);
LCDPutCmd(0x0025);LCDPutData(0x8000);
// LCDPutCmd(0x0025);LCDPutData(0xE000);
LCDPutCmd(0x004e);LCDPutData(0);
LCDPutCmd(0x004f);LCDPutData(0);
/*
LCDPutCmd(0x0028);LCDPutData(0x0006);
LCDPutCmd(0x002F);LCDPutData(0x12BE);
LCDPutCmd(0x0012);LCDPutData(0x6CEB);
*/
LCDGotoXY(0, 0);
LCDClear(240, 320, BLACK);
MergeCircularProgressBar(1);
jpeg_read.buf_type = 0;
LCDPutCmd(0x0000);
LCD->RAM;
debug.printf("\r\nLCD_ID:%04x", LCD->RAM);
LCDBackLightInit();
}
void LCDSetWindowArea(uint16_t x, uint16_t y, uint16_t width, uint16_t height){
if(1){
LCDPutCmd(0x0044);LCDPutData((height - 1 + y) << 8 | y);
LCDPutCmd(0x0045);LCDPutData(LCD_WIDTH - width - x);
LCDPutCmd(0x0046);LCDPutData(LCD_WIDTH - 1 - x);
} else {
LCDPutCmd(0x0044);LCDPutData(LCD_HEIGHT - height - 1);
LCDPutCmd(0x0045);LCDPutData(0x0000);
LCDPutCmd(0x0046);LCDPutData(width - 1);
}
}
__attribute__( ( always_inline ) ) __INLINE void LCDSetGramAddr(int x, int y)
{
// if(1){
LCDPutCmd(0x004e);
LCDPutData(y);
LCDPutCmd(0x004f);
LCDPutData(LCD_WIDTH - 1 - x);
// } else {
// LCDPutCmd(0x004e);
// LCDPutData(LCD_HEIGHT - 1 - y);
// LCDPutCmd(0x004f);
// LCDPutData(y);
// }
}
void LCDPutPos(uint16_t x, uint16_t y, colors color)
{
LCDSetGramAddr(x, y);
LCDPutCmd(0x0022);
LCDPutData(colorc[color]);
}
inline void LCDGotoXY(int x, int y)
{
clx = x;
cly = y;
}
void LCDPutWideCharDefault(uint16_t code, colors color)
{
if(code >= 0x0020 && code <= 0x00DF){
LCDPutAscii(code, color);
} else {
LCDPutAscii(0x00e0, color);
}
}
static uint16_t sjis_utf16_conv(uint16_t code)
{
return sjis2utf16_table[code - 0x8140];
}
void LCDPutStringSJIS(uint8_t *s, uint8_t color)
{
uint16_t tc;
while(*s != '\0'){
if((*s >= 0x20 && *s <= 0x7F) || (*s >= 0xA0 && *s <= 0xDF)){
LCD_FUNC.putChar(*s++, color);
continue;
}
tc = *s++ << 8;
tc |= *s++;
if(!pcf_font.c_loaded){
LCD_FUNC.putWideChar(sjis_utf16_conv(tc), color);
} else {
LCD_FUNC.putWideChar(C_FONT_UNDEF_CODE, color);
}
}
}
uint16_t LCDPutStringSJISN(uint16_t startPosX, uint16_t endPosX, uint8_t lineCnt, uint8_t *s, uint8_t color)
{
uint16_t tc, yPos = 0;
while(*s != '\0'){
/*
if(clx >= endPosX){
LCDPutString("..", color);
return;
}
*/
if(clx > endPosX){
if(lineCnt-- > 1){
if((LCD_FUNC.putChar == PCFPutChar16px) || (LCD_FUNC.putChar == C_PCFPutChar16px)){
cly += 17;
yPos += 17;
} else {
cly += 13;
yPos += 13;
}
clx = startPosX;
} else {
LCDPutString("..", color);
return yPos;
}
}
if((*s >= 0x20 && *s <= 0x7F) || (*s >= 0xA0 && *s <= 0xDF)){
LCD_FUNC.putChar(*s++, color);
continue;
}
tc = *s++ << 8;
tc |= *s++;
if(!pcf_font.c_loaded){
LCD_FUNC.putWideChar(sjis_utf16_conv(tc), color);
} else {
LCD_FUNC.putWideChar(C_FONT_UNDEF_CODE, color);
}
}
return yPos;
}
uint16_t LCDGetStringSJISPixelLength(uint8_t *s, uint16_t font_width)
{
uint16_t tc, len = 0;
while(*s != '\0'){
if((*s >= 0x20 && *s <= 0x7F) || (*s >= 0xA0 && *s <= 0xDF)){
len += LCD_FUNC.getCharLength(*s++, font_width);
continue;
}
tc = *s++ << 8;
tc |= *s++;
if(!pcf_font.c_loaded){
len += LCD_FUNC.getCharLength(sjis_utf16_conv(tc), font_width);
} else {
len += LCD_FUNC.getCharLength(C_FONT_UNDEF_CODE, font_width);
}
}
return len;
}
uint16_t LCDPutStringLFN(uint16_t startPosX, uint16_t endPosX, uint8_t lineCnt, uint8_t *s, colors color)
{
uint16_t tc, yPos = 0;
while(1){
if(clx > endPosX){
if(lineCnt-- > 1){
if((LCD_FUNC.putChar == PCFPutChar16px) || (LCD_FUNC.putChar == C_PCFPutChar16px)){
cly += 17;
yPos += 17;
} else {
cly += 13;
yPos += 13;
}
clx = startPosX;
} else {
LCDPutString("..", color);
return yPos;
}
}
tc = *(uint8_t*)s++;
tc |= *(uint8_t*)s++ << 8;
if(tc == 0x0000){
return yPos;
}
if(tc <= 0x007F){
LCD_FUNC.putChar(tc, color);
continue;
}
if(!pcf_font.c_loaded){
LCD_FUNC.putWideChar(tc, color);
} else {
LCD_FUNC.putWideChar(C_FONT_UNDEF_CODE, color);
}
}
return yPos;
}
uint16_t LCDGetStringLFNPixelLength(void *s, uint16_t font_width){
uint16_t tc, len = 0;
while(1){
tc = *(uint8_t*)s++;
tc |= *(uint8_t*)s++ << 8;
if(tc == 0x0000) return len;
if(tc <= 0x007F){
len += LCD_FUNC.getCharLength(tc, font_width);
continue;
}
if(!pcf_font.c_loaded){
len += LCD_FUNC.getCharLength(tc, font_width);
} else {
len += LCD_FUNC.getCharLength(C_FONT_UNDEF_CODE, font_width);
}
}
return len;
}
void LCDPutAscii(uint16_t asc, colors color)
{
int i, j, x, y = cly + 2;
uint8_t fontbuf[12];
*((uint32_t*)&fontbuf[0]) = *((uint32_t*)&font_ascii_table[asc * sizeof(fontbuf) + 0]);
*((uint32_t*)&fontbuf[4]) = *((uint32_t*)&font_ascii_table[asc * sizeof(fontbuf) + 4]);
*((uint32_t*)&fontbuf[8]) = *((uint32_t*)&font_ascii_table[asc * sizeof(fontbuf) + 8]);
for(i = 0;i < 11;i++){
x = clx;
for(j = 0;j < 6;j++){
LCDSetGramAddr(x++, y);
LCDPutCmd(0x0022);
if((fontbuf[i] << j) & 0x80){
LCDPutData(colorc[color]);
}
}
y++;
}
clx += 6;
}
void LCDPutString(const char *str, colors color)
{
while(*str != '\0'){
if((0x20 <= *str) && (*str <= 0xDF)){
LCD_FUNC.putChar(*str++, color);
} else if(*str++ == '\n') {
clx = 0;
cly += 15;
continue;
}
}
}
void LCDPutStringN(const char *str, uint16_t endPosX, colors color)
{
while(*str != '\0'){
if(clx >= endPosX){
LCDPutString("..", color);
return;
}
if((0x20 <= *str) && (*str <= 0xDF)){
LCD_FUNC.putChar(*str++, color);
} else if(*str++ == '\n') {
clx = 0;
cly += 13;
continue;
}
}
}
uint16_t LCDPutStringUTF8(uint16_t startPosX, uint16_t endPosX, uint8_t lineCnt, uint8_t *s, colors color)
{
uint16_t tc, yPos = 0;
while(*s != '\0'){
if(clx > endPosX){
if(lineCnt-- > 1){
if((LCD_FUNC.putChar == PCFPutChar16px) || (LCD_FUNC.putChar == C_PCFPutChar16px)){
cly += 17;
yPos += 17;
} else {
cly += 13;
yPos += 13;
}
clx = startPosX;
} else {
LCDPutString("..", color);
return yPos;
}
}
if((*s >= 0x20 && *s <= 0x7F)){
LCD_FUNC.putChar(*s++, color);
continue;
}
if(*s >= 0xE0){
tc = ((uint16_t)*s++ << 12) & 0xF000;
tc |= ((uint16_t)*s++ << 6) & 0x0FC0;
tc |= (uint16_t)*s++ & 0x003F;
if(!pcf_font.c_loaded){
LCD_FUNC.putChar(tc, color);
} else {
LCD_FUNC.putChar(C_FONT_UNDEF_CODE, color);
}
}
}
return yPos;
}
uint16_t LCDGetStringUTF8PixelLength(uint8_t *s, uint16_t font_width)
{
uint16_t tc, len = 0;
while(*s != '\0'){
if((*s >= 0x20 && *s <= 0x7F)){
len += LCD_FUNC.getCharLength(*s++, font_width);
continue;
}
if(*s >= 0xE0){
tc = ((uint16_t)*s++ << 12) & 0xF000;
tc |= ((uint16_t)*s++ << 6) & 0x0FC0;
tc |= (uint16_t)*s++ & 0x003F;
if(!pcf_font.c_loaded){
len += LCD_FUNC.getCharLength(tc, font_width);
} else {
len += LCD_FUNC.getCharLength(C_FONT_UNDEF_CODE, font_width);
}
}
}
return len;
}
void LCDClear(int x,int y, colors color)
{
int i, j;
LCDSetGramAddr(0, 0);
LCDPutCmd(0x0022);
for(i = 0;i < y;i++){
for(j = 0;j < x;j++){
LCDPutData(colorc[color]);
}
}
}
void LCDClearWithBgImg()
{
int i;
int R, G, B;
uint16_t temp;
LCDSetGramAddr(0, 0);
LCDPutCmd(0x0022);
for(i = 0;i < LCD_WIDTH * LCD_HEIGHT;i++){
#ifdef ENABLE_BGIMG
temp = bgImage[i];
R = (temp & 0xf800) >> 11;
G = (temp & 0x07e0) >> 5;
B = (temp & 0x001f);
if((R -= 4) <= 0) R = 0;
if((G -= 8) <= 0) G = 0;
if((B -= 4) <= 0) B = 0;
if(R > 31){R = 31;}
if(G > 63){G = 63;}
if(B > 31){B = 31;}
temp = (R << 11) | (G << 5) | B;
// LCDPutData(bgImage[i]);
LCDPutData(temp);
#else
LCDPutData(black);
#endif
}
}
void LCDPutBgImg(const uint16_t *p)
{
int i;
LCDSetGramAddr(0, 0);
LCDPutCmd(0x0022);
for(i = 0;i < LCD_WIDTH * LCD_HEIGHT;i++){
LCDPutData(*p++);
}
}
uint16_t addValRGB(uint16_t srcColor, int16_t add)
{
pixel_fmt_typedef pixel;
pixel.color.d16 = srcColor;
pixel.color.R = __USAT(pixel.color.R + add, 5);
pixel.color.G = __USAT(pixel.color.G + add * 2, 6);
pixel.color.B = __USAT(pixel.color.B + add, 5);
return (pixel.color.d16);
}
void LCDPutBgImgFiler(){
uint32_t i;
uint16_t *p;
LCDSetGramAddr(0, 0);
LCDPutCmd(0x0022);
p = (uint16_t*)(FLASH_BASE + 16 * 1024); // Sector #1
for(i = 0;i < (6 * 1024 / sizeof(uint16_t));i++){ // 1st 6KB
LCD->RAM = addValRGB(*p++, -4);
}
p = (uint16_t*)(FLASH_BASE + (16 + 16) * 1024); // Sector #2
for(i = 0;i < (16 * 1024 / sizeof(uint16_t));i++){ // 2nd 16KB
LCD->RAM = addValRGB(*p++, -4);
}
p = (uint16_t*)(0x080C0000); // Sector #10
for(i = 0;i < (128 * 1024 / sizeof(uint16_t));i++){ // 3rd 128KB
LCD->RAM = addValRGB(*p++, -4);
}
}
void LCDPutBgImgMusic(){
uint32_t i;
uint16_t *p;
LCDSetGramAddr(0, 0);
LCDPutCmd(0x0022);
p = (uint16_t*)(FLASH_BASE + (16 + 6) * 1024); // Sector #1 + 6KB offset
for(i = 0;i < (6 * 1024 / sizeof(uint16_t));i++){ // 1st 6KB
LCD->RAM = *p++;
}
p = (uint16_t*)(FLASH_BASE + (16 + 16 + 16) * 1024); // Sector #3
for(i = 0;i < (16 * 1024 / sizeof(uint16_t));i++){ // 2nd 16KB
LCD->RAM = *p++;
}
p = (uint16_t*)(0x080E0000); // Sector #11
for(i = 0;i < (128 * 1024 / sizeof(uint16_t));i++){ // 3rd 128KB
LCD->RAM = *p++;
}
}
void DrawLine(int x1, int y1, int x2, int y2, colors color)
{
int W = x2 - x1;
int H = y2 - y1;
int dx = 0;
int dy = 0;
int Wy = 0;
int Hx = 0;
if (W >= H)
{
for (dx = 0; dx <= W; dx ++)
{
LCDSetGramAddr(x1+dx, y1+dy);
LCDPutCmd(0x0022);
LCDPutData(colorc[color]);
Hx += H;
if (Wy < Hx)
{
Wy += W;
dy += 1;
}
}
}
else
{
for (dy = 0; dy <= H; dy ++)
{
LCDSetGramAddr(x1+dx, y1+dy);
LCDPutCmd(0x0022);
LCDPutData(colorc[color]);
Wy += W;
if (Hx < Wy)
{
Hx += H;
dx += 1;
}
}
}
}
__attribute__( ( always_inline ) ) __INLINE void LCDPset(uint16_t x, uint16_t y, colors color){
LCDSetGramAddr(x, y);
LCDPutCmd(0x0022);
LCDPutData(colorc[color]);
}
__attribute__( ( always_inline ) ) __INLINE void LCDPset2(uint16_t x, uint16_t y, uint16_t data){
LCDSetGramAddr(x, y);
LCDPutCmd(0x0022);
LCDPutData(data);
}
__attribute__( ( always_inline ) ) __INLINE uint16_t LCDGetPos(uint16_t x, uint16_t y){
LCDSetGramAddr(x, y);
LCDPutCmd(0x0022);
LCD->RAM;
return LCD->RAM;
}
void LCDDrawLine2(int16_t sPosX, int16_t sPosY, int16_t ePosX, int16_t ePosY, colors color){
int dw, dh, e, x, y;
dw = ePosX - sPosX;
dh = ePosY - sPosY;
e = 0;
if(dw >= dh){
y = sPosY;
for(x = sPosX;x <= ePosX;x++){
LCDPset(x, y, color);
e += 2 * dh;
if(e >= (2 * dw)){
y++;
e -= 2 * dw;
}
}
} else{
}
}
void LCDDrawLine(uint16_t sPosX, uint16_t sPosY, uint16_t ePosX, uint16_t ePosY, colors color){
int x, y, w, h, offsetY;
float delta, alpha;
pixel_fmt_typedef pixel_fg, pixel_bg, pixel;
w = ePosX - sPosX;
h = ePosY - sPosY;
// debug.printf("\r\n\nPlot");
// debug.printf("\r\ndelta:%f", delta);
// debug.printf("\r\noffsetY:%d", offsetY);
if(abs(w) >= abs(h)){
if(ePosX == sPosX){
offsetY = sPosY + 0.5f;
for(x = sPosX;x <= ePosX;x++){
y = offsetY;
LCDPset(x, y, color);
}
return;
}
delta = (float)h / (float)w;
offsetY = -delta * sPosX + sPosY + 0.5f;
if(ePosX >= sPosX){
for(x = sPosX;x <= ePosX;x++){
y = delta * x + offsetY;
alpha = delta * x + offsetY;
alpha = 1.0f - (alpha - y);
pixel_bg.color.d16 = LCDGetPos(x, y);
pixel_fg.color.d16 = colorc[color];
pixel.color.R = pixel_fg.color.R * alpha + pixel_bg.color.R * (1.0f - alpha);
pixel.color.G = pixel_fg.color.G * alpha + pixel_bg.color.G * (1.0f - alpha);
pixel.color.B = pixel_fg.color.B * alpha + pixel_bg.color.B * (1.0f - alpha);
LCDPset2(x, y, pixel.color.d16);
debug.printf("\r\nA x:%d y:%d delta:%f", x, y, delta);
// LCDPset(x, y, color);
}
} else {
for(x = sPosX;x >= ePosX;x--){
y = delta * x + offsetY;
alpha = delta * x + offsetY;
alpha = 1.0f - (alpha - y);
pixel_bg.color.d16 = LCDGetPos(x, y);
pixel_fg.color.d16 = colorc[color];
pixel.color.R = pixel_fg.color.R * alpha + pixel_bg.color.R * (1.0f - alpha);
pixel.color.G = pixel_fg.color.G * alpha + pixel_bg.color.G * (1.0f - alpha);
pixel.color.B = pixel_fg.color.B * alpha + pixel_bg.color.B * (1.0f - alpha);
LCDPset2(x, y, pixel.color.d16);
debug.printf("\r\nB x:%d y:%d delta:%f", x, y, delta);
// LCDPset(x, y, color);
}
}
} else {
if(ePosY >= sPosY){
if(sPosX == ePosX){
for(y = sPosY;y <= ePosY;y++){
x = sPosX;
// debug.printf("\r\nC0 x:%d y:%d delta:%f", x, y, delta);
LCDPset(x, y, color);
}
} else {
delta = (float)h / (float)w;
offsetY = -delta * sPosX + sPosY + 0.5f;
delta = 1.0f / delta;
for(y = sPosY;y <= ePosY;y++){
x = (y - offsetY) * delta;
debug.printf("\r\nC x:%d y:%d delta:%f", x, y, delta);
LCDPset(x, y, color);
alpha = (y - offsetY) * delta;
alpha = 1.0f - (alpha - x);
pixel_bg.color.d16 = LCDGetPos(x - 1, y);
pixel_fg.color.d16 = colorc[color];
pixel.color.R = pixel_fg.color.R * alpha + pixel_bg.color.R * (1.0f - alpha);
pixel.color.G = pixel_fg.color.G * alpha + pixel_bg.color.G * (1.0f - alpha);
pixel.color.B = pixel_fg.color.B * alpha + pixel_bg.color.B * (1.0f - alpha);
LCDPset2(x - 1, y, pixel.color.d16);
alpha = 1.0f - alpha;
pixel_bg.color.d16 = LCDGetPos(x + 1, y);
pixel_fg.color.d16 = colorc[color];
pixel.color.R = pixel_fg.color.R * alpha + pixel_bg.color.R * (1.0f - alpha);
pixel.color.G = pixel_fg.color.G * alpha + pixel_bg.color.G * (1.0f - alpha);
pixel.color.B = pixel_fg.color.B * alpha + pixel_bg.color.B * (1.0f - alpha);
LCDPset2(x + 1, y, pixel.color.d16);
}
}
} else {
if(sPosX == ePosX){
for(y = sPosY;y >= ePosY;y--){
x = sPosX;
// debug.printf("\r\nD0 x:%d y:%d delta:%f", x, y, delta);
LCDPset(x, y, color);
}
} else {
delta = (float)h / (float)w;
offsetY = -delta * sPosX + sPosY + 0.5f;
delta = 1.0f / delta;
for(y = sPosY;y >= ePosY;y--){
x = (y - offsetY) * delta;
alpha = (y - offsetY) * delta;
alpha = 1.0f - (alpha - x);
pixel_bg.color.d16 = LCDGetPos(x, y);
pixel_fg.color.d16 = colorc[color];
pixel.color.R = pixel_fg.color.R * alpha + pixel_bg.color.R * (1.0f - alpha);
pixel.color.G = pixel_fg.color.G * alpha + pixel_bg.color.G * (1.0f - alpha);
pixel.color.B = pixel_fg.color.B * alpha + pixel_bg.color.B * (1.0f - alpha);
LCDPset2(x, y, pixel.color.d16);
debug.printf("\r\nD x:%d y:%d delta:%f", x, y, delta);
// LCDPset(x, y, color);
}
}
}
}
}
void LCDDrawSquare(uint16_t x, uint16_t y, uint16_t width, uint16_t height, colors color)
{
uint32_t ix, iy;
for(iy = 0;iy < height;iy++){
ix = 0;
LCDSetGramAddr(x + ix, y + iy);
for(ix = 0;ix < width;ix++){
LCDPutCmd(0x0022);
LCDPutData(colorc[color]);
}
}
}
void LCDPrintFileList()
{
// TOUCH_PINIRQ_DISABLE;
touch.func = LCDTouchPoint;
USART_IRQ_DISABLE;
int i;
uint32_t var32;
volatile uint16_t idEntry = cursor.pageIdx * PAGE_NUM_ITEMS;
uint16_t entryPointOffset, color, step;
uint8_t pLFNname[80];
char fileNameStr[13], fileSizeStr[13], fileTypeStr[4];
TIM_Cmd(TIM1, DISABLE); // Stop displaying progress bar
DMA_Cmd(DMA2_Stream6, DISABLE);
LCDSetWindowArea(0, 0, LCD_WIDTH, LCD_HEIGHT);
// LCDClearWithBgImg();
LCDPutBgImgFiler();
LCDPutIcon(0, 0, 320, 22, menubar_320x22, menubar_320x22_alpha);
LCDGotoXY(5, 2);
LCDPutStringLFN(5, 185, 1, (uint8_t*)fat.currentDirName, HEADER_COLOR);
step = fat.fileCnt - idEntry;
if(step >= PAGE_NUM_ITEMS){
step = PAGE_NUM_ITEMS;
}
cly = HEIGHT_ITEM;
for(i = idEntry;i < (idEntry + step);i++){
if((i == 0) && (fat.currentDirEntry == fat.rootDirEntry)){ // exception for settings item
LCDPutIcon(2, cly - 3, 22, 22, settings_22x22, settings_22x22_alpha);
clx = 28;
LCDPutString("Settings", ARCHIVE_COLOR);
cly += HEIGHT_ITEM;
continue;
}
entryPointOffset = getListEntryPoint(i); // リスト上にあるIDファイルエントリの先頭位置をセット
memset(fileNameStr, '\0', sizeof(fileNameStr));
memset(fileSizeStr, '\0', sizeof(fileSizeStr));
memset(fileTypeStr, '\0', sizeof(fileTypeStr));
strncpy(fileNameStr, (char*)&fbuf[entryPointOffset], 8); // 8文字ファイル名をコピー
strtok(fileNameStr, " "); // スペースがあればNULLに置き換える
if(fbuf[entryPointOffset + NT_Reserved] & NT_U2L_NAME){ // Name Upper to Lower
fileNameStr[0] = tolower(fileNameStr[0]);
fileNameStr[1] = tolower(fileNameStr[1]);
fileNameStr[2] = tolower(fileNameStr[2]);
fileNameStr[3] = tolower(fileNameStr[3]);
fileNameStr[4] = tolower(fileNameStr[4]);
fileNameStr[5] = tolower(fileNameStr[5]);
fileNameStr[6] = tolower(fileNameStr[6]);
fileNameStr[7] = tolower(fileNameStr[7]);
}
var32 = *((uint32_t*)&fbuf[entryPointOffset + FILESIZE]); // ファイルサイズ取得
if(var32 >= 1000000){
var32 /= 1000000;
SPRINTF(fileSizeStr, "%dMB", var32);
} else if(var32 >= 1000){
var32 /= 1000;
SPRINTF(fileSizeStr, "%dKB", var32);
} else {
SPRINTF(fileSizeStr, "%dB", var32);
}
if(!(fbuf[entryPointOffset + ATTRIBUTES] & ATTR_DIRECTORY)){
if(fbuf[entryPointOffset + 8] != 0x20){
strncpy(fileTypeStr, (char*)&fbuf[entryPointOffset + 8], 3);
//strcat(fileNameStr, ".");
//strcat(fileNameStr, fileTypeStr);
} else {
strcpy(fileTypeStr, "---");
}
color = ARCHIVE_COLOR; // archivecolor
if(strcmp(fileTypeStr, "MOV") == 0){
LCDPutIcon(2, cly - 5, 22, 22, movie_22x22, movie_22x22_alpha);
} else if(strcmp(fileTypeStr, "MP3") == 0 || \
strcmp(fileTypeStr, "AAC") == 0 || \
strcmp(fileTypeStr, "MP4") == 0 || \
strcmp(fileTypeStr, "M4A") == 0 || \
strcmp(fileTypeStr, "M4P") == 0 || \
strcmp(fileTypeStr, "WAV") == 0
) {
LCDPutIcon(2, cly - 5, 22, 22, onpu_22x22, onpu_22x22_alpha);
} else if(strcmp(fileTypeStr, "PCF") == 0) {
LCDPutIcon(2, cly - 5, 22, 22, font_22x22, font_22x22_alpha);
} else if(strcmp(fileTypeStr, "JPG") == 0 || strcmp(fileTypeStr, "JPE") == 0) {
LCDPutIcon(2, cly - 5, 22, 22, jpeg_22x22, jpeg_22x22_alpha);
} else {
LCDPutIcon(2, cly - 5, 22, 22, archive_22x22, archive_22x22_alpha);
}
} else {
strcat(fileTypeStr, "DIR");
color = DIR_COLOR; // dircolor
fileSizeStr[0] = '\0';
if(strncmp(fileNameStr, "..", 2) == 0){
LCDPutIcon(2, cly - 5, 22, 22, parent_arrow_22x22, parent_arrow_22x22_alpha);
} else {
LCDPutIcon(2, cly - 5, 22, 22, folder_22x22, folder_22x22_alpha);
}
}
clx = 28;
if(!setLFNname(pLFNname, i, LFN_WITHOUT_EXTENSION, sizeof(pLFNname))){ // エントリがSFNの場合
LCDPutString(fileNameStr, color);
} else { // LFNの場合
LCDPutStringLFN(clx, 180, 1, pLFNname, color);
}
clx = 210;
LCDPutString(fileTypeStr, color);
clx = 250;
LCDPutString(fileSizeStr, color);
cly += HEIGHT_ITEM;
}
if(cursor.pages > 0){
// Scroll Bar
int scrollHeight = 204 / (cursor.pages + 1), \
scrollStartPos = scrollHeight * cursor.pageIdx + 25 + 2, \
height = scrollHeight - 14 - 4;
LCDPutIcon(309, 25, 6, 204, scrollbar_6x204, scrollbar_6x204_alpha); // scroll background
LCDPutIcon(309, scrollStartPos, 6, 7, scrollbar_top_6x7, scrollbar_top_6x7_alpha);
for(i = scrollStartPos + 7;i < ((scrollStartPos + 7) + height);i++){
LCDPutIcon(309, i, 6, 1, scrollbar_hline_6x1, scrollbar_hline_6x1_alpha);
}
LCDPutIcon(309, i, 6, 7, scrollbar_bottom_6x7, scrollbar_bottom_6x7_alpha);
}
LCDStoreCursorBar(cursor.pos);
LCDSelectCursorBar(cursor.pos);
LCDBackLightTimerInit();
// TOUCH_PINIRQ_ENABLE;
// TouchPenIRQ_Enable();
USART_IRQ_ENABLE;
touch.repeat = 1;
}
void LCDPrintSettingsList(char type, int select_id, settings_item_typedef *item)
{
// TOUCH_PINIRQ_DISABLE;
// USART_IRQ_DISABLE;
touch.func = LCDTouchPoint;
int i, selected_entry;
volatile uint16_t idEntry = cursor.pageIdx * PAGE_NUM_ITEMS;
uint16_t step;
TIM_Cmd(TIM1, DISABLE);
DMA_Cmd(DMA2_Stream6, DISABLE);
LCDSetWindowArea(0, 0, LCD_WIDTH, LCD_HEIGHT);
// LCDClear(LCD_WIDTH, LCD_HEIGHT, BLACK);
LCDCheckPattern();
// LCDPutBgImgFiler();
LCDPutIcon(0, 0, 320, 22, menubar_320x22, menubar_320x22_alpha);
LCDGotoXY(5, 2);
LCDPutString((char*)fat.currentDirName, HEADER_COLOR);
step = fat.fileCnt - idEntry;
if(step >= PAGE_NUM_ITEMS){
step = PAGE_NUM_ITEMS;
}
cly = HEIGHT_ITEM;
if(type == SETTING_TYPE_ITEM){
if(select_id == 0){
selected_entry = item->selected_id + 1;
} else {
selected_entry = select_id;
}
for(i = idEntry;i < (idEntry + step);i++){
if(strncmp(settings_p[i].name, "..", 2) == 0){
LCDPutIcon(2, cly - 5, 22, 22, parent_arrow_22x22, parent_arrow_22x22_alpha);
} else {
if(i == selected_entry){
LCDPutIcon(2, cly - 3, 22, 22, radiobutton_checked_22x22, radiobutton_22x22_alpha);
} else {
LCDPutIcon(2, cly - 3, 22, 22, radiobutton_unchecked_22x22, radiobutton_22x22_alpha);
}
}
clx = 28;
LCDPutString(settings_p[i].name, WHITE);
cly += HEIGHT_ITEM;
}
item->selected_id = selected_entry - 1;
if(item->func != NULL && select_id != 0){
item->func((void*)item);
}
} else {
for(i = idEntry;i < (idEntry + step);i++){
if(strncmp(settings_p[i].name, "..", 2) == 0){
LCDPutIcon(2, cly - 5, 22, 22, parent_arrow_22x22, parent_arrow_22x22_alpha);
} else {
if(settings_p[i].icon != NULL){
LCDPutIcon(2, cly - 5, 22, 22, settings_p[i].icon->data, settings_p[i].icon->alpha);
} else {
LCDPutIcon(2, cly - 5, 22, 22, select_22x22, select_22x22_alpha);
}
}
clx = 28;
LCDPutString(settings_p[i].name, WHITE);
cly += HEIGHT_ITEM;
}
}
/*
if(cursor.pages > 0){
// Scroll Bar
int scrollHeight = 204 / (cursor.pages + 1), \
scrollStartPos = scrollHeight * cursor.pageIdx + 25 + 2, \
height = scrollHeight - 14 - 4;
LCDPutIcon(309, 25, 6, 204, scrollbar_6x204, scrollbar_6x204_alpha); // scroll background
LCDPutIcon(309, scrollStartPos, 6, 7, scrollbar_top_6x7, scrollbar_top_6x7_alpha);
for(i = scrollStartPos + 7;i < ((scrollStartPos + 7) + height);i++){
LCDPutIcon(309, i, 6, 1, scrollbar_hline_6x1, scrollbar_hline_6x1_alpha);
}
LCDPutIcon(309, i, 6, 7, scrollbar_bottom_6x7, scrollbar_bottom_6x7_alpha);
}
*/
LCDStoreCursorBar(cursor.pos);
LCDSelectCursorBar(cursor.pos);
// USART_IRQ_ENABLE;
LCDBackLightTimerInit();
// TOUCH_PINIRQ_ENABLE;
touch.repeat = 1;
}
void LCDPutCursorBar(int curPos)
{
int i;
LCDSetGramAddr(0, (curPos + 1) * HEIGHT_ITEM);
LCDPutCmd(0x0022);
for(i = 0;i < LCD_WIDTH * 13;i++){
LCDPutData(cursorRAM[i]);
}
}
void LCDSelectCursorBar(int curPos)
{
int i, j;
uint16_t startPosX = 26, width = 280;
pixel_fmt_typedef pixel;
for(j = 0;j < 13;j++){
LCDSetGramAddr(startPosX, (curPos + 1) * HEIGHT_ITEM + j);
LCDPutCmd(0x0022);
for(i = startPosX;i < (startPosX + width);i++){
pixel.color.d16 = cursorRAM[i + j * LCD_WIDTH];
pixel.color.R = __USAT(pixel.color.R + 6, 5);
pixel.color.G = __USAT(pixel.color.G + 12, 6);
pixel.color.B = __USAT(pixel.color.B + 6, 5);
LCDPutData(pixel.color.d16);
}
}
}
/*
void LCDSelectCursorBar(int curPos)
{
int i, j;
int R, G, B;
uint16_t startPosX = 26, width = 280, pixel;
for(j = 0;j < 13;j++){
LCDSetGramAddr(startPosX, (curPos + 1) * HEIGHT_ITEM + j);
LCDPutCmd(0x0022);
for(i = startPosX;i < (startPosX + width);i++){
pixel = cursorRAM[i + j * LCD_WIDTH];
R = (pixel & 0xf800) >> 11;
G = (pixel & 0x07e0) >> 5;
B = (pixel & 0x001f);
R = __USAT(R + 6, 5); // 0 <= R < 32
G = __USAT(G + 6 * 2, 6); // 0 <= G < 64
B = __USAT(B + 6, 5); // 0 <= B < 32
LCDPutData(R << 11 | G << 5 | B);
}
}
}
*/
void LCDStoreCursorBar(int curPos)
{
int i;
LCDSetGramAddr(0, (curPos + 1) * HEIGHT_ITEM);
LCDPutCmd(0x0022);
LCD->RAM;
for(i = 0;i < LCD_WIDTH * 13;i++){
cursorRAM[i] = LCD->RAM;
}
}
void LCDCursorUp()
{
if(cursor.pos-- <= 0) {
if(cursor.pageIdx-- <= 0){
cursor.pageIdx = cursor.pos = 0;
return;
} else {
cursor.pos = PAGE_NUM_ITEMS - 1;
if(!settings_mode){
LCDPrintFileList();
} else {
LCDPrintSettingsList(SETTING_TYPE_DIR, 0, NULL);
}
return;
}
}
LCDPutCursorBar(cursor.pos + 1); // 前項消去
LCDStoreCursorBar(cursor.pos); // 現在の項目を保存
LCDSelectCursorBar(cursor.pos); // 現在の項目を選択
}
void LCDCursorDown()
{
if( (cursor.pos + cursor.pageIdx * PAGE_NUM_ITEMS + 1) >= fat.fileCnt ){
return;
}
if(cursor.pos++ >= (PAGE_NUM_ITEMS - 1)) {
cursor.pos = 0;
if(++cursor.pageIdx > cursor.pages) cursor.pageIdx = cursor.pages - 1;
if(!settings_mode){
LCDPrintFileList();
} else {
LCDPrintSettingsList(SETTING_TYPE_DIR, 0, NULL);
}
return;
}
LCDPutCursorBar(cursor.pos - 1); // 前項消去
LCDStoreCursorBar(cursor.pos); // 現在の項目を保存
LCDSelectCursorBar(cursor.pos); // 現在の項目を選択表示
}
void LCDCursorEnter()
{
uint16_t idEntry = cursor.pos + cursor.pageIdx * PAGE_NUM_ITEMS, entryPointOffset;
char fileType[4];
memset(fileType, '\0', sizeof(fileType));
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
TIM_TimeBaseInitStructure.TIM_Period = 999;
TIM_TimeBaseInitStructure.TIM_Prescaler = 99;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = (SystemCoreClock / 1000000UL) - 1;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStructure);
TIM_SetCounter(TIM1, 0);
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM1, ENABLE);
while(!TIM_GetITStatus(TIM1, TIM_IT_Update));
TIM_SetCounter(TIM1, 0);
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
LCDPutCursorBar(cursor.pos);
while(!TIM_GetITStatus(TIM1, TIM_IT_Update));
LCDSelectCursorBar(cursor.pos);
if(settings_mode){ // settings mode
if(strncmp(settings_p[idEntry].name, "..", 2) == 0){ // selected item is parent directry
settings_p = (settings_list_typedef*)settings_p[idEntry].next;
if(settings_p == NULL){ // back to root
settings_mode = 0;
fat.currentDirEntry = fat.rootDirEntry;
memcpy((char*)fat.currentDirName, (char*)root_str, sizeof(root_str));
free(fat.pfileList);
makeFileList();
LCDPrintFileList();
return;
}
strcpy((char*)fat.currentDirName, (char*)&settings_stack.name[--settings_stack.idx][0]);
fat.fileCnt = settings_stack.items[settings_stack.idx];
cursor.pages = fat.fileCnt / PAGE_NUM_ITEMS;
cursor.pageIdx = settings_stack.pos[settings_stack.idx] / PAGE_NUM_ITEMS;
cursor.pos = settings_stack.pos[settings_stack.idx] % PAGE_NUM_ITEMS;
LCDPrintSettingsList(SETTING_TYPE_DIR, 0, NULL);
return;
} else {
settings_list_typedef *settings_cur = &settings_p[idEntry];
if(settings_cur->next == NULL){
LCDPrintSettingsList(SETTING_TYPE_ITEM, idEntry, settings_cur->item);
return;
}
settings_stack.items[settings_stack.idx] = fat.fileCnt;
strcpy((char*)&settings_stack.name[settings_stack.idx][0], (char*)fat.currentDirName);
strcpy((char*)fat.currentDirName, settings_p[idEntry].name);
fat.fileCnt = settings_p[idEntry].itemCnt;
settings_p = settings_p[idEntry].next;
settings_stack.pos[settings_stack.idx] = idEntry;
cursor.pages = fat.fileCnt / PAGE_NUM_ITEMS;
cursor.pos = cursor.pageIdx = 0;
settings_stack.idx++;
LCDPrintSettingsList(settings_cur->type, 0, settings_cur->item);
if(settings_cur->func){
settings_cur->func(NULL);
}
return;
}
}
if((idEntry == 0) && (fat.currentDirEntry == fat.rootDirEntry)){ // exception for settings item
settings_mode = 1;
settings_stack.idx = 1;
strcpy((char*)fat.currentDirName, "Settings");
// fat.fileCnt = sizeof(settings_root_list) / sizeof(settings_root_list[0]);
fat.fileCnt = settings_root_list_fileCnt;
cursor.pages = fat.fileCnt / PAGE_NUM_ITEMS;
cursor.pos = cursor.pageIdx = 0;
settings_p = (settings_list_typedef*)settings_root_list;
LCDPrintSettingsList(0, 0, NULL);
return;
}
entryPointOffset = getListEntryPoint(idEntry); // リスト上にあるIDファイルエントリの先頭位置をセット
if(!(fbuf[entryPointOffset + ATTRIBUTES] & ATTR_DIRECTORY)){ // ファイルの属性をチェック
strncpy(fileType, (char*)&fbuf[entryPointOffset + 8], 3);
if(strcmp(fileType, "WAV") == 0){
LCDStatusStruct.idEntry = idEntry;
LCDStatusStruct.waitExitKey = FILE_TYPE_WAV;
return;
}
if(strcmp(fileType, "MP3") == 0){
LCDSetGramAddr(0, 0);
LCDStatusStruct.idEntry = idEntry;
LCDStatusStruct.waitExitKey = FILE_TYPE_MP3;
return;
}
if(strcmp(fileType, "MP4") == 0 || \
strcmp(fileType, "M4A") == 0 || \
strcmp(fileType, "M4P") == 0 || \
strcmp(fileType, "AAC") == 0){
LCDSetGramAddr(0, 0);
LCDStatusStruct.idEntry = idEntry;
LCDStatusStruct.waitExitKey = FILE_TYPE_AAC;
return;
}
if(strcmp(fileType, "JPG") == 0 || strcmp(fileType, "JPE") == 0){
LCDSetGramAddr(0, 0);
LCDStatusStruct.idEntry = idEntry;
LCDStatusStruct.waitExitKey = FILE_TYPE_JPG;
return;
}
if(strcmp(fileType, "MOV") == 0){
LCDSetGramAddr(0, 0);
LCDStatusStruct.idEntry = idEntry;
LCDStatusStruct.waitExitKey = FILE_TYPE_MOV;
return;
}
if(strcmp(fileType, "PCF") == 0){
LCDSetGramAddr(0, 0);
LCDStatusStruct.idEntry = idEntry;
LCDStatusStruct.waitExitKey = FILE_TYPE_PCF;
return;
}
touch.repeat = 1;
} else { // ファイルの属性がディレクトリ
// show circular progress bar animation until file list complete
LCDSetWindowArea(303, 1, 16, 16);
LCDSetGramAddr(303, 1);
LCDPutCmd(0x0022);
DMA_ProgressBar_Conf();
shuffle_play.flag_make_rand = 0; // clear shuffle flag
changeDir(idEntry); // idEntryのディレクトリに移動する
LCDPrintFileList(); // ファイルリスト表示
}
}
void LCDStoreBgImgToBuff(int startPosX, int startPosY, int width, int height, uint16_t *p)
{
uint32_t x, y;
for(y = 0;y < height;y++){
LCDSetGramAddr(startPosX, startPosY + y);
LCDPutCmd(0x0022);
LCD->RAM;
for(x = 0;x < width;x++){
*p++ = LCD->RAM;
}
}
}
void LCDPutBuffToBgImg(int startPosX, int startPosY, int width, int height, uint16_t *p)
{
uint32_t x, y;
for(y = 0;y < height;y++){
LCDSetGramAddr(startPosX, startPosY + y);
LCDPutCmd(0x0022);
for(x = 0;x < width;x++){
LCD->RAM = *p++;
}
}
}
/*
void LCDPutIcon(int startPosX, int startPosY, int width, int height, const uint16_t *d, const uint16_t *a)
{
int i, j, x, y = startPosY;
float alpha_ratio;
pixel_fmt_typedef pixel_alpha, pixel_fg, pixel_bg;
if(a == '\0'){
for(y = startPosY;y < startPosY + height;y++){
LCDSetGramAddr(startPosX, y);
LCDPutCmd(0x0022);
for(x = 0;x < width;x++){
LCDPutData(*d++);
}
}
return;
}
for(i = 0;i < height;i++){
x = startPosX;
for(j = 0;j < width;j++){
LCDSetGramAddr(x, y);
LCDPutCmd(0x0022);
LCD->RAM;
pixel_bg.color.d16 = LCD->RAM;
pixel_alpha.color.d16 = *a++;
pixel_fg.color.d16 = *d++;
alpha_ratio = (float)pixel_alpha.color.G / 63.0f;
// Foreground Image
pixel_fg.color.R *= alpha_ratio;
pixel_fg.color.G *= alpha_ratio;
pixel_fg.color.B *= alpha_ratio;
// Background Image
pixel_bg.color.R *= (1.0f - alpha_ratio);
pixel_bg.color.G *= (1.0f - alpha_ratio);
pixel_bg.color.B *= (1.0f - alpha_ratio);
// Add colors
pixel_fg.color.R += pixel_bg.color.R;
pixel_fg.color.G += pixel_bg.color.G;
pixel_fg.color.B += pixel_bg.color.B;
LCDSetGramAddr(x, y);
LCDPutCmd(0x0022);
LCDPutData(pixel_fg.color.d16);
x++;
}
y++;
}
}
*/
void LCDPutIcon(int startPosX, int startPosY, int width, int height, const uint16_t *d, const uint8_t *a)
{
int i, j, x, y = startPosY;
float alpha_ratio;
pixel_fmt_typedef pixel_fg, pixel_bg;
#define F_INV_255 (1.0f / 255.0f)
if(a == '\0'){
for(y = startPosY;y < startPosY + height;y++){
LCDSetGramAddr(startPosX, y);
LCDPutCmd(0x0022);
for(x = 0;x < width;x++){
LCDPutData(*d++);
}
}
return;
}
for(i = 0;i < height;i++){
x = startPosX;
for(j = 0;j < width;j++){
LCDSetGramAddr(x, y);
LCDPutCmd(0x0022);
LCD->RAM;
pixel_bg.color.d16 = LCD->RAM;
pixel_fg.color.d16 = *d++;
alpha_ratio = *a++ * F_INV_255; // Gray Scale
// Foreground Color
pixel_fg.color.R *= alpha_ratio;
pixel_fg.color.G *= alpha_ratio;
pixel_fg.color.B *= alpha_ratio;
// Background Color
pixel_bg.color.R *= (1.0f - alpha_ratio);
pixel_bg.color.G *= (1.0f - alpha_ratio);
pixel_bg.color.B *= (1.0f - alpha_ratio);
// Add colors
pixel_fg.color.R += pixel_bg.color.R;
pixel_fg.color.G += pixel_bg.color.G;
pixel_fg.color.B += pixel_bg.color.B;
LCDSetGramAddr(x, y);
LCDPutCmd(0x0022);
LCDPutData(pixel_fg.color.d16);
x++;
}
y++;
}
}
void LCDTouchPos()
{
LCDDrawSquare(touch.posX - 1, touch.posY - 1, 3, 3, WHITE);
}
int firstTouchedItem;
int currentTouchItem;
void LCDTouchReleased(void){
if(currentTouchItem == -1){
return;
// cursor.pageIdx = 0, cursor.pos = 0;
// LCDPrintFileList();
}else if(currentTouchItem == firstTouchedItem){
touch.repeat = 0;
LCDCursorEnter();
currentTouchItem = 0, firstTouchedItem = -999;
}
}
void LCDTouchPoint(){
if(!touch.repeat){
return;
}
currentTouchItem = (touch.posY / HEIGHT_ITEM) - 1; // 選択項目のカーソル位置取得
if(cursor.pageIdx == 0 && currentTouchItem < 0){
currentTouchItem = 0;
}
if(touch.posY > (LCD_HEIGHT - 5)){
currentTouchItem++;
}
if(touch.update == 0){
firstTouchedItem = currentTouchItem;
} else if(firstTouchedItem != currentTouchItem){
firstTouchedItem = -999;
}
if(currentTouchItem == cursor.pos) return; // 前項と同じ項目ならリターン
if( (currentTouchItem + cursor.pageIdx * PAGE_NUM_ITEMS) >= fat.fileCnt ) return; // ファイル数以上ならリターン
if(touch.posY < HEIGHT_ITEM){ // 上端まできたらスクロールアップ
LCDCursorUp();
return;
}
if(currentTouchItem >= PAGE_NUM_ITEMS){ // 下端まできたらスクロールダウン
LCDCursorDown();
return;
}
LCDPutCursorBar(cursor.pos); // 前項消去
LCDStoreCursorBar(currentTouchItem); // 現在の項目を保存
LCDSelectCursorBar(currentTouchItem); // 現在の項目を選択表示
cursor.pos = currentTouchItem;
return;
}
typedef struct{
uint16_t p[100][100];
}artRAM_typedef;
void dispArtWork(MY_FILE *input_file)
{
int i, j, t, image_type = 0;
int x, y, width, height;
float alpha, alpha_ratio;
pixel_fmt_typedef pixel_fg, pixel_bg;
uint8_t checkHeader[512];
struct jpeg_decompress_struct jdinfo;
struct jpeg_error_mgr jerr;
djpeg_dest_ptr dest_mgr = NULL;
if(input_file->clusterOrg == 0){
image_type = 1;
goto DISPLAY_ARTWORK;
}
my_fread(checkHeader, 1, 512, input_file);
for(i = 0;i < 511;i++){
if((checkHeader[i] == 0xff) && (checkHeader[i + 1] == 0xd8)){
break;
}
}
if(i >= 511){
debug.printf("\r\nArtWork: doesn't start with 0xffd8");
image_type = 1;
goto DISPLAY_ARTWORK;
}
my_fseek(input_file, -512, SEEK_CUR);
debug.printf("\r\n");
create_mpool();
/* Initialize the JPEG decompression object with default error handling. */
jdinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&jdinfo);
jdinfo.useMergedUpsampling = FALSE;
jdinfo.dct_method = JDCT_ISLOW;
jdinfo.dither_mode = JDITHER_FS;
jdinfo.two_pass_quantize = TRUE;
jdinfo.mem->max_memory_to_use = 30000UL;
/* Specify data source for decompression */
jpeg_stdio_src(&jdinfo, input_file);
/* Read file header, set default decompression parameters */
(void) jpeg_read_header(&jdinfo, TRUE);
if(jdinfo.err->msg_code == JERR_NO_IMAGE){
debug.printf("\r\nnArtWork: JPEG datastream contains no image");
image_type = 1;
goto DISPLAY_ARTWORK;
}
if(jdinfo.progressive_mode){ // progressivee jpeg not supported
debug.printf("\r\nnArtWork: progressive jpeg not supported");
image_type = 1;
goto DISPLAY_ARTWORK;
}
if(jdinfo.image_width > 640 || jdinfo.image_height > 640){
debug.printf("\r\nnArtWork: too large to display");
image_type = 1;
goto DISPLAY_ARTWORK;
}
for(i = 8;i >= 1; i--){
if((jdinfo.image_width * (float)i / 8.0f) <= 80 && \
(jdinfo.image_height * (float)i / 8.0f) <= 80){
break;
}
}
jdinfo.scale_denom = 8;
jdinfo.scale_num = i > 1 ? i : 1;
dest_mgr = jinit_write_ppm(&jdinfo);
/* Start decompressor */
(void) jpeg_start_decompress(&jdinfo);
typedef struct {
struct djpeg_dest_struct pub; /* public fields */
/* Usually these two pointers point to the same place: */
char *iobuffer; /* fwrite's I/O buffer */
JSAMPROW pixrow; /* decompressor output buffer */
size_t buffer_width; /* width of I/O buffer */
JDIMENSION samples_per_row; /* JSAMPLEs per output row */
} ppm_dest_struct;
typedef ppm_dest_struct * ppm_dest_ptr;
ppm_dest_ptr dest = (ppm_dest_ptr) dest_mgr;
#ifdef MY_DEBUG
debug.printf("\r\nx:%d y:%d width:%d height:%d", x, y, width, height);
#endif
DISPLAY_ARTWORK:
if(image_type == 1){
x = 22, y = 57, width = 74, height = 74;
} else {
debug.printf("\r\nsrc_size:%dx%d", jdinfo.image_width, jdinfo.image_height);
debug.printf("\r\ndst_size:%dx%d", jdinfo.output_width, jdinfo.output_height);
debug.printf("\r\nscale_num:%d scale_denom:%d", jdinfo.scale_num, jdinfo.scale_denom);
debug.printf("\r\nscale:%d/%d", jdinfo.scale_num, jdinfo.scale_denom);
width = jdinfo.output_width;
height = jdinfo.output_height;
x = (80 - width) / 2 - 1;
y = (80 - height) / 2 - 1;
x = (x > 0 ? x : 0) + 20;
y = (y > 0 ? y : 0) + 55;
}
float a, d, g;
int heightTop, heightBottom;
heightTop = height * 0.062f;
heightBottom = height - heightTop;
g = (float)(heightBottom - heightTop - height) / (float)(width * (heightTop - heightBottom));
a = 1.0f + (float)width * g;
d = heightTop * (1.0f / width + g);
artRAM_typedef *artRAM, *jpegRAM, *jpegRAM_mirror;
artRAM = (artRAM_typedef*)CCM_BASE;
jpegRAM = (artRAM_typedef*)(CCM_BASE + sizeof(artRAM_typedef));
jpegRAM_mirror = (artRAM_typedef*)(CCM_BASE + sizeof(artRAM_typedef) + sizeof(artRAM_typedef));
for(j = 0;j < height;j++){
LCDSetGramAddr(x, j + y);
LCDPutCmd(0x0022);
LCD->RAM;
for(i = 0;i < width;i++){
artRAM->p[i][j] = LCD->RAM;
}
}
uint16_t xx, yy;
if(image_type == 1){
for(j = 0;j < height;j++){
for(i = 0;i < width;i++){
jpegRAM->p[i][j] = music_art_default_74x74[i + j * width];
}
}
} else {
yy = 0;
while(jdinfo.output_scanline < jdinfo.output_height){
jpeg_read_scanlines(&jdinfo, dest_mgr->buffer, dest_mgr->buffer_height);
xx = 0;
for(i = 0;i < dest->buffer_width;i += 3){
jpegRAM->p[xx][yy] = (dest->pixrow[i + 2] >> 3) << 11 | (dest->pixrow[i + 1] >> 2) << 5 | dest->pixrow[i] >> 3;
xx++;
}
yy++;
}
(void) jpeg_finish_decompress(&jdinfo);
/* All done. */
#ifdef MY_DEBUG
if(jerr.num_warnings == EXIT_WARNING){
USARTPutString("\r\nEXIT_WARNING");
}else if(jerr.num_warnings == EXIT_SUCCESS){
USARTPutString("\r\nEXIT_SUCCESS");
}
debug.printf("\r\nlast msg:%s", jdinfo.err->jpeg_message_table[jdinfo.err->last_jpeg_message]);
#endif
jpeg_destroy_decompress(&jdinfo);
}
pixel_fmt_typedef pixel, pixelBox[2][2], pixelV1, pixelV2;
int ii, jj, inverse;
float ratioX0, ratioX1, ratioY0, ratioY1, fx, fy;
xx = 0, yy = 0;
for(j = 0;j < height;j++){
xx = 0;
LCDSetGramAddr(xx + x, yy + y);
LCDPutCmd(0x0022);
for(i = 0;i < width;i++){
// fx = (float)(xx * a) / (float)(1.0f + xx * g);
// fy = (float)(xx * d + yy) / (float)(1.0f + xx * g);
fx = (float)(xx) / (float)(a - g * xx);
fy = (float)(1 + g * fx) * yy - d * fx;
ii = (int)fx;
jj = (int)fy;
if(fy < 0.0f){
inverse = 1;
fy = -fy;
} else {
inverse = 0;
}
ratioX0 = 1.0f - (fx - (float)ii);
ratioX1 = 1.0f - ratioX0;
ratioY0 = 1.0f - (fy - (float)jj);
ratioY1 = 1.0f - ratioY0;
if((ii >= 0 && ii < width) && (jj >= 0 && jj < height)){
pixelBox[0][0].color.d16 = jpegRAM->p[ii][jj];
if(!inverse){
if((ii + 1) < width && (jj + 1) < height){
pixelBox[1][1].color.d16 = jpegRAM->p[ii + 1][jj + 1];
} else {
pixelBox[1][1].color.d16 = artRAM->p[ii][jj];
}
if((ii + 1) < width){
pixelBox[1][0].color.d16 = jpegRAM->p[ii + 1][jj];
} else {
pixelBox[1][0].color.d16 = artRAM->p[ii][jj];
}
if((jj + 1) < height){
pixelBox[0][1].color.d16 = jpegRAM->p[ii][jj + 1];
} else {
pixelBox[0][1].color.d16 = artRAM->p[ii][jj];
}
} else {
if((ii + 1) < width){
pixelBox[1][0].color.d16 = jpegRAM->p[ii + 1][jj];
} else {
pixelBox[1][0].color.d16 = artRAM->p[ii][jj];
}
pixelBox[0][1].color.d16 = artRAM->p[ii][(jj - 1) >= 0 ? (jj - 1) : 0];
pixelBox[1][1].color.d16 = artRAM->p[ii + 1][(jj - 1) >= 0 ? (jj - 1) : 0];
}
pixelV1.color.R = __USAT(pixelBox[0][0].color.R * ratioX0 + pixelBox[1][0].color.R * ratioX1, 5);
pixelV1.color.G = __USAT(pixelBox[0][0].color.G * ratioX0 + pixelBox[1][0].color.G * ratioX1, 6);
pixelV1.color.B = __USAT(pixelBox[0][0].color.B * ratioX0 + pixelBox[1][0].color.B * ratioX1, 5);
pixelV2.color.R = __USAT(pixelBox[0][1].color.R * ratioX0 + pixelBox[1][1].color.R * ratioX1, 5);
pixelV2.color.G = __USAT(pixelBox[0][1].color.G * ratioX0 + pixelBox[1][1].color.G * ratioX1, 6);
pixelV2.color.B = __USAT(pixelBox[0][1].color.B * ratioX0 + pixelBox[1][1].color.B * ratioX1, 5);
pixel.color.R = __USAT(pixelV1.color.R * ratioY0 + pixelV2.color.R * ratioY1, 5);
pixel.color.G = __USAT(pixelV1.color.G * ratioY0 + pixelV2.color.G * ratioY1, 6);
pixel.color.B = __USAT(pixelV1.color.B * ratioY0 + pixelV2.color.B * ratioY1, 5);
// LCDSetGramAddr(xx + x, yy + y);
// LCDPutCmd(0x0022);
LCD->RAM = pixel.color.d16;
}
xx++;
}
yy++;
}
DRAW_REFLECTION:
// y = y + height - 3;
y = y + height;
for(j = 0;j < height;j++){
LCDSetGramAddr(x, j + y);
LCDPutCmd(0x0022);
LCD->RAM;
for(i = 0;i < width;i++){
artRAM->p[width - 1 - i][height - 1 - j] = LCD->RAM;
// artRAM->p[i][j] = LCD->RAM;
}
}
for(j = 0;j < height;j++){
for(i = 0;i < width;i++){
jpegRAM_mirror->p[width - 1 - i][j] = jpegRAM->p[i][j];
}
}
jpegRAM = jpegRAM_mirror;
xx = 0, yy = 0;
for(j = 0;j < height;j++){
alpha = (float)j / (float)(height / 3);
alpha = alpha <= 1.0f ? alpha : 1.0f;
alpha_ratio = 1.0f - alpha;
xx = 0;
for(i = 0;i < width;i++){
fx = (float)(-xx + width - 1) / (a - g * (-xx + width - 1));
// fy = (1.0f + g * fx) * (-yy + height - 1) - d * fx;
// fx = (float)(xx) / (float)(a - g * xx);
fy = (1.0f + g * fx) * (-yy + height - 1) - d * fx;
ii = (int)fx;
jj = (int)fy;
if(fy < 0.0f){
fy = -fy;
inverse = 1;
} else {
inverse = 0;
}
ratioX0 = 1.0f - (fx - (float)ii);
ratioX1 = 1.0f - ratioX0;
ratioY0 = 1.0f - (fy - (float)jj);
ratioY1 = 1.0f - ratioY0;
if((ii >= 0 && ii < width) && (jj >= 0 && jj < height)){
pixelBox[0][0].color.d16 = jpegRAM->p[ii][jj];
if(!inverse){
if((ii + 1) < width && (jj + 1) < height){
pixelBox[1][1].color.d16 = jpegRAM->p[ii + 1][jj + 1];
} else {
pixelBox[1][1].color.d16 = artRAM->p[ii][jj];
}
if((ii + 1) < width){
pixelBox[1][0].color.d16 = jpegRAM->p[ii + 1][jj];
} else {
pixelBox[1][0].color.d16 = artRAM->p[ii][jj];
}
if((jj + 1) < height){
pixelBox[0][1].color.d16 = jpegRAM->p[ii][jj + 1];
} else {
pixelBox[0][1].color.d16 = artRAM->p[ii][jj];
}
} else {
if((ii + 1) < width){
pixelBox[1][0].color.d16 = jpegRAM->p[ii + 1][jj];
} else {
pixelBox[1][0].color.d16 = artRAM->p[ii][jj];
}
pixelBox[0][1].color.d16 = artRAM->p[ii][(jj - 1) >= 0 ? (jj - 1) : 0];
pixelBox[1][1].color.d16 = artRAM->p[ii + 1][(jj - 1) >= 0 ? (jj - 1) : 0];
}
pixelV1.color.R = __USAT(pixelBox[0][0].color.R * ratioX0 + pixelBox[1][0].color.R * ratioX1, 5);
pixelV1.color.G = __USAT(pixelBox[0][0].color.G * ratioX0 + pixelBox[1][0].color.G * ratioX1, 6);
pixelV1.color.B = __USAT(pixelBox[0][0].color.B * ratioX0 + pixelBox[1][0].color.B * ratioX1, 5);
pixelV2.color.R = __USAT(pixelBox[0][1].color.R * ratioX0 + pixelBox[1][1].color.R * ratioX1, 5);
pixelV2.color.G = __USAT(pixelBox[0][1].color.G * ratioX0 + pixelBox[1][1].color.G * ratioX1, 6);
pixelV2.color.B = __USAT(pixelBox[0][1].color.B * ratioX0 + pixelBox[1][1].color.B * ratioX1, 5);
pixel.color.R = __USAT(pixelV1.color.R * ratioY0 + pixelV2.color.R * ratioY1, 5);
pixel.color.G = __USAT(pixelV1.color.G * ratioY0 + pixelV2.color.G * ratioY1, 6);
pixel.color.B = __USAT(pixelV1.color.B * ratioY0 + pixelV2.color.B * ratioY1, 5);
// Foreground Image
pixel.color.R *= alpha_ratio;
pixel.color.G *= alpha_ratio;
pixel.color.B *= alpha_ratio;
pixel_bg.color.d16 = artRAM->p[width - 1 - xx][height - 1 - yy];
// Background Image
pixel_bg.color.R *= (1.0f - alpha_ratio);
pixel_bg.color.G *= (1.0f - alpha_ratio);
pixel_bg.color.B *= (1.0f - alpha_ratio);
// Add colors
pixel.color.R += pixel_bg.color.R;
pixel.color.G += pixel_bg.color.G;
pixel.color.B += pixel_bg.color.B;
// LCDSetGramAddr(-xx + width - 1 + x, -yy + height - 1 + y);
LCDSetGramAddr(xx + x, yy + y);
LCDPutCmd(0x0022);
LCD->RAM = pixel.color.d16;
}
xx++;
}
yy++;
}
//DRAW_REFLECTION:
/*
LCDSetWindowArea(0, 0, LCD_WIDTH, LCD_HEIGHT);
t = 5;
yy = height - 1;
for(j = y + height - 1;j >= y;j--){
alpha = ((float)t * 2.3f) / (float)(height);
alpha = alpha <= 1.0f ? alpha : 1.0f;
alpha_ratio = 1.0f - alpha;
xx = 0;
for(i = x;i < x + width;i++){
// LCDSetGramAddr(i, j);
// LCDPutCmd(0x0022);
// LCD->RAM;
// pixel_fg.color.d16 = LCD->RAM;
pixel_fg.color.d16 = jpegRAM->p[xx][yy];
// Foreground Image
pixel_fg.color.R *= alpha_ratio;
pixel_fg.color.G *= alpha_ratio;
pixel_fg.color.B *= alpha_ratio;
LCDSetGramAddr(i, y + height + t);
LCDPutCmd(0x0022);
LCD->RAM;
pixel_bg.color.d16 = LCD->RAM;
// Background Image
pixel_bg.color.R *= (1.0f - alpha_ratio);
pixel_bg.color.G *= (1.0f - alpha_ratio);
pixel_bg.color.B *= (1.0f - alpha_ratio);
// Add colors
pixel_fg.color.R += pixel_bg.color.R;
pixel_fg.color.G += pixel_bg.color.G;
pixel_fg.color.B += pixel_bg.color.B;
LCDSetGramAddr(i, y + height + t);
LCDPutCmd(0x0022);
LCDPutData(pixel_fg.color.d16);
xx++;
}
t++;
yy--;
}
*/
// LCDSetWindowArea(0, 0, LCD_WIDTH, LCD_HEIGHT);
}
|
1137519-player
|
lcd.c
|
C
|
lgpl
| 63,611
|
/*
* STM32F4-Discovery Motion Player Project
* by Tonsuke
*
* v1.12
* 2014/03/07
*
* WIKI
* http://motionplayer.wiki.fc2.com
*
* Git Source
* https://code.google.com/p/motion-player-project/
*/
#include "stm32f4xx_conf.h"
#include "fat.h"
#include "sd.h"
#include "lcd.h"
#include "dojpeg.h"
#include "mjpeg.h"
#include "aac.h"
#include "mp3.h"
#include "sound.h"
#include "pcf_font.h"
#include "usart.h"
#include "xmodem.h"
#include "xpt2046.h"
#include "icon.h"
#include "settings.h"
#include "mpool.h"
#include "usbd_msc_core.h"
#include "usbd_usr.h"
#include "usbd_desc.h"
#include "usb_conf.h"
USB_OTG_CORE_HANDLE *pUSB_OTG_dev;
volatile int8_t usb_msc_enable = 0, usb_msc_card_accessing = 0, usb_msc_progressbar_enable = 0, photo_frame_flag = 0;
void TIM8_UP_TIM13_IRQHandler(void) // Back Light & Sleep control timer
{
if(TIM_GetITStatus(TIM8, TIM_IT_Update)){
TIM_ClearITPendingBit(TIM8, TIM_IT_Update);
if(usb_msc_enable){
if(usb_msc_card_accessing){
if(usb_msc_progressbar_enable){
TIM_Cmd(TIM1, ENABLE); // Start displaying progress bar
}
usb_msc_progressbar_enable = 1;
} else {
TIM_Cmd(TIM1, DISABLE); // Stop displaying progress bar
int i;
for(i = 0;i < 16 * 16;i++){ // Clear progress bar drawings
LCDPutData(colorc[BLACK]);
}
usb_msc_progressbar_enable = 0;
}
usb_msc_card_accessing = 0;
return;
}
if(settings_group.disp_conf.time2sleep == 0){ // Always On
return;
}
++time.curTime;
if((abs(time.curTime - time.prevTime) >= (settings_group.disp_conf.time2sleep / 2)) && !time.flags.dimLight && time.flags.enable){ // Dim Light
TIM_SetCompare2(TIM4, (int)(500 * (float)settings_group.disp_conf.brightness / 100.0f) - 1);
time.flags.dimLight = 1;
}
if(abs(time.curTime - time.prevTime) >= settings_group.disp_conf.time2sleep && time.flags.dimLight && time.flags.enable){ // Sleep Enable
time.flags.stop_mode = 1;
}
}
}
void MassStorage()
{
settings_group.disp_conf.time2sleep = 0;
TOUCH_PINIRQ_DISABLE;
touch.func = touch_empty_func;
LCDClear(LCD_WIDTH, LCD_HEIGHT, BLACK);
LCDPutIcon(75, 95, 22, 22, usb_22x22, usb_22x22_alpha);
LCDGotoXY(100, 100);
LCDPutString("USB Connect to HOST", WHITE);
// show circular progress bar animation until file list complete
MergeCircularProgressBar(0);
LCDSetWindowArea(147, 150, 16, 16);
LCDSetGramAddr(147, 150);
LCDPutCmd(0x0022);
DMA_ProgressBar_Conf();
SystemInit2(168);
SystemCoreClockUpdate();
USARTInit();
USB_OTG_CORE_HANDLE USB_OTG_dev;
pUSB_OTG_dev = &USB_OTG_dev;
USBD_Init(&USB_OTG_dev,
USB_OTG_FS_CORE_ID,
&USR_desc,
&USBD_MSC_cb,
&USR_cb);
while(1){};
}
void mem_clean(){
void *p;
p = malloc(sizeof(mempool));
memset(p, 0, sizeof(mempool));
free(p);
}
int main(void)
{
char extensionName[4];
int8_t ret, prevRet = 0, djpeg_arrows, arrow_clicked;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
do{
SYSCFG_CompensationCellCmd(ENABLE);
}while(SYSCFG_GetCompensationCellStatus() == RESET);
NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x00000);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
mem_clean();
SETTINGS_Init();
USARTInit();
if(C_PCFFontInit((uint32_t)internal_flash_pcf_font, (size_t)_sizeof_internal_flash_pcf_font) != -1){
debug.printf("\r\ninternal flash font loaded.");
LCD_FUNC.putChar = C_PCFPutChar;
LCD_FUNC.putWideChar = C_PCFPutChar;
LCD_FUNC.getCharLength = C_PCFGetCharPixelLength;
} else {
debug.printf("\r\ninternal flash font load failed.");
}
debug.printf("\r\nMCU_IDCODE:%08x", *(uint32_t*)0xE0042000);
uint32_t mcu_revision = *(uint32_t*)0xE0042000 & 0xffff0000;
debug.printf("\r\nRevision: ");
switch(mcu_revision){
case 0x10000000:
debug.printf("A");
break;
case 0x20000000:
debug.printf("B");
break;
case 0x10010000:
debug.printf("Z");
break;
default:
break;
}
LCDInit();
XPT2046Init();
SDInit();
if(!initFat()){
const char fat_init_succeeded_str[] = "\r\nFat initialization succeeded.";
debug.printf(fat_init_succeeded_str);
LCDPutString(fat_init_succeeded_str, WHITE);
} else {
const char fat_init_failed_str[] = "\r\nFat initialization failed.";
debug.printf(fat_init_failed_str);
LCDPutString(fat_init_failed_str, WHITE);
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_8)){
debug.printf("\r\nno card inserted.");
LCDPutString("\r\nno card inserted.", WHITE);
}
TouchPenIRQ_Enable();
TouchPenReleaseIRQ_Enable();
settings_group.disp_conf.time2sleep = 10;
LCDBackLightTimerInit();
while(1){
if(time.flags.stop_mode){
LCDBackLightDisable();
PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);
SystemInit();
SystemCoreClockUpdate();
LCDBackLightInit();
time.flags.stop_mode = 0;
}
}
}
if(fat.fsType == FS_TYPE_FAT16){
debug.printf("\r\nFileSystem:FAT16");
} else if (fat.fsType == FS_TYPE_FAT32){
debug.printf("\r\nFileSystem:FAT32");
}
debug.printf("\r\nCluster Size:%dKB", (fat.sectorsPerCluster * 512) / 1024);
USARTPutString("\r\nStarting...");
if(settings_group.filer_conf.fontEnabled){
if(PCFFontInit(getIdByName("FONT.PCF")) != -1){
debug.printf("\r\nexternal font loaded.");
LCD_FUNC.putChar = PCFPutChar;
LCD_FUNC.putWideChar = PCFPutChar;
LCD_FUNC.getCharLength = PCFGetCharPixelLength;
} else {
debug.printf("\r\nexternal font load failed.");
}
}
LCDPrintFileList();
debug.printf("\r\nSystemCoreClock:%dMHz", SystemCoreClock / 1000000);
TouchPenIRQ_Enable();
TouchPenReleaseIRQ_Enable();
navigation_loop_mode = NAV_PLAY_ENTIRE;
bass_boost_mode = 0;
reverb_effect_mode = 0;
vocal_cancel_mode = 0;
touch.click = 0;
LCDBackLightTimerInit();
while(1){
if(usb_msc_enable){ // Start Mass Storage Mode
MassStorage();
}
if(time.flags.stop_mode){ // Enter Stop Mode
LCDBackLightDisable();
PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI);
SystemInit();
SystemCoreClockUpdate();
do{
SYSCFG_CompensationCellCmd(ENABLE);
}while(SYSCFG_GetCompensationCellStatus() == RESET);
LCDBackLightInit();
time.flags.stop_mode = 0;
}
switch (LCDStatusStruct.waitExitKey) {
case FILE_TYPE_WAV: // WAV
case FILE_TYPE_MP3: // MP3
case FILE_TYPE_AAC: // AAC
case FILE_TYPE_MOV: // Motion Jpeg
shuffle_play.play_continuous = 0;
shuffle_play.mode_changed = 0;
shuffle_play.initial_mode = navigation_loop_mode;
do{
ret = PlayMusic(LCDStatusStruct.idEntry);
debug.printf("\r\nret:%d LCDStatusStruct.idEntry:%d fat.fileCnt:%d navigation_loop.mode:%d", ret, LCDStatusStruct.idEntry, fat.fileCnt, navigation_loop_mode);
switch(ret){
case RET_PLAY_NORM:
switch(navigation_loop_mode){
case NAV_ONE_PLAY_EXIT:
LCDStatusStruct.waitExitKey = 0;
ret = RET_PLAY_STOP;
break;
case NAV_INFINITE_ONE_PLAY:
debug.printf("\r\nNAV_INFINITE_ONE_PLAY:%d", LCDStatusStruct.idEntry);
LCDStatusStruct.waitExitKey = 1;
continue;
case NAV_PLAY_ENTIRE:
case NAV_INFINITE_PLAY_ENTIRE:
case NAV_SHUFFLE_PLAY:
goto PLAY_NEXT;
default:
break;
}
break;
case RET_PLAY_NEXT: // 次へ
PLAY_NEXT:
if(shuffle_play.flag_make_rand && shuffle_play.mode_changed && (navigation_loop_mode != NAV_SHUFFLE_PLAY)){
if(shuffle_play.initial_mode != NAV_SHUFFLE_PLAY){
LCDStatusStruct.idEntry = shuffle_play.pRandIdEntry[LCDStatusStruct.idEntry];
}
shuffle_play.mode_changed = 0;
}
prevRet = LCDStatusStruct.idEntry;
LCDStatusStruct.waitExitKey = 1;
if(++LCDStatusStruct.idEntry >= fat.fileCnt){
if(navigation_loop_mode == NAV_INFINITE_PLAY_ENTIRE || navigation_loop_mode == NAV_SHUFFLE_PLAY){
LCDStatusStruct.idEntry = 1;
LCDStatusStruct.waitExitKey = 1;
continue;
} else {
LCDStatusStruct.idEntry--;
LCDStatusStruct.waitExitKey = 0;
ret = RET_PLAY_STOP;
}
}
break;
case RET_PLAY_PREV: // 前へ
prevRet = RET_PLAY_PREV;
LCDStatusStruct.waitExitKey = 1;
if(--LCDStatusStruct.idEntry <= 0){
LCDStatusStruct.idEntry = fat.fileCnt - 1;
}
continue;
case RET_PLAY_INVALID: // invalid type
ret = RET_PLAY_STOP;
LCDStatusStruct.waitExitKey = 0;
if(prevRet == RET_PLAY_PREV){
LCDStatusStruct.idEntry++;
} else {
LCDStatusStruct.idEntry--;
}
break;
default:
break;
}
}while((ret != RET_PLAY_STOP) || LCDStatusStruct.waitExitKey);
if(shuffle_play.flag_make_rand && (navigation_loop_mode == NAV_SHUFFLE_PLAY)){
LCDStatusStruct.idEntry = shuffle_play.pRandIdEntry[LCDStatusStruct.idEntry];
}
cursor.pos = LCDStatusStruct.idEntry % PAGE_NUM_ITEMS;
cursor.pageIdx = LCDStatusStruct.idEntry / PAGE_NUM_ITEMS;
MergeCircularProgressBar(1);
LCDPrintFileList();
touch.click = 0;
break;
case FILE_TYPE_JPG: // JPEG
arrow_clicked = 0;
ret = 0;
photo_frame_flag = 0;
// uint8_t play_flag = 0;
// int WAV_idEntry;
do{
djpeg_arrows = DJPEG_ARROW_LEFT | DJPEG_ARROW_RIGHT;
if((ret & DJPEG_PLAY)){
djpeg_arrows |= DJPEG_PLAY;
if(LCDStatusStruct.idEntry >= fat.fileCnt){
LCDStatusStruct.idEntry = 1;
}
}
if(LCDStatusStruct.idEntry <= 1){
djpeg_arrows &= ~DJPEG_ARROW_LEFT;
} else {
if(setExtensionName(extensionName, LCDStatusStruct.idEntry - 1)){ // check if current - 1 entry is JPEG
if(strncmp(extensionName, "JPG", 3) != 0 && strncmp(extensionName, "JPE", 3) != 0){
djpeg_arrows &= ~DJPEG_ARROW_LEFT;
}
} else {
djpeg_arrows &= ~DJPEG_ARROW_LEFT;
}
}
if(LCDStatusStruct.idEntry >= (fat.fileCnt - 1)){ // if id entry reaches end of files
djpeg_arrows &= ~DJPEG_ARROW_RIGHT;
} else {
if(setExtensionName(extensionName, LCDStatusStruct.idEntry + 1)){ // check if current - 1 entry is JPEG
if(strncmp(extensionName, "JPG", 3) != 0 && strncmp(extensionName, "JPE", 3) != 0){
djpeg_arrows &= ~DJPEG_ARROW_RIGHT;
}
} else {
djpeg_arrows &= ~DJPEG_ARROW_RIGHT;
}
}
if(setExtensionName(extensionName, LCDStatusStruct.idEntry)){ // check if current entry is JPEG
if(strncmp(extensionName, "JPG", 3) == 0 || strncmp(extensionName, "JPE", 3) == 0){
ret = dojpeg(LCDStatusStruct.idEntry, djpeg_arrows, arrow_clicked);
}
}
if(ret == DJPEG_ARROW_LEFT){
arrow_clicked = 1;
LCDStatusStruct.idEntry--;
} else if(ret == DJPEG_ARROW_RIGHT){
arrow_clicked = 1;
LCDStatusStruct.idEntry++;
} else if(ret == DJPEG_PLAY){
arrow_clicked = 0;
if(!photo_frame_flag){
photo_frame_flag = 1;
} else {
LCDStatusStruct.idEntry++;
}
/* Experimental photo frame music
if(dac_intr.comp == 1){
play_flag = 0;
}
if(!play_flag){
play_flag = 1;
WAV_idEntry = 0;
while(++WAV_idEntry <= (fat.fileCnt - 1)){
if(setExtensionName(extensionName, WAV_idEntry)){
if(strncmp(extensionName, "WAV", 3) == 0){
debug.printf("\r\nFound WAV file at:%d", WAV_idEntry);
PlaySoundPhotoFrame(WAV_idEntry);
break;
}
}
}
}
*/
}
if(LCDStatusStruct.idEntry){
cursor.pos = LCDStatusStruct.idEntry % PAGE_NUM_ITEMS;
cursor.pageIdx = LCDStatusStruct.idEntry / PAGE_NUM_ITEMS;
}
}while(LCDStatusStruct.waitExitKey);
/* Experimental photo frame music
NVIC_InitTypeDef NVIC_InitStructure;
DMA_ITConfig(DMA1_Stream1, DMA_IT_TC | DMA_IT_HT, DISABLE);
DMA_Cmd(DMA1_Stream1, DISABLE);
AUDIO_OUT_SHUTDOWN;
dac_intr.sound_reads = 0;
// Disable DMA1_Stream1 gloabal Interrupt
NVIC_InitStructure.NVIC_IRQChannel = DMA1_Stream1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
NVIC_Init(&NVIC_InitStructure);
my_fclose(dac_intr.fp);
*/
MergeCircularProgressBar(1);
LCDPrintFileList();
touch.click = 0;
break;
case FILE_TYPE_PCF: // Display Font
if(PCFFontInit(LCDStatusStruct.idEntry) != -1){
debug.printf("\r\nexternal font loaded.");
LCD_FUNC.putChar = PCFPutChar;
LCD_FUNC.putWideChar = PCFPutChar;
LCD_FUNC.getCharLength = PCFGetCharPixelLength;
} else {
debug.printf("\r\nexternal font load failed.");
}
LCDPrintFileList();
LCDStatusStruct.waitExitKey = 0;
touch.click = 0;
break;
default:
break;
}
}
return 0;
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
debug.printf("\r\nWrong parameters value: file %s on line %d\r\n", file, line);
/* Infinite loop */
while (1)
{
}
}
#endif
|
1137519-player
|
main.c
|
C
|
lgpl
| 13,410
|
/**
******************************************************************************
* @file stm32f4xx_it.c
* @author MCD Application Team
* @version V1.0.0
* @date 19-September-2011
* @brief Main Interrupt Service Routines.
* This file provides all exceptions handler and peripherals interrupt
* service routine.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_it.h"
#include "usart.h"
#include "stdlib.h"
#include "usb_core.h"
#include "usbd_core.h"
#include "usb_conf.h"
//#include "lcd_log.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
extern USB_OTG_CORE_HANDLE *pUSB_OTG_dev;
/* Private function prototypes -----------------------------------------------*/
extern uint32_t USBD_OTG_ISR_Handler (USB_OTG_CORE_HANDLE *pdev);
#ifdef USB_OTG_HS_DEDICATED_EP1_ENABLED
extern uint32_t USBD_OTG_EP1IN_ISR_Handler (USB_OTG_CORE_HANDLE *pdev);
extern uint32_t USBD_OTG_EP1OUT_ISR_Handler (USB_OTG_CORE_HANDLE *pdev);
#endif
/******************************************************************************/
/* Cortex-M3 Processor Exceptions Handlers */
/******************************************************************************/
/**
* @brief This function handles NMI exception.
* @param None
* @retval None
*/
void NMI_Handler(void)
{
}
void WWDG_IRQHandler(void)
{
}
/**
* @brief This function handles Hard Fault exception.
* @param None
* @retval None
*/
void HardFault_Handler(void)
{
debug.printf("\r\nHardFault");
void *test;
debug.printf("\r\ntest:%p", &test);
void *heap;
heap = malloc(1);
debug.printf("\r\nheap:%p", heap);
free((void*)heap);
IWDG_Enable();
/* Go to infinite loop when Hard Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Memory Manage exception.
* @param None
* @retval None
*/
void MemManage_Handler(void)
{
debug.printf("\r\nMemManage");
/* Go to infinite loop when Memory Manage exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Bus Fault exception.
* @param None
* @retval None
*/
void BusFault_Handler(void)
{
debug.printf("\r\nBusFault");
/* Go to infinite loop when Bus Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Usage Fault exception.
* @param None
* @retval None
*/
void UsageFault_Handler(void)
{
debug.printf("\r\nUsageFault");
/* Go to infinite loop when Usage Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles SVCall exception.
* @param None
* @retval None
*/
void SVC_Handler(void)
{
}
/**
* @brief This function handles Debug Monitor exception.
* @param None
* @retval None
*/
void DebugMon_Handler(void)
{
}
/**
* @brief This function handles PendSVC exception.
* @param None
* @retval None
*/
void PendSV_Handler(void)
{
}
/**
* @brief This function handles SysTick Handler.
* @param None
* @retval None
*/
void SysTick_Handler(void)
{
}
/**
* @brief This function handles OTG_HS Handler.
* @param None
* @retval None
*/
#ifdef USE_USB_OTG_HS
void OTG_HS_IRQHandler(void)
{
USBD_OTG_ISR_Handler (&USB_OTG_dev);
}
#endif
#ifdef USE_USB_OTG_FS
void OTG_FS_IRQHandler(void)
{
USBD_OTG_ISR_Handler (pUSB_OTG_dev);
}
#endif
#ifdef USB_OTG_HS_DEDICATED_EP1_ENABLED
/**
* @brief This function handles EP1_IN Handler.
* @param None
* @retval None
*/
void OTG_HS_EP1_IN_IRQHandler(void)
{
USBD_OTG_EP1IN_ISR_Handler (&USB_OTG_dev);
}
/**
* @brief This function handles EP1_OUT Handler.
* @param None
* @retval None
*/
void OTG_HS_EP1_OUT_IRQHandler(void)
{
USBD_OTG_EP1OUT_ISR_Handler (&USB_OTG_dev);
}
#endif
/******************************************************************************/
/* STM32Fxxx Peripherals Interrupt Handlers */
/* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */
/* available peripheral interrupt handler's name please refer to the startup */
/* file (startup_stm32fxxx.s). */
/******************************************************************************/
/**
* @brief This function handles PPP interrupt request.
* @param None
* @retval None
*/
/*void PPP_IRQHandler(void)
{
}*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
|
1137519-player
|
stm32f4xx_it.c
|
C
|
lgpl
| 5,716
|
/*
* fx.h
*
* Created on: 2013/02/23
* Author: Tonsuke
*/
#ifndef FX_H_
#define FX_H_
#include <stdint.h>
#include <stddef.h>
typedef struct {
uint32_t *ptr;
int idx;
size_t size;
}delay_buffer_typedef;
typedef struct {
int repeat[4], delay[4], fs, number;
float amp[4], clipper[4], coeff_table[4][10];
delay_buffer_typedef *delay_buffer;
size_t num_blocks;
}REVERB_Struct_Typedef;
typedef struct {
int number, fs;
float fc, Q, g, a[3], b[3], A[4][3], B[4][3];
delay_buffer_typedef *delay_buffer;
size_t num_blocks, sbuf_size;
}IIR_Filter_Struct_Typedef;
extern void REVERB_Set_Prams(REVERB_Struct_Typedef *RFX);
extern void REVERB_Init(REVERB_Struct_Typedef *RFX, int n);
extern void REVERB(REVERB_Struct_Typedef *RFX, uint32_t *out_ptr);
extern void IIR_Set_Params(IIR_Filter_Struct_Typedef *IIR);
extern void IIR_Filter(IIR_Filter_Struct_Typedef *IIR, uint32_t *out_ptr, float *sout_ptr_A, float *sout_ptr_B);
extern void IIR_resonator(float fc, float Q, float a[], float b[]);
extern void IIR_LPF(float fc, float Q, float a[], float b[]);
extern void IIR_HPF(float fc, float Q, float a[], float b[]);
extern void IIR_low_shelving(float fc, float Q, float g, float a[], float b[]);
extern void IIR_peaking(float fc, float Q, float g, float a[], float b[]);
//float fc, fcv, Q, g, a[3], b[3], A[10][3], B[10][3];
#endif /* FX_H_ */
|
1137519-player
|
fx.h
|
C
|
lgpl
| 1,368
|
/*
* delay.h
*
* Created on: 2011/10/31
* Author: Tonsuke
*/
#ifndef DELAY_H_
#define DELAY_H_
extern void Delayms(int i);
extern void Delay(int i);
#endif /* DELAY_H_ */
|
1137519-player
|
delay.h
|
C
|
lgpl
| 187
|