Soundtouch audio processing database source code analysis and algorithm extraction (2)

Source: Internet
Author: User

Soundtouch audio processing database Initialization Process Analysis

Define a variable soundtouch m_soundtouch;

 

Derivation of soundtouch

Export osamplepipe-> export oprocessor-> soundtouch (process [1])

Therefore, first construct the base class kerberosamplepipe, then derive the kerberoprocessor, and then derive the soundtouch from kerberoprocessor. I have to mention that the level of C ++ for foreigners is really high. Here, class inheritance is basically brought to the extreme. The ability to analyze such code is simply a pleasure. First, let's take a look at the basic class kerberosamplepipe, which is defined as follows:

Class program osamplepipe

{

Public:

// Virtual default destructor

Virtual ~ Export osamplepipe (){}

 

/// Returns a pointer to the beginning of the output samples.

/// This function is provided for accessing the output samples directly.

/// Please be careful for not to upload upt the book-keeping!

///

/// When using this function to output samples, also remember to 'delete'

/// Output samples from the buffer by calling

/// 'Your esamples (numsamples) 'function

Virtual sampletype * ptrbegin () = 0;

 

/// Adds 'numsamples' pcs of samples from the 'samples' memory position

/// The sample buffer.

Virtual void putsamples (const sampletype * samples, // <pointer to samples.

Uint numsamples // <number of samples to insert.

) = 0;

 

 

// Moves samples from the 'other' pipe instance to this instance.

Void movesamples (export osamplepipe & Other // <other pipe instance where from the receive the data.

)

{

Int onumsamples = Other. numsamples ();

 

Putsamples (other. ptrbegin (), onumsamples );

Other. receivesamples (onumsamples );

};

 

/// Output samples from beginning of the sample buffer. copies requested samples

/// Output buffer and removes them from the sample buffer. If there are less

/// 'Numsample' samples in the buffer, returns all that available.

///

/// Return number of samples returned.

Virtual uint into esamples (sampletype * output, // <buffer where to copy output samples.

Uint maxsamples // <How many samples to receive at max.

) = 0;

 

/// Adjusts book-keeping so that given number of samples are removed from beginning of

/// Sample buffer without copying them anywhere.

///

/// Used to reduce the number of samples in the buffer when accessing the sample buffer directly

/// With 'ptrbegin' function.

Virtual uint parallel esamples (uint maxsamples // <remove this parameter samples from the beginning

 

Pipe.

) = 0;

 

/// Returns number of samples currently available.

Virtual uint numsamples () const = 0;

 

// Returns Nonzero if There Aren't any samples available for outputting.

Virtual int isempty () const = 0;

 

/// Clears all the samples.

Virtual void clear () = 0;

}

 

The constructor of the fifosamplepipe class is not implemented here, so the system implicitly calls the default automatically generated fifosamplepipe (). Of course, he should not perform any initialization, and he does not need to perform any initialization. By defining virtual ~ Fifosamplepipe () {} virtual destructor to create a new subclass, for example, export osamplepipe * A = new export oprocessor. When a destroys, it executes the destructor of the subclass export oprocessor, ensure that all layers of inheritance are destroyed once, which is a feature of a base class. Class inheritance and polymorphism are indeed the most powerful part of C ++, which helps to write highly repetitive classes. By looking at the declaration of this base class, we can note that apart from defining most virtual functions, he only implements the movesamples function, that is, if the subclass does not have override movesamples, will call this method. The processing is also relatively simple. According to the annotations, it is not difficult to understand that this function implements the data sharing transfer interface between the derived classes.

// Moves samples from the 'other' pipe instance to this instance.

Movesamples (export osamplepipe & Other // <other pipe instance where from the receive the data.

)

{

Int onumsamples = Other. numsamples ();

 

Putsamples (other. ptrbegin (), onumsamples );

Other. receivesamples (onumsamples );

};

