最近有做一些FLAC播放的工作,做点简单总结用于个人学习。主要参考官网ttp://flac.sourceforge.net/
FLAC结构与编码
FLAC流数据组织结构可用如下图表示,详情参考1 STREAM基本结构:
-The four byte string "fLaC"
-The STREAMINFO metadata block
--metadata header
---metadata type
---metadata data length
--real metadata data
-Zero or more other metadata blocks
-One or more audio frames
--frame header
--subframe
---subframe header
---subframe data
--frame footer
一些背景以及编码知识如下:
This is a detailed description of the FLAC format. There is also a companion document that describes FLAC-to-Ogg mapping.
For a user-oriented overview, see About the FLAC Format.
Table of Contents
· Scope
· Blocking
· Format
· Specification
o STREAM
§ METADATA_BLOCK_VORBIS_COMMENT
o
§ FRAME
§ SUBFRAME
§ RESIDUAL
§ RESIDUAL_CODING_METHOD_PARTITIONED_RICE
§ RESIDUAL_CODING_METHOD_PARTITIONED_RICE2
Acknowledgments
FLAC owes much to the many people who have advanced the audio compression field so freely. For instance:
· A. J. Robinson for his work on Shorten; his paper is a good starting point on some of the basic methods used by FLAC. FLAC trivially extends and improves the fixed predictors, LPC coefficient quantization, and Rice coding used in Shorten.
· S. W. Golomb and Robert F. Rice; their universal codes are used by FLAC's entropy coder.
· N. Levinson and J. Durbin; the reference encoder uses an algorithm developed and refined by them for determining the LPC coefficients from the autocorrelation coefficients.
· And of course, Claude Shannon
Scope
It is a known fact that no algorithm can losslessly compress all possible input, so most compressors restrict themselves to a useful domain and try to work as well as possible within that domain. FLAC's domain is audio data. Though it can losslessly code any input, only certain kinds of input will get smaller. FLAC exploits the fact that audio data typically has a high degree of sample-to-sample correlation.
Within the audio domain, there are many possible subdomains. For example: low bitrate speech, high-bitrate multi-channel music, etc. FLAC itself does not target a specific subdomain but many of the default parameters of the reference encoder are tuned to CD-quality music data (i.e. 44.1kHz, 2 channel, 16 bits per sample). The effect of the encoding parameters on different kinds of audio data will be examined later.
Architecture
Similar to many audio coders, a FLAC encoder has the following stages:
· Blocking. The input is broken up into many contiguous blocks. With FLAC, the blocks may vary in size. The optimal size of the block is usually affected by many factors, including the sample rate, spectral characteristics over time, etc. Though FLAC allows the block size to vary within a stream, the reference encoder uses a fixed block size. 首先将输入的音频流划分成block,尽管FLAC允许变化的block size,但encoder目前还是使用固定的block size。
· Interchannel Decorrelation. In the case of stereo streams, the encoder will create mid and side signals based on the average and difference (respectively) of the left and right channels. The encoder will then pass the best form of the signal to the next stage.
· Prediction. The block is passed through a prediction stage where the encoder tries to find a mathematical description (usually an approximate one) of the signal. This description is typically much smaller than the raw signal itself. Since the methods of prediction are known to both the encoder and decoder, only the parameters of the predictor need be included in the compressed stream. FLAC currently uses four different classes of predictors (described in the prediction section), but the format has reserved space for additional methods. FLAC allows the class of predictor to change from block to block, or even within the channels of a block. 由于encoder与decoder都知道前向预测的方法,我们只需要保留参数即可,每个block也可以使用不同的预测方法,甚至每个block内部的每个声道也可以。
· Residual coding. If the predictor does not describe the signal exactly, the difference between the original signal and the predicted signal (called the error or residual signal) must be coded losslessy. If the predictor is effective, the residual signal will require fewer bits per sample than the original signal. FLAC currently uses only one method for encoding the residual (see the Residual coding section), but the format has reserved space for additional methods. FLAC allows the residual coding method to change from block to block, or even within the channels of a block.
In addition, FLAC specifies a metadata system, which allows arbitrary information about the stream to be included at the beginning of the stream.
Definitions
Many terms like "block" and "frame" are used to mean different things in differenct encoding schemes.
block和frame的概念,的确让人混淆,在不同的encoder里面表示的东西都不一样!
For example, a frame in MP3 corresponds to many samples across several channels, whereas an S/PDIF frame represents just one sample for each channel. The definitions we use for FLAC follow. Note that when we talk about blocks and subblocks we are referring to the raw unencoded audio data that is the input to the encoder,
block和subblock只用于输入到encoder的raw unencoded audio data,以samples为单位,一般为4096;
and when we talk about frames and subframes, we are referring to the FLAC-encoded data.
frame和subframes指已经编码过的data大小,以bytes为单位。
· Block: One or more audio samples that span several channels.
· Subblock: One or more audio samples within a channel. So a block contains one subblock for each channel, and all subblocks contain the same number of samples. 每个subblock只包含一个channel的sample值,一个block由多个subblock组成;
· Blocksize: The number of samples in any of a block's subblocks. For example, a one second block sampled at 44.1KHz has a blocksize of 44100, regardless of the number of channels.
· Frame: A frame header plus one or more subframes.
· Subframe: A subframe header plus one or more encoded samples from a given channel. All subframes within a frame will contain the same number of samples.
Blocking
The size used for blocking the audio data has a direct effect on the compression ratio. If the block size is too small, the resulting large number of frames mean that excess bits will be wasted on frame headers. If the block size is too large, the characteristics of the signal may vary so much that the encoder will be unable to find a good predictor. In order to simplify encoder/decoder design, FLAC imposes a minimum block size of 16 samples, and a maximum block size of 65535 samples. This range covers the optimal size for all of the audio data FLAC supports.
Currently the reference encoder uses a fixed block size, optimized on the sample rate of the input. Future versions may vary the block size depending on the characteristics of the signal.
Blocked data is passed to the predictor stage one subblock (channel) at a time. Each subblock is independently coded into a subframe, and the subframes are concatenated into a frame. Because each channel is coded separately, it means that one channel of a stereo frame may be encoded as a constant subframe, and the other an LPC subframe.
Interchannel Decorrelation
In stereo streams, many times there is an exploitable amount of correlation between the left and right channels. FLAC allows the frames of stereo streams to have different channel assignments, and an encoder may choose to use the best representation on a frame-by-frame basis.
· Independent. The left and right channels are coded independently.
· Mid-side. The left and right channels are transformed into mid and side channels. The mid channel is the midpoint (average) of the left and right signals, and the side is the difference signal (left minus right).
· Left-side. The left channel and side channel are coded.
· Right-side. The right channel and side channel are coded
Surprisingly, the left-side and right-side forms can be the most efficient in many frames, even though the raw number of bits per sample needed for the original signal is slightly more than that needed for independent or mid-side coding.
Prediction
FLAC uses four methods for modeling the input signal:
· Verbatim. This is essentially a zero-order predictor of the signal. The predicted signal is zero, meaning the residual is the signal itself, and the compression is zero. This is the baseline against which the other predictors are measured. If you feed random data to the encoder, the verbatim predictor will probably be used for every subblock. Since the raw signal is not actually passed through the residual coding stage (it is added to the stream 'verbatim'), the encoding results will not be the same as a zero-order linear predictor.
· Constant. This predictor is used whenever the subblock is pure DC ("digital silence"), i.e. a constant value throughout. The signal is run-length encoded and added to the stream.
· Fixed linear predictor. FLAC uses a class of computationally-efficient fixed linear predictors (for a good description, see audiopak and shorten). FLAC adds a fourth-order predictor to the zero-to-third-order predictors used by Shorten. Since the predictors are fixed, the predictor order is the only parameter that needs to be stored in the compressed stream. The error signal is then passed to the residual coder.
· FIR Linear prediction. For more accurate modeling (at a cost of slower encoding), FLAC supports up to 32nd order FIR linear prediction (again, for information on linear prediction, see audiopak and shorten). The reference encoder uses the Levinson-Durbin method for calculating the LPC coefficients from the autocorrelation coefficients, and the coefficients are quantized before computing the residual. Whereas encoders such as Shorten used a fixed quantization for the entire input, FLAC allows the quantized coefficient precision to vary from subframe to subframe. The FLAC reference encoder estimates the optimal precision to use based on the block size and dynamic range of the original signal.
Residual Coding
FLAC currently defines two similar methods for the coding of the error signal from the prediction stage. The error signal is coded using Rice codes in one of two ways: 1) the encoder estimates a single Rice parameter based on the variance of the residual and Rice codes the entire residual using this parameter; 2) the residual is partitioned into several equal-length regions of contiguous samples, and each region is coded with its own Rice parameter based on the region's mean. (Note that the first method is a special case of the second method with one partition, except the Rice parameter is based on the residual variance instead of the mean.)
The FLAC format has reserved space for other coding methods. Some possiblities for volunteers would be to explore better context-modeling of the Rice parameter, or Huffman coding. See LOCO-I and pucrunch for descriptions of several universal codes.
Format
This section specifies the FLAC bitstream format. FLAC has no format version information, but it does contain reserved space in several places. Future versions of the format may use this reserved space safely without breaking the format of older streams. Older decoders may choose to abort decoding or skip data encoded with newer methods. Apart from reserved patterns, in places the format specifies invalid patterns, meaning that the patterns may never appear in any valid bitstream, in any prior, present, or future versions of the format. These invalid patterns are usually used to make the synchronization mechanism more robust.
All numbers used in a FLAC bitstream are integers; there are no floating-point representations. All numbers are big-endian coded. All numbers are unsigned unless otherwise specified.所有的数值都是无符号、大端编码。
Before the formal description of the stream, an overview might be helpful.
· A FLAC bitstream consists of the "fLaC" marker at the beginning of the stream, followed by a mandatory metadata block (called the STREAMINFO block), any number of other metadata blocks, then the audio frames.
· FLAC supports up to 128 kinds of metadata blocks; currently the following are defined: 最多支持128个metadata block,block的类型如下:
o STREAMINFO: This block has information about the whole stream, like sample rate, number of channels, total number of samples, etc. It must be present as the first metadata block in the stream. Other metadata blocks may follow, and ones that the decoder doesn't understand, it will skip.Decoder不能解释的metadata block,将会被略过。
o APPLICATION: This block is for use by third-party applications. The only mandatory field is a 32-bit identifier. This ID is granted upon request to an application by the FLAC maintainers. The remainder is of the block is defined by the registered application. Visit the registration page if you would like to register an ID for your application with FLAC.
o PADDING: This block allows for an arbitrary amount of padding. The contents of a PADDING block have no meaning. This block is useful when it is known that metadata will be edited after encoding; the user can instruct the encoder to reserve a PADDING block of sufficient size so that when metadata is added, it will simply overwrite the padding (which is relatively quick) instead of having to insert it into the right place in the existing file (which would normally require rewriting the entire file).
o SEEKTABLE: This is an optional block for storing seek points. It is possible to seek to any given sample in a FLAC stream without a seek table, but the delay can be unpredictable since the bitrate may vary widely within a stream. By adding seek points to a stream, this delay can be significantly reduced. Each seek point takes 18 bytes, so 1% resolution within a stream adds less than 2k. There can be only one SEEKTABLE in a stream, but the table can have any number of seek points. There is also a special 'placeholder' seekpoint which will be ignored by decoders but which can be used to reserve space for future seek point insertion.
o VORBIS_COMMENT: This block is for storing a list of human-readable name/value pairs. Values are encoded using UTF-8. It is an implementation of the Vorbis comment specification (without the framing bit). This is the only officially supported tagging mechanism in FLAC. There may be only one VORBIS_COMMENT block in a stream. In some external documentation, Vorbis comments are called FLAC tags to lessen confusion.
o CUESHEET: This block is for storing various information that can be used in a cue sheet. It supports track and index points, compatible with Red Book CD digital audio discs, as well as other CD-DA metadata such as media catalog number and track ISRCs. The CUESHEET block is especially useful for backing up CD-DA discs, but it can be used as a general purpose cueing mechanism for playback.
o PICTURE: This block is for storing pictures associated with the file, most commonly cover art from CDs. There may be more than one PICTURE block in a file. The picture format is similar to the APIC frame in ID3v2. The PICTURE block has a type, MIME type, and UTF-8 description like ID3v2, and supports external linking via URL (though this is discouraged). The differences are that there is no uniqueness constraint on the description field, and the MIME type is mandatory. The FLAC PICTURE block also includes the resolution, color depth, and palette size so that the client can search for a suitable picture without having to scan them all.
· The audio data is composed of one or more audio frames. Each frame consists of a frame header, which contains a sync code, information about the frame like the block size, sample rate, number of channels, et cetera, and an 8-bit CRC. The frame header also contains either the sample number of the first sample in the frame (for variable-blocksize streams), or the frame number (for fixed-blocksize streams). This allows for fast, sample-accurate seeking to be performed. Following the frame header are encoded subframes, one for each channel, and finally, the frame is zero-padded to a byte boundary. Each subframe has its own header that specifies how the subframe is encoded. 每个frame都有一个frame header,frame header之后是subframes,每个subframe也有一个自己的header用来描述subframe是如何编码。
· Since a decoder may start decoding in the middle of a stream, there must be a method to determine the start of a frame. A 14-bit sync code begins each frame. The sync code will not appear anywhere else in the frame header. However, since it may appear in the subframes, the decoder has two other ways of ensuring a correct sync. The first is to check that the rest of the frame header contains no invalid data. Even this is not foolproof since valid header patterns can still occur within the subframes. The decoder's final check is to generate an 8-bit CRC of the frame header and compare this to the CRC stored at the end of the frame header.
· Again, since a decoder may start decoding at an arbitrary frame in the stream, each frame header must contain some basic information about the stream because the decoder may not have access to the STREAMINFO metadata block at the start of the stream. This information includes sample rate, bits per sample, number of channels, etc. Since the frame header is pure overhead, it has a direct effect on the compression ratio. To keep the frame header as small as possible, FLAC uses lookup tables for the most commonly used values for frame parameters. For instance, the sample rate part of the frame header is specified using 4 bits. Eight of the bit patterns correspond to the commonly used sample rates of 8/16/22.05/24/32/44.1/48/96 kHz. However, odd sample rates can be specified by using one of the 'hint' bit patterns, directing the decoder to find the exact sample rate at the end of the frame header. The same method is used for specifying the block size and bits per sample. In this way, the frame header size stays small for all of the most common forms of audio data.
· Individual subframes (one for each channel) are coded separately within a frame, and appear serially in the stream. In other words, the encoded audio data is NOT channel-interleaved. This reduces decoder complexity at the cost of requiring larger decode buffers. Each subframe has its own header specifying the attributes of the subframe, like prediction method and order, residual coding parameters, etc. The header is followed by the encoded audio data for that channel.
· FLAC specifies a subset of itself as the Subset format. The purpose of this is to ensure that any streams encoded according to the Subset are truly "streamable", meaning that a decoder that cannot seek within the stream can still pick up in the middle of the stream and start decoding. It also makes hardware decoder implementations more practical by limiting the encoding parameters such that decoder buffer sizes and other resource requirements can be easily determined. flac generates Subset streams by default unless the "--lax" command-line option is used. The Subset makes the following limitations on what may be used in the stream:
o The blocksize bits in the frame header must be 0001-1110. The blocksize must be <=16384; if the sample rate is <= 48000Hz, the blocksize must be <=4608.
o The sample rate bits in the frame header must be 0001-1110.
o The bits-per-sample bits in the frame header must be 001-111.
o If the sample rate is <= 48000Hz, the filter order in LPC subframes must be less than or equal to 12, i.e. the subframe type bits in the subframe header may not be 101100-111111.
o The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
The following tables constitute a formal description of the FLAC format. Numbers in angle brackets indicate how many bits are used for a given field.
1 FLAC STREAM 基本结构
|
2 METADATA_BLOCK
METADATA BLOCK由四字节的头以及数据组成。
|
|
|
2.1 METADATA_BLOCK_STREAMINFO
|
2.1 METADATA_BLOCK_PADDING
padding block的作用?
|
|
|
|
|
|
|
|
|
3 AUDIO FRAME
frame由frame header+subframess+frame footer组成。
frame header中参数的描述与STREAMINFO Block中有何区别?frame header中自己也记录了一些sample rate等参数,用来保证当FLAC流被从中间切割时,即使没有STREAMINFO Block中的信息,frame还是能够单独解码。
|
|
|
3.1 subframe
Subframe也有自己的header,主要描述一些编码参数。
|
|
|
RESIDUAL | |
<2> | Residual coding method:
|
RESIDUAL_CODING_METHOD_PARTITIONED_RICE || |
|
|
|
|
|
|
|
|
|
4 解码步骤:
解码部分其实比较简单,使用开源的libflacdec.o,只要调用如下几个接口就可以了。对于API的介绍,参考http://flac.sourceforge.net/api/index.html
1 FLAC__stream_decoder_new()
创建一个decoder
2 FLAC__stream_decoder_set_*();
设置decoder的一些属性。
3 FLAC__stream_decoder_init_xx();
如果是从文件读,就调用FLAC__stream_decoder_init_file(),如果是从其它地方接收数据,则调用FLAC__stream_decoder_init_stream(), 另外需要注意的是,FLAC__stream_decoder_init_stream(),必须要注册的是read_callback/write_callback/error_callback.该三个callback的使用在4中将介绍。
4 FLAC__stream_decoder_process_*();
解码函数接口,由于我们OMX/FFMPEG每次推送一个frame,所以调用FLAC__stream_decoder_process_singal()函数,这个函数解码完一个metadata block或者audio frame时都会返回。
前面提到了注册三个callback,现在这里就能用到了。调用FLAC__stream_decoder_process_singal()时,该函数会先调用read_callback:
read_callback用来读取数据;decoder会向read_callback提供一个buffer,bytes,read_callback往这个buffer中填充数据并返回。
decoder拿到read_callback中的数据后,会进行解码。解码完成后调用write_callback,用来输出数据。
如果解码过程中出错了,则会调用error_callback.
5 FLAC__stream_decoder_finish();
播放结束时调用。
6 FLAC__stream_decoder_delete();
销毁decoder。
最后需要注意在write_call中输出数据时,decoder提供了int32 *buffer[x]来存储各个channel的数据,每个sample值为32bits。