Before creating the soundtouch class, after the first two steps (process [1]), they all implicitly called the default destructor. Because the base class kerberosamplepipe does not implement the constructor, by default, we can choose not to perform any initialization. Then, mongooprocessor simply puts the member variable into osamplepipe * output. a pointer to the base class is initialized to point to null.

Fifoprocessor ()

{

Output = NULL;

}

Now return to the soundtouch constructor. After constructing the first two classes, he can finally call his own default constructor.

Soundtouch: soundtouch ()

{

// Initialize rate transposer and tempo changer instances

Pratetransposer = ratetransposer: newinstance ();

Ptdstretch = tdstretch: newinstance ();

Setoutpipe (ptdstretch );

Rate = tempo = 0;

Virtualpitch =

Virtualrate =

Virtualtempo = 1.0;

Calceffectiverateandtempo ();

Channels = 0;

Bsrateset = false;

}

Let's take a look at the member variables of the soundtouch class.

Class soundtouch: Public writable oprocessor

{

PRIVATE:

/// Rate transposer class instance

Class ratetransposer * pratetransposer;

 

/// Time-stretch class instance

Class tdstretch * ptdstretch;

 

/// Virtual pitch parameter. Valid tive rate & tempo are calculated from these parameters.

Float virtualrate;

 

/// Virtual pitch parameter. Valid tive rate & tempo are calculated from these parameters.

Float virtualtempo;

 

/// Virtual pitch parameter. Valid tive rate & tempo are calculated from these parameters.

Float virtualpitch;

 

/// Flag: Has sample rate been set?

Bool bsrateset;

 

/// Calculates valid tive rate & tempo valuescfrom 'virtualrate', 'virtualtempo' and

/// 'Virtualproject' parameters.

Void calceffectiverateandtempo ();

 

Protected:

/// Number of channels

Uint channels;

 

/// Valid tive 'rate' value calculated from 'virtualrate', 'virtualtempo' and 'virtualedit'

Float rate;

 

/// Valid tive 'tempo' value calculated from 'virtualrate', 'virtualtempo' and 'virtualedit'

Float tempo;

...

Based on the constructor, The pratetransposer and ptdstretch classes are instantiated.

First, let's take a look at the member function newinstance of the ratetransposer class and use a macro to define integer_samples to create a class with fixed points or floating points. Now we can determine whether ratetransposerinteger or ratetransposerfloat should be directly derived from. (Assuming integer_samples is defined) It constructs a ratetransposerinteger.

Ratetransposer * ratetransposer: newinstance ()

{

# Ifdef integer_samples

Return: New ratetransposerinteger;

# Else

Return: New ratetransposerfloat;

# Endif

}

Let's take a look at the definition of the ratetransposerinteger class. As expected, it is derived from ratetransposer.

Class ratetransposer: Public writable oprocessor

{

Protected:

...

Restore osamplebuffer storebuffer;

 

/// Buffer for keeping samples between transposing & anti-Alias Filter

Using osamplebuffer tempbuffer;

 

/// Output sample buffer

Extends osamplebuffer outputbuffer;

...

Appeal the relationship between the two classes and the base class:

Export osamplepipe-> export oprocessor-> ratetransposer-> ratetransposerinteger

The construction process here is different: ratetransposer (): kerberoprocessor (& outputbuffer)

The ratetransposer constructor specifies the constructor of the parent class kerberoprocessor (& outputbuffer)

Export oprocessor (export osamplepipe * poutput // <output pipe.

)

{

Output = poutput;

}

Ratetransposer uses the class member variable outputbuffer as the parameter for passing functions. It may be strange to everyone here that the ratetransposer class has not been instantiated in the Code. How can he possibly have an external osamplebuffer outputbuffer; in fact, it reflects the C ++ polymorphism. The input here is actually a _ vfptr array, which is a pointer array pointing to the variable of each derived class. Now I understand. _ Vfptr [0] is not necessarily a value, but _ vfptr is definitely an existing value. After constructing the external oprocessor, You need to construct the ratetransposer. It has three definitions of the external osamplebuffer class.

...

Class implements osamplebuffer: Public implements osamplepipe

...

Inheritance relationship with the base class

Export osamplepipe-> export osamplebuffer

/// Constructor

Export osamplebuffer (INT numchannels = 2 // <number of channels, 1 = mono, 2 = stereo.

/// <Default is stereo.

);

The constructor does not define a constructor without parameters. Therefore, the constructor with parameters is called by default.

Using osamplebuffer: Using osamplebuffer (INT numchannels)

{

Assert (numchannels> 0 );

Sizeinbytes = 0; // reasonable Initial Value

Buffer = NULL;

Bufferunaligned = NULL;

Samplesinbuffer = 0;

Bufferpos = 0;

Channels = (uint) numchannels;

Ensurecapacity (32); // allocate initial capacity

}

The constructor of writable osamplebuffer is called three times.

Now we can finally execute the ratetransposer constructor.

// Constructor

Ratetransposer: ratetransposer (): kerberoprocessor (& outputbuffer)

{

Numchannels = 2;

Buseaafilter = true;

Frate = 0;

 

// Instantiates the anti-alias filter with default tap Length

// Of 32

Paafilter = new aafilter (32 );

}

First, let's take a look at the definition of aafilter.

Class aafilter

{

Protected:

Class firfilter * pfir;

/// Low-pass filter cut-off frequency, negative = invalid

Double cutofffreq;

/// Num of filter taps

Uint length;

/// Calculate the FIR coefficients realizing the given cutoff-Frequency

Void calculatecoeffs ();

Public:

Aafilter (uint length );

~ Aafilter ();

/// Sets new anti-alias filter cut-off edge frequency, scaled to sampling

/// Frequency (nyquest frequency = 0.5). The filter will cut off

/// Frequencies than that.

Void setcutofffreq (double newcutofffreq );

/// Sets number of FIR Filter taps, I. e .~ Filter complexity

Void setlength (uint newlength );

Uint getlength () const;

/// Applies the filter to the given sequence of samples.

// Note: The amount of outputted samples is by value of 'filter length'

/// Smaller than the amount of input samples.

Uint evaluate (sampletype * DEST,

Const sampletype * SRC,

Uint numsamples,

Uint numchannels) const;

};

The constructor initializes a pointer to class firfilter.

Aafilter: aafilter (uint Len)

{

Pfir = firfilter: newinstance ();

Cutofffreq = 0.5;

Setlength (LEN );

}

First, let's look at the firfilter class member function newinstance (). Hey hey, here we found a very useful function detectcpuextensions (); through this function, we can determine the type of multimedia instruction sets supported by the CPU. According to the annotations, we can quickly understand. Detectcpuextensions is added to the Favorites list. Its implementation is in the implementation of cpu_detect_x86_win.cpp. In the US, he can only detect the cpu Of The X86 architecture. Maybe I think more. Only MMX commands are supported based on the configurations of your computer (using the sayang CPU.

Firfilter * firfilter: newinstance ()

{

Uint uextensions;

Uextensions = detectcpuextensions ();

// Check if MMX/SSE/3 dnow! Instruction Set extensions supported by CPU

# Ifdef allow_mmx

// MMX routines available only with integer sample types

If (uextensions & support_mmx)

{

Return: New firfiltermmx;

}

Else

# Endif // allow_mmx

# Ifdef allow_sse

If (uextensions & support_sse)

{

// SSE support

Return: New firfiltersse;

}

Else

# Endif // allow_sse

# Ifdef allow_3dnow

If (uextensions & support_3dnow)

{

// 3 dnow! Support

Return: New firfilter3dnow;

}

Else

# Endif // allow_3dnow

{

// ISA optimizations not supported, use plain C version

Return: New firfilter;

}

}

Therefore, he will return a firfiltermmx class through this judgment structure.

If (uextensions & support_mmx)

{

Return: New firfiltermmx;

}

View the firfiltermmx class definition class firfiltermmx: Public firfilter, which is derived from firfilter. The member function uint firfiltermmx: evaluatefilterstereo has attracted my attention. The main algorithm uses the MMX instruction set to complete some sound computing. This is the core rate algorithm we need. For implementation of different instruction sets, see firfilter3dnow and firfiltersse. The default is the implementation of the evaluatefilterstereo function of firfilter.

// MMX-optimized version of the filter routine for stereo sound

Uint firfiltermmx: evaluatefilterstereo (short * DEST, const short * SRC, uint numsamples) const

{

// Create stack copies of the needed member variables for ASM routines:

Uint I, J;

_ M64 * pvdest = (_ M64 *) DEST;

 

If (length <2) return 0;

 

For (I = 0; I <(numsamples-length)/2; I ++)

{

_ M64 accu1;

_ M64 accu2;

Const _ M64 * pvsrc = (const _ M64 *) SRC;

Const _ M64 * pvfilter = (const _ M64 *) filtercoeffsalign;

 

Accu1 = accu2 = _ mm_setzero_si64 ();

For (j = 0; j <lengthdiv8 * 2; j ++)

{

_ M64 temp1, temp2;

 

Temp1 = _ mm_unpacklo_pi16 (pvsrc [0], pvsrc [1]); // = L2 l0 R2 R0

Temp2 = _ mm_unpackhi_pi16 (pvsrc [0], pvsrc [1]); // = L3 L1 R3 r1

 

Accu1 = _ mm_add_pi32 (accu1, _ mm_madd_pi16 (temp1, pvfilter [0]); // + = L2 * F2 + l0 * f0

 

R2 * F2 + R0 * f0

Accu1 = _ mm_add_pi32 (accu1, _ mm_madd_pi16 (temp2, pvfilter [1]); // + = L3 * F3 + L1 * F1

 

R3 * F3 + R1 * F1

 

Temp1 = _ mm_unpacklo_pi16 (pvsrc [1], pvsrc [2]); // = L4 L2 R4 r2

 

Accu2 = _ mm_add_pi32 (accu2, _ mm_madd_pi16 (temp2, pvfilter [0]); // + = L3 * F2 + L1 * f0

 

R3 * F2 + R1 * f0

Accu2 = _ mm_add_pi32 (accu2, _ mm_madd_pi16 (temp1, pvfilter [1]); // + = L4 * F3 + l2 * F1

 

R4 * F3 + R2 * F1

 

// Accu1 + = L2 * F2 + l0 * f0 R2 * F2 + R0 * f0

// + = L3 * F3 + L1 * F1 R3 * F3 + R1 * F1

 

// Accu2 + = L3 * F2 + L1 * f0 R3 * F2 + R1 * f0

// L4 * F3 + l2 * F1 R4 * F3 + R2 * F1

 

Pvfilter + = 2;

Pvsrc + = 2;

}

// ACCU >>= resultdivfactor

Accu1 = _ mm_srai_pi32 (accu1, resultdivfactor );

Accu2 = _ mm_srai_pi32 (accu2, resultdivfactor );

 

// Pack 2*2*32 bits => 4*16 bits

Pvdest [0] = _ mm_packs_pi32 (accu1, accu2 );

SRC + = 4;

Pvdest ++;

}

 

_ M_empty (); // clear Emms state

 

Return (numsamples & 0 xfffffffe)-length;

}

Therefore, if you port soundtouch to a CPU without multimedia instruction sets, you should use the evaluatefilterstere function of firfilter. After the execution, we can finally construct our ratetransposerinteger (). In the constructor:

Ratetransposerinteger: ratetransposerinteger (): ratetransposer ()

{

// Notice: use local function calling syntax for sake of clarity,

// To indicate the fact that C ++ constructor can't call virtual functions.

Ratetransposerinteger: resetregisters ();

Ratetransposerinteger: setrate (1.0f );

. So far, pratetransposer = ratetransposer: newinstance (); instantiation is complete. For ptdstretch = tdstretch: newinstance (); the next release is Xiao.

 

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/suhetao/archive/2010/08/28/5845667.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.