加入PortAudio与FFmpeg

This commit is contained in:
Sch 2023-07-15 03:07:19 +08:00
parent d6317fd7e2
commit 59e248fe01
1025 changed files with 190550 additions and 19 deletions

Binary file not shown.

View File

@ -7,7 +7,7 @@
{
"Name": "Cut5",
"Type": "Runtime",
"LoadingPhase": "Default",
"LoadingPhase": "PreDefault",
"AdditionalDependencies": [
"Engine"
]

10
Plugins/FFMPEGMedia-master/.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
##########################
# Unreal Generated Files #
##########################
Build
Binaries
DerivedDataCache
Intermediate/**
*.VC.db
*.VC.opendb
*.pdb

Binary file not shown.

View File

@ -0,0 +1,20 @@
FFMPEG Media Plugin for unreal engine
===================================
A plugin that let's you use the FFMPEG library as media player
## Features:
- Works on Windows and Mac
- Support for hardware accelerated codecs
- Support for videos with alpha
## How to use
1. The plugin works with Unreal 4.26
2. You can clone the repository to `<Game>/Plugins/` or if you want you can use git submodules to your own git repository. Alternatively, you can copy to the `Engine/Plugins/` if you wish to make the plugin available to all of your projects.
> Do not forget to run UE4's `Generate Project Files` to account for these changes!
3. Follow the steps to [play a video tutorial](https://docs.unrealengine.com/en-us/Engine/MediaFramework/HowTo/FileMediaSource) but insead of using the automatic player, choose the FFMPEGPlayer inside the players overrides for the step 5.
![Player Overrrides](https://github.com/bakjos/FFMPEGMedia/raw/master/docs/mediatype.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,171 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.IO;
public class FFMPEGMedia : ModuleRules
{
private string ModulePath
{
get { return ModuleDirectory; }
}
private string ThirdPartyPath
{
get { return Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/")); }
}
private string UProjectPath
{
get { return Directory.GetParent(ModulePath).Parent.FullName; }
}
private void CopyToBinaries(string Filepath, ReadOnlyTargetRules Target)
{
string binariesDir = Path.Combine(UProjectPath, "Binaries", Target.Platform.ToString());
string filename = Path.GetFileName(Filepath);
System.Console.WriteLine("Writing file " + Filepath + " to " + binariesDir);
if (!Directory.Exists(binariesDir))
Directory.CreateDirectory(binariesDir);
if (!File.Exists(Path.Combine(binariesDir, filename)))
File.Copy(Filepath, Path.Combine(binariesDir, filename), true);
}
public bool LoadFFmpeg(ReadOnlyTargetRules Target)
{
bool isLibrarySupported = false;
if ((Target.Platform == UnrealTargetPlatform.Win64))
{
isLibrarySupported = true;
string PlatformString = (Target.Platform == UnrealTargetPlatform.Win64) ? "x64" : "Win32";
string LibrariesPath = Path.Combine(Path.Combine(Path.Combine(ThirdPartyPath, "ffmpeg", "lib"), "vs"), PlatformString);
System.Console.WriteLine("... LibrariesPath -> " + LibrariesPath);
PublicAdditionalLibraries.Add(Path.Combine(LibrariesPath, "avcodec.lib"));
PublicAdditionalLibraries.Add(Path.Combine(LibrariesPath, "avdevice.lib"));
PublicAdditionalLibraries.Add(Path.Combine(LibrariesPath, "avfilter.lib"));
PublicAdditionalLibraries.Add(Path.Combine(LibrariesPath, "avformat.lib"));
PublicAdditionalLibraries.Add(Path.Combine(LibrariesPath, "avutil.lib"));
PublicAdditionalLibraries.Add(Path.Combine(LibrariesPath, "swresample.lib"));
PublicAdditionalLibraries.Add(Path.Combine(LibrariesPath, "swscale.lib"));
string[] dlls = {"avcodec-58.dll","avdevice-58.dll", "avfilter-7.dll", "avformat-58.dll", "avutil-56.dll", "swresample-3.dll", "swscale-5.dll", "postproc-55.dll"};
string BinariesPath = Path.Combine(Path.Combine(Path.Combine(ThirdPartyPath, "ffmpeg", "bin"), "vs"), PlatformString);
foreach (string dll in dlls)
{
PublicDelayLoadDLLs.Add(dll);
//CopyToBinaries(Path.Combine(BinariesPath, dll), Target);
RuntimeDependencies.Add(Path.Combine(BinariesPath, dll), StagedFileType.NonUFS);
}
}
else if (Target.Platform == UnrealTargetPlatform.Mac)
{
isLibrarySupported = true;
//string LibrariesPath = Path.Combine(Path.Combine(ThirdPartyPath, "ffmpeg", "lib"), "osx");
string LibrariesPath = "/usr/local/lib";
System.Console.WriteLine("... LibrariesPath -> " + LibrariesPath);
string[] libs = {"libavcodec.58.dylib","libavdevice.58.dylib", "libavfilter.7.dylib", "libavformat.58.dylib", "libavutil.56.dylib", "libswresample.3.dylib", "libswscale.5.dylib", "libpostproc.55.dylib"};
foreach (string lib in libs)
{
PublicAdditionalLibraries.Add(Path.Combine(LibrariesPath, lib));
//PublicDelayLoadDLLs.Add(Path.Combine(LibrariesPath, lib));
//CopyToBinaries(Path.Combine(LibrariesPath, lib), Target);
//RuntimeDependencies.Add(Path.Combine(LibrariesPath, lib), StagedFileType.NonUFS);
}
} else if (Target.Platform == UnrealTargetPlatform.Android) {
isLibrarySupported = true;
string LibrariesPath =Path.Combine(Path.Combine(ThirdPartyPath, "ffmpeg", "lib"), "android");
string[] Platforms = { "armeabi-v7a", "arm64-v8a", "x86", "x86_64" };
string[] libs = {"libavcodec.so","libavdevice.so", "libavfilter.so", "libavformat.so", "libavutil.so", "libswresample.so", "libswscale.so"};
System.Console.WriteLine("Architecture: " + Target);
foreach (string platform in Platforms)
{
foreach (string lib in libs)
{
PublicAdditionalLibraries.Add(Path.Combine(Path.Combine(LibrariesPath, platform), lib ));
}
}
string finalPath = Path.Combine(ModulePath, "FFMPEGMedia_APL.xml");
System.Console.WriteLine("... APL Path -> " + finalPath);
AdditionalPropertiesForReceipt.Add("AndroidPlugin", finalPath);
}
if (isLibrarySupported)
{
// Include path
PublicIncludePaths.Add(Path.Combine(ThirdPartyPath, "ffmpeg", "include"));
}
return isLibrarySupported;
}
public FFMPEGMedia(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
bEnableExceptions = true;
//OptimizeCode = CodeOptimization.Never;
DynamicallyLoadedModuleNames.AddRange(
new string[] {
"Media",
});
PrivateDependencyModuleNames.AddRange(
new string[] {
"Core",
"CoreUObject",
"Engine",
"MediaUtils",
"RenderCore",
"FFMPEGMediaFactory",
"Projects",
});
if (Target.Platform == UnrealTargetPlatform.Android)
{
PrivateDependencyModuleNames.AddRange(
new string[]
{
"ApplicationCore",
"Launch"
}
);
}
PrivateIncludePathModuleNames.AddRange(
new string[] {
"Media",
});
PrivateIncludePaths.AddRange(
new string[] {
"FFMPEGMedia/Private",
"FFMPEGMedia/Private/Player",
"FFMPEGMedia/Private/FFMPEG",
});
LoadFFmpeg(Target);
}
}

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<!--Android Camera plugin additions-->
<root xmlns:android="http://schemas.android.com/apk/res/android">
<!-- init section is always evaluated once per architecture -->
<init>
<log text="FFMPEG Media init"/>
<isArch arch="armeabi-v7a">
<setBool result="bSupported" value="true"/>
</isArch>
<isArch arch="arm64-v8a">
<setBool result="bSupported" value="true"/>
</isArch>
<isArch arch="x86_64">
<setBool result="bSupported" value="true"/>
</isArch>
</init>
<!-- optional files or directories to copy to Intermediate/Android/APK -->
<resourceCopies>
<log text="Copying GoogleVR runtime files to staging" />
<isArch arch="armeabi-v7a">
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/armeabi-v7a/libavcodec.so"
dst="$S(BuildDir)/libs/armeabi-v7a/libavcodec.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/armeabi-v7a/libavdevice.so"
dst="$S(BuildDir)/libs/armeabi-v7a/libavdevice.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/armeabi-v7a/libavfilter.so"
dst="$S(BuildDir)/libs/armeabi-v7a/libavfilter.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/armeabi-v7a/libavformat.so"
dst="$S(BuildDir)/libs/armeabi-v7a/libavformat.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/armeabi-v7a/libavutil.so"
dst="$S(BuildDir)/libs/armeabi-v7a/libavutil.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/armeabi-v7a/libswresample.so"
dst="$S(BuildDir)/libs/armeabi-v7a/libswresample.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/armeabi-v7a/libswscale.so"
dst="$S(BuildDir)/libs/armeabi-v7a/libswscale.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/armeabi-v7a/libcpufeatures.so"
dst="$S(BuildDir)/libs/armeabi-v7a/libcpufeatures.so" />
</isArch>
<isArch arch="arm64-v8a">
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/arm64-v8a/libavcodec.so"
dst="$S(BuildDir)/libs/arm64-v8a/libavcodec.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/arm64-v8a/libavdevice.so"
dst="$S(BuildDir)/libs/arm64-v8a/libavdevice.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/arm64-v8a/libavfilter.so"
dst="$S(BuildDir)/libs/arm64-v8a/libavfilter.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/arm64-v8a/libavformat.so"
dst="$S(BuildDir)/libs/arm64-v8a/libavformat.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/arm64-v8a/libavutil.so"
dst="$S(BuildDir)/libs/arm64-v8a/libavutil.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/arm64-v8a/libswresample.so"
dst="$S(BuildDir)/libs/arm64-v8a/libswresample.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/arm64-v8a/libswscale.so"
dst="$S(BuildDir)/libs/arm64-v8a/libswscale.so" />
</isArch>
<isArch arch="x86">
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86/libavcodec.so"
dst="$S(BuildDir)/libs/x86/libavcodec.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86/libavdevice.so"
dst="$S(BuildDir)/libs/x86/libavdevice.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86/libavfilter.so"
dst="$S(BuildDir)/libs/x86/libavfilter.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86/libavformat.so"
dst="$S(BuildDir)/libs/x86/libavformat.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86/libavutil.so"
dst="$S(BuildDir)/libs/x86/libavutil.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86/libswresample.so"
dst="$S(BuildDir)/libs/x86/libswresample.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86/libswscale.so"
dst="$S(BuildDir)/libs/x86/libswscale.so" />
</isArch>
<isArch arch="x86_64">
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86_64/libavcodec.so"
dst="$S(BuildDir)/libs/x86_64/libavcodec.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86_64/libavdevice.so"
dst="$S(BuildDir)/libs/x86_64/libavdevice.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86_64/libavfilter.so"
dst="$S(BuildDir)/libs/x86_64/libavfilter.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86_64/libavformat.so"
dst="$S(BuildDir)/libs/x86_64/libavformat.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86_64/libavutil.so"
dst="$S(BuildDir)/libs/x86_64/libavutil.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86_64/libswresample.so"
dst="$S(BuildDir)/libs/x86_64/libswresample.so" />
<copyFile src="$S(PluginDir)/../../ThirdParty/ffmpeg/lib/android/x86_64/libswscale.so"
dst="$S(BuildDir)/libs/x86_64/libswscale.so" />
</isArch>
</resourceCopies>
</root>

View File

@ -0,0 +1,40 @@
#include "CondWait.h"
#include "GenericPlatform/GenericPlatformProcess.h"
CondWait::CondWait() {
event = FGenericPlatformProcess::GetSynchEventFromPool();
}
CondWait::~CondWait() {
if ( event ) {
FGenericPlatformProcess::ReturnSynchEventToPool(event);
}
}
void CondWait::signal() {
if ( event) {
event->Trigger();
}
}
int CondWait::wait(FCriticalSection& mutex) {
return waitTimeout(mutex, 0);
}
int CondWait::waitTimeout(FCriticalSection& mutex , unsigned int ms) {
mutex.Unlock();
if ( ms == 0) {
event->Wait();
mutex.Lock();
return 0;
} else {
bool wait_result = event->Wait(FTimespan::FromMicroseconds(ms));
mutex.Lock();
if ( !wait_result) {
return 1;
}
return 0;
}
}

View File

@ -0,0 +1,20 @@
#pragma once
#include "HAL/Event.h"
#include "Misc/ScopeLock.h"
#include <chrono>
class CondWait {
public:
CondWait();
~CondWait();
void signal();
int wait(FCriticalSection& mutex);
int waitTimeout(FCriticalSection& mutex, unsigned int ms);
private:
FEvent* event;
};

View File

@ -0,0 +1,96 @@
#include "FFMPEGClock.h"
#include "FFMPEGPacketQueue.h"
extern "C" {
#include "libavutil/time.h"
}
/* no AV correction is done if too big error */
#define AV_NOSYNC_THRESHOLD 10.0
FFMPEGClock::FFMPEGClock()
{
pts = 0.0;
pts_drift = 0.0;
last_updated = 0.0;
speed = 0.0;
serial = 0;
paused = false;
queue_serial = NULL;
}
FFMPEGClock::~FFMPEGClock()
{
}
void FFMPEGClock::Init(FFMPEGPacketQueue* queue) {
speed = 1.0;
paused = false;
this->queue_serial = &queue->serial;
Set(NAN, -1);
}
void FFMPEGClock::Init(FFMPEGClock* clock) {
speed = 1.0;
paused = 0;
this->queue_serial = &clock->serial;
Set(NAN, -1);
}
double FFMPEGClock::Get() {
if ( queue_serial == NULL || *queue_serial != serial)
return NAN;
if (paused) {
return pts;
}
else {
double time = av_gettime_relative() / 1000000.0;
return pts_drift + time - (time - last_updated) * (1.0 - speed);
}
}
void FFMPEGClock::Set(double _pts, int _serial) {
double time = av_gettime_relative() / 1000000.0;
SetAt(_pts, _serial, time);
}
void FFMPEGClock::SetAt( double _pts, int _serial, double _time) {
this->pts = _pts;
this->last_updated = _time;
this->pts_drift = this->pts - _time;
this->serial = _serial;
}
void FFMPEGClock::SetPaused(bool p) {
paused = p;
}
void FFMPEGClock::SetSpeed(double s) {
Set(Get(), serial);
this->speed = s;
}
int FFMPEGClock::GetSerial() {
return serial;
}
double FFMPEGClock::GetSpeed() {
return speed;
}
double FFMPEGClock::GetPts() {
return pts;
}
double FFMPEGClock::GetLastUpdated() {
return last_updated;
}
void FFMPEGClock::SyncToSlave(FFMPEGClock *slave) {
double clock = Get();
double slave_clock = slave->Get();
if (!isnan(slave_clock) && (isnan(clock) || fabs(clock - slave_clock) > AV_NOSYNC_THRESHOLD))
Set(slave_clock, slave->GetSerial());
}

View File

@ -0,0 +1,37 @@
#pragma once
class FFMPEGPacketQueue;
class FFMPEGClock
{
public:
FFMPEGClock();
~FFMPEGClock();
void Init(FFMPEGPacketQueue* queue);
void Init(FFMPEGClock* clock);
double Get();
void Set (double pts, int serial);
void SetAt( double pts, int serial, double time);
void SetSpeed(double speed);
void SetPaused(bool paused);
double GetPts();
int GetSerial();
double GetSpeed();
double GetLastUpdated();
void SyncToSlave(FFMPEGClock *slave);
private:
double pts; /* clock base */
double pts_drift; /* clock base minus time at which we updated the clock */
double last_updated;
double speed;
int serial; /* clock is based on a packet with this serial */
bool paused;
int* queue_serial;
//int *queue_serial; /* pointer to the current packet queue serial, used for obsolete clock detection */
};

View File

@ -0,0 +1,197 @@
#include "FFMPEGDecoder.h"
FFMPEGDecoder::FFMPEGDecoder() {
decoder_reorder_pts = -1;
queue = NULL;
avctx = NULL;
pkt_serial = -1;
finished = 0;
packet_pending = false;
empty_queue_cond = NULL;
start_pts = 0;
start_pts_tb = {0,0};
next_pts = 0;
next_pts_tb = {0, 0};
decoder_tid = NULL;
}
FFMPEGDecoder::~FFMPEGDecoder()
{
}
void FFMPEGDecoder::Init(AVCodecContext *_avctx, FFMPEGPacketQueue *_queue, CondWait *_empty_queue_cond) {
this->avctx = _avctx;
this->queue = _queue;
this->empty_queue_cond = _empty_queue_cond;
this->start_pts = AV_NOPTS_VALUE;
this->pkt_serial = -1;
}
int FFMPEGDecoder::DecodeFrame( AVFrame *frame, AVSubtitle *sub) {
int ret = AVERROR(EAGAIN);
for (;;) {
AVPacket pkt;
if (queue->GetSerial() == pkt_serial) {
do {
if (queue->IsAbortRequest())
return -1;
switch (avctx->codec_type) {
case AVMEDIA_TYPE_VIDEO:
ret = avcodec_receive_frame(avctx, frame);
if (ret >= 0) {
if (decoder_reorder_pts == -1) {
frame->pts = frame->best_effort_timestamp;
}
else if (!decoder_reorder_pts) {
frame->pts = frame->pkt_dts;
}
}
break;
case AVMEDIA_TYPE_AUDIO:
ret = avcodec_receive_frame(avctx, frame);
if (ret >= 0) {
AVRational tb = { 1, frame->sample_rate };
if (frame->pts != AV_NOPTS_VALUE)
frame->pts = av_rescale_q(frame->pts, avctx->pkt_timebase, tb);
else if (next_pts != AV_NOPTS_VALUE)
frame->pts = av_rescale_q(next_pts, next_pts_tb, tb);
if (frame->pts != AV_NOPTS_VALUE) {
next_pts = frame->pts + frame->nb_samples;
next_pts_tb = tb;
}
}
break;
}
if (ret == AVERROR_EOF) {
finished = pkt_serial;
avcodec_flush_buffers(avctx);
return 0;
}
if (ret >= 0)
return 1;
} while (ret != AVERROR(EAGAIN));
}
do {
if (queue->GetNumPackets() == 0)
empty_queue_cond->signal();
if (packet_pending) {
av_packet_move_ref(&pkt, &pkt);
packet_pending = false;
}
else {
if (queue->Get(&pkt, 1, &pkt_serial) < 0)
return -1;
}
} while (queue->GetSerial() != pkt_serial);
if (FFMPEGPacketQueue::IsFlushPacket(pkt.data)) {
avcodec_flush_buffers(avctx);
finished = 0;
next_pts = start_pts;
next_pts_tb = start_pts_tb;
}
else {
if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
int got_frame = 0;
ret = avcodec_decode_subtitle2(avctx, sub, &got_frame, &pkt);
if (ret < 0) {
ret = AVERROR(EAGAIN);
}
else {
if (got_frame && !pkt.data) {
packet_pending = 1;
av_packet_move_ref(&pkt, &pkt);
}
ret = got_frame ? 0 : (pkt.data ? AVERROR(EAGAIN) : AVERROR_EOF);
}
}
else {
if (avcodec_send_packet(avctx, &pkt) == AVERROR(EAGAIN)) {
av_log(avctx, AV_LOG_ERROR, "Receive_frame and send_packet both returned EAGAIN, which is an API violation.\n");
packet_pending = 1;
av_packet_move_ref(&pkt, &pkt);
}
}
av_packet_unref(&pkt);
}
}
return ret;
}
void FFMPEGDecoder::SetDecoderReorderPts ( int pts ) {
decoder_reorder_pts = pts;
}
void FFMPEGDecoder::Destroy() {
avcodec_free_context(&avctx);
avctx = NULL;
}
void FFMPEGDecoder::Abort(FFMPEGFrameQueue* fq) {
queue->Abort();
fq->Signal();
try {
if (decoder_tid->joinable()) {
decoder_tid->join();
}
}
catch (std::system_error &) {
}
delete decoder_tid;
queue->Flush();
}
int FFMPEGDecoder::Start(std::function<int (void *)> thread_func, void *arg ) {
queue->Start();
std::thread cpp_thread(thread_func, arg);
decoder_tid = new std::thread(std::move(cpp_thread));
if (!decoder_tid) {
//av_log(NULL, AV_LOG_ERROR, "SDL_CreateThread(): %s\n", SDL_GetError());
return AVERROR(ENOMEM);
}
#ifdef TARGET_WIN32
HANDLE hThread = decoder_tid->native_handle();
int currentPriority = GetThreadPriority(hThread);
if (currentPriority != THREAD_PRIORITY_HIGHEST &&
SetThreadPriority(hThread, THREAD_PRIORITY_HIGHEST) == 0) {
OFX_LOG(ofx_error, "Error setting the thread priority");
}
#endif
return 0;
}
AVCodecContext* FFMPEGDecoder::GetAvctx() {
return avctx;
}
int FFMPEGDecoder::GetPktSerial() {
return pkt_serial;
}
int FFMPEGDecoder::GetFinished() {
return finished;
}
void FFMPEGDecoder::SetTime ( int64_t _start_pts, AVRational _start_pts_tb) {
this->start_pts = _start_pts;
this->start_pts_tb = _start_pts_tb;
}
void FFMPEGDecoder::SetFinished ( int _finished ) {
this->finished = _finished;
}

View File

@ -0,0 +1,50 @@
#pragma once
#include "CondWait.h"
#include "FFMPEGPacketQueue.h"
#include "FFMPEGFrameQueue.h"
#include <thread>
#include <functional>
extern "C" {
#include <libavcodec/avcodec.h>
}
class FFMPEGDecoder
{
public:
FFMPEGDecoder();
~FFMPEGDecoder();
void Init(AVCodecContext *avctx, FFMPEGPacketQueue *queue, CondWait *empty_queue_cond);
int DecodeFrame( AVFrame *frame, AVSubtitle *sub);
void SetDecoderReorderPts ( int pts );
void Abort(FFMPEGFrameQueue* fq);
void Destroy();
int Start(std::function<int (void *)> thread_func, void *arg );
AVCodecContext* GetAvctx();
int GetPktSerial();
int GetFinished();
void SetTime ( int64_t start_pts, AVRational start_pts_tb);
void SetFinished ( int finished );
private:
int decoder_reorder_pts;
FFMPEGPacketQueue *queue;
AVCodecContext *avctx;
int pkt_serial;
int finished;
bool packet_pending;
CondWait *empty_queue_cond;
int64_t start_pts;
AVRational start_pts_tb;
int64_t next_pts;
AVRational next_pts_tb;
std::thread *decoder_tid;
};

View File

@ -0,0 +1,159 @@
#include "FFMPEGFrame.h"
FFMPEGFrame::FFMPEGFrame()
{
frame = NULL;
serial = 0;
pts = 0.0;
duration = 0.0;
pos = 0;
width = 0;
height = 0;
format = 0;
uploaded = false;
flip_v = false;
sub = {0};
}
FFMPEGFrame::~FFMPEGFrame()
{
Destroy();
}
int FFMPEGFrame::Init () {
Destroy();
frame = av_frame_alloc();
return frame == 0? 0: 1;
}
void FFMPEGFrame::Destroy() {
if (frame != NULL) {
UnRef();
av_frame_free(&frame);
}
frame = NULL;
uploaded = false;
}
void FFMPEGFrame::UnRef() {
if ( frame != NULL) {
av_frame_unref(frame);
avsubtitle_free(&sub);
}
}
int FFMPEGFrame::GetSerial() {
return serial;
}
int64_t FFMPEGFrame::GetPos() {
return pos;
}
double FFMPEGFrame::GetPts() {
return pts;
}
double FFMPEGFrame::GetDuration() {
return duration;
}
AVFrame* FFMPEGFrame::GetFrame() {
return frame;
}
int FFMPEGFrame::GetWidth() {
return width;
}
int FFMPEGFrame::GetHeight() {
return height;
}
int FFMPEGFrame::GetFormat() {
return format;
}
AVRational FFMPEGFrame::GetSar() {
return sar;
}
bool FFMPEGFrame::IsUploaded() {
return uploaded;
}
bool FFMPEGFrame::IsVerticalFlip() {
return flip_v;
}
AVSubtitle& FFMPEGFrame::GetSub() {
return sub;
}
double FFMPEGFrame::GetDifference(FFMPEGFrame* nextvp, double max) {
if (serial == nextvp->serial) {
double diff = nextvp->pts - pts;
if (isnan(diff) || diff <= 0 || diff > max)
return GetDuration();
else
return diff;
}
else {
return 0.0;
}
}
void FFMPEGFrame::UpdateFrame(AVFrame* src_frame, double _pts, double _duration, int64_t _pos, int _serial) {
this->sar = src_frame->sample_aspect_ratio;
this->uploaded = 0;
this->width = src_frame->width;
this->height = src_frame->height;
this->format = src_frame->format;
this->pts = _pts;
this->duration = _duration;
this->pos = _pos;
this->serial = _serial;
}
void FFMPEGFrame::UpdateSize(FFMPEGFrame *vp) {
width = vp->width;
height = vp->height;
}
void FFMPEGFrame::SetPts(double _pts) {
this->pts = _pts;
}
void FFMPEGFrame::SetSerial(int s) {
this->serial = s;
}
void FFMPEGFrame::SetWidth(int w) {
this->width = w;
}
void FFMPEGFrame::SetHeight(int h) {
this->height = h;
}
void FFMPEGFrame::SetUploaded(bool u) {
this->uploaded = u;
}
void FFMPEGFrame::SetVerticalFlip(bool fv) {
this->flip_v = fv;
}
void FFMPEGFrame::SetPos(int64_t p) {
this->pos = p;
}
void FFMPEGFrame::SetDuration(double d) {
this->duration = d;
}

View File

@ -0,0 +1,58 @@
#pragma once
extern "C" {
#include <libavcodec/avcodec.h>
}
class FFMPEGFrame
{
public:
FFMPEGFrame();
~FFMPEGFrame();
int Init ();
void Destroy();
void UnRef();
int GetSerial();
int64_t GetPos();
double GetPts();
double GetDuration();
AVFrame* GetFrame();
int GetWidth();
int GetHeight();
int GetFormat();
AVRational GetSar();
bool IsUploaded();
bool IsVerticalFlip();
AVSubtitle& GetSub();
void UpdateFrame(AVFrame* src_frame, double pts, double duration, int64_t pos, int serial);
void UpdateSize(FFMPEGFrame *vp);
void SetPos(int64_t pos);
void SetDuration(double duration);
void SetPts(double pts);
void SetSerial(int serial);
void SetWidth(int width);
void SetHeight(int height);
void SetUploaded(bool u);
void SetVerticalFlip(bool v);
double GetDifference( FFMPEGFrame* nextvp, double max );
private:
AVFrame *frame;
AVSubtitle sub;
int serial;
double pts; /* presentation timestamp for the frame */
double duration; /* estimated duration of the frame */
int64_t pos; /* byte position of the frame in the input file */
int width;
int height;
int format;
AVRational sar;
bool uploaded;
bool flip_v;
};

View File

@ -0,0 +1,160 @@
#include "FFMPEGFrameQueue.h"
#include "FFMPEGFrame.h"
FFMPEGFrameQueue::FFMPEGFrameQueue()
{
for ( int i = 0; i < FRAME_QUEUE_SIZE; i++) {
queue[i] = new FFMPEGFrame();
}
rindex = 0;
windex = 0;
size = 0;
max_size = 0;
keep_last = 0;
rindex_shown = 0;
pktq = NULL;
}
FFMPEGFrameQueue::~FFMPEGFrameQueue()
{
Destroy();
for (int i = 0; i < FRAME_QUEUE_SIZE; i++) {
if ( queue[i] ) delete queue[i];
queue[i] = NULL;
}
}
int FFMPEGFrameQueue::Init( FFMPEGPacketQueue *_pktq, int _max_size, int _keep_last) {
this->pktq = _pktq;
this->max_size = FFMIN(_max_size, FRAME_QUEUE_SIZE);
this->keep_last = !!_keep_last;
for (int i = 0; i < this->max_size; i++)
if (!(queue[i]->Init()))
return AVERROR(ENOMEM);
return 0;
}
void FFMPEGFrameQueue::Destroy() {
for (int i = 0; i < max_size; i++) {
FFMPEGFrame *vp = queue[i];
if ( vp) vp->Destroy();
}
rindex = 0;
windex = 0;
size = 0;
max_size = 0;
keep_last = 0;
rindex_shown = 0;
pktq = NULL;
}
void FFMPEGFrameQueue::Signal() {
mutex.Lock();
cond.signal();
mutex.Unlock();
}
FFMPEGFrame *FFMPEGFrameQueue::Peek() {
return queue[(rindex + rindex_shown) % max_size];
}
FFMPEGFrame *FFMPEGFrameQueue::PeekNext() {
return queue[(rindex + rindex_shown + 1) % max_size];
}
FFMPEGFrame *FFMPEGFrameQueue::PeekLast() {
return queue[rindex];
}
FFMPEGFrame *FFMPEGFrameQueue::PeekWritable() {
mutex.Lock();
while (size >= max_size &&
!pktq->IsAbortRequest()) {
cond.wait(mutex);
}
mutex.Unlock();
if (pktq->IsAbortRequest())
return NULL;
return queue[windex];
}
FFMPEGFrame *FFMPEGFrameQueue::PeekReadable() {
mutex.Lock();
while (size - rindex_shown <= 0 &&
!pktq->IsAbortRequest()) {
cond.wait(mutex);
}
mutex.Unlock();
if (pktq->IsAbortRequest())
return NULL;
return queue[(rindex + rindex_shown) % max_size];
}
int FFMPEGFrameQueue::QueuePicture( AVFrame *src_frame, double pts, double duration, int64_t pos, int serial) {
FFMPEGFrame *vp = PeekWritable();
if (!vp )
return -1;
vp->UpdateFrame(src_frame, pts, duration, pos, serial);
av_frame_move_ref(vp->GetFrame(), src_frame);
Push();
return 0;
}
void FFMPEGFrameQueue::Push() {
if (++windex == max_size)
windex = 0;
mutex.Lock();
size++;
cond.signal();
mutex.Unlock();
}
void FFMPEGFrameQueue::Next() {
if (keep_last && !rindex_shown) {
rindex_shown = 1;
return;
}
queue[rindex]->UnRef();
if (++rindex == max_size)
rindex = 0;
mutex.Lock();
size--;
cond.signal();
mutex.Unlock();
}
void FFMPEGFrameQueue::Lock() {
mutex.Lock();
}
void FFMPEGFrameQueue::Unlock() {
mutex.Unlock();
}
int FFMPEGFrameQueue::GetNumRemaining() {
return size - rindex_shown;
}
int64_t FFMPEGFrameQueue::GetQueueLastPos() {
FFMPEGFrame *fp = queue[rindex];
if (rindex_shown && fp->GetSerial() == pktq->GetSerial())
return fp->GetPos();
else
return -1;
}
int FFMPEGFrameQueue::GetIndexShown() {
return rindex_shown;
}

View File

@ -0,0 +1,59 @@
#pragma once
#include <mutex>
#include "FFMPEGPacketQueue.h"
#ifndef FFMAX
#define FFMAX(a,b) ((a) > (b) ? (a) : (b))
#endif
#define VIDEO_PICTURE_QUEUE_SIZE 3
#define SUBPICTURE_QUEUE_SIZE 16
#define SAMPLE_QUEUE_SIZE 9
#define FRAME_QUEUE_SIZE FFMAX(SAMPLE_QUEUE_SIZE, FFMAX(VIDEO_PICTURE_QUEUE_SIZE, SUBPICTURE_QUEUE_SIZE))
class FFMPEGFrame;
struct AVFrame;
class FFMPEGFrameQueue
{
public:
FFMPEGFrameQueue();
~FFMPEGFrameQueue();
int Init( FFMPEGPacketQueue *pktq, int max_size, int keep_last);
void Destroy();
void Signal();
int QueuePicture( AVFrame *src_frame, double pts, double duration, int64_t pos, int serial);
FFMPEGFrame *Peek();
FFMPEGFrame *PeekNext();
FFMPEGFrame *PeekLast();
FFMPEGFrame *PeekWritable();
FFMPEGFrame *PeekReadable();
void Push();
void Next();
void Lock();
void Unlock();
int64_t GetQueueLastPos();
int GetNumRemaining();
int GetIndexShown();
private:
FFMPEGFrame* queue[FRAME_QUEUE_SIZE];
int rindex;
int windex;
int size;
int max_size;
int keep_last;
int rindex_shown;
FCriticalSection mutex;
CondWait cond;
FFMPEGPacketQueue *pktq;
};

View File

@ -0,0 +1,203 @@
#include "FFMPEGPacketQueue.h"
extern "C" {
#include <inttypes.h>
#include "libavcodec/avcodec.h"
}
struct MyAVPacketList {
AVPacket pkt;
struct MyAVPacketList *next;
int serial;
};
typedef struct MyAVPacketList MyAVPacketList;
AVPacket* FFMPEGPacketQueue::flush_pkt_queue = NULL;
std::mutex flush_pkt_queue_mutex;
FFMPEGPacketQueue::FFMPEGPacketQueue()
{
first_pkt = NULL;
last_pkt = NULL;
nb_packets = 0;
size = 0;
duration = 0;
abort_request = true;
serial = 0;
}
FFMPEGPacketQueue::~FFMPEGPacketQueue()
{
Flush();
}
AVPacket* FFMPEGPacketQueue::FlushPkt() {
if ( flush_pkt_queue == NULL) {
flush_pkt_queue_mutex.lock();
if ( flush_pkt_queue == NULL) {
flush_pkt_queue = new AVPacket();
av_init_packet(flush_pkt_queue);
flush_pkt_queue->data = (uint8_t *)flush_pkt_queue;
}
flush_pkt_queue_mutex.unlock();
}
return flush_pkt_queue;
}
int FFMPEGPacketQueue::Put(AVPacket *pkt) {
int ret;
mutex.Lock();
ret = PutPrivate( pkt);
mutex.Unlock();
if (pkt != FlushPkt() && ret < 0)
av_packet_unref(pkt);
return ret;
}
int FFMPEGPacketQueue::PutNullPacket(int stream_index) {
AVPacket pkt1, *pkt = &pkt1;
av_init_packet(pkt);
pkt->data = NULL;
pkt->size = 0;
pkt->stream_index = stream_index;
return Put(pkt);
}
int FFMPEGPacketQueue::PutPrivate(AVPacket *pkt) {
MyAVPacketList *pkt1;
if (abort_request)
return -1;
pkt1 = new MyAVPacketList();
if (!pkt1)
return -1;
pkt1->pkt = *pkt;
pkt1->next = NULL;
if (pkt == FlushPkt())
serial++;
pkt1->serial = serial;
if (!last_pkt)
first_pkt = pkt1;
else
last_pkt->next = pkt1;
last_pkt = pkt1;
nb_packets++;
size += pkt1->pkt.size + sizeof(*pkt1);
duration += pkt1->pkt.duration;
/* XXX: should duplicate packet data in DV case */
cond.signal();
return 0;
}
int FFMPEGPacketQueue::Get(AVPacket *pkt, int block, int *_serial) {
MyAVPacketList *pkt1;
int ret;
mutex.Lock();
for (;;) {
if (abort_request) {
ret = -1;
break;
}
pkt1 = first_pkt;
if (pkt1) {
first_pkt = pkt1->next;
if (!first_pkt)
last_pkt = NULL;
nb_packets--;
size -= pkt1->pkt.size + sizeof(*pkt1);
duration -= pkt1->pkt.duration;
*pkt = pkt1->pkt;
if (_serial)
*_serial = pkt1->serial;
delete pkt1;
ret = 1;
break;
}
else if (!block) {
ret = 0;
break;
}
else {
cond.wait(mutex);
}
}
mutex.Unlock();
return ret;
}
void FFMPEGPacketQueue::Abort() {
mutex.Lock();
abort_request = true;
cond.signal();
mutex.Unlock();
}
void FFMPEGPacketQueue::Start() {
mutex.Lock();
abort_request = false;
PutPrivate(FlushPkt());
mutex.Unlock();
}
void FFMPEGPacketQueue::Flush() {
MyAVPacketList *pkt, *pkt1;
mutex.Lock();
for (pkt = first_pkt; pkt; pkt = pkt1) {
pkt1 = pkt->next;
av_packet_unref(&pkt->pkt);
delete pkt;
}
last_pkt = NULL;
first_pkt = NULL;
nb_packets = 0;
size = 0;
duration = 0;
mutex.Unlock();
}
int FFMPEGPacketQueue::PutFlush() {
return Put(FlushPkt());
}
int FFMPEGPacketQueue::GetSize() {
return size;
}
int FFMPEGPacketQueue::GetSerial() {
return serial;
}
bool FFMPEGPacketQueue::IsAbortRequest() {
return abort_request;
}
int FFMPEGPacketQueue::GetNumPackets() {
return nb_packets;
}
int FFMPEGPacketQueue::GetDuration() {
return duration;
}
bool FFMPEGPacketQueue::IsFlushPacket( void* data) {
if ( flush_pkt_queue != NULL) {
return flush_pkt_queue->data == data;
}
return false;
}

View File

@ -0,0 +1,50 @@
#pragma once
#include "CondWait.h"
#include <mutex>
struct MyAVPacketList;
struct AVPacket;
class FFMPEGPacketQueue
{
public:
FFMPEGPacketQueue();
~FFMPEGPacketQueue();
int Get(AVPacket *pkt, int block, int *serial);
int Put(AVPacket *pkt);
int PutFlush();
int PutNullPacket(int stream_index);
void Start();
void Abort();
void Flush();
int GetSize();
bool IsAbortRequest();
int GetSerial();
int GetNumPackets();
int GetDuration();
static bool IsFlushPacket( void* data);
protected:
AVPacket* FlushPkt();
int PutPrivate(AVPacket *pkt);
static AVPacket* flush_pkt_queue;
MyAVPacketList *first_pkt, *last_pkt;
int nb_packets;
int size;
int64_t duration;
bool abort_request;
int serial;
FCriticalSection mutex;
CondWait cond;
friend class FFMPEGClock;
};

View File

@ -0,0 +1,291 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "FFMPEGMediaPrivate.h"
#include "IMediaCaptureSupport.h"
#include "Modules/ModuleManager.h"
#include "IFFMPEGMediaModule.h"
#include "Core.h"
#include "Interfaces/IPluginManager.h"
#include "IMediaModule.h"
#include "Modules/ModuleInterface.h"
#include "Templates/SharedPointer.h"
#if PLATFORM_ANDROID
#include "Android/AndroidJNI.h"
#endif
extern "C" {
#include "libavformat/avformat.h"
#if PLATFORM_ANDROID
#include "libavcodec/jni.h"
#endif
}
#include "FFMPEGMediaPlayer.h"
DEFINE_LOG_CATEGORY(LogFFMPEGMedia);
/**
* Implements the FFMPEGMedia module.
*/
class FFFMPEGMediaModule
: /*public IMediaCaptureSupport
,*/ public IFFMPEGMediaModule
{
public:
/** Default constructor. */
FFFMPEGMediaModule()
: Initialized(false) {
AVDeviceLibrary = nullptr;
AVFilterLibrary = nullptr;
PostProcLibrary = nullptr;
SWScaleLibrary = nullptr;
AVFormatLibrary = nullptr;
AVCodecLibrary = nullptr;
SWResampleLibrary = nullptr;
AVUtilLibrary = nullptr;
}
public:
//~ IWmfMediaModule interface
virtual TSharedPtr<IMediaPlayer, ESPMode::ThreadSafe> CreatePlayer(IMediaEventSink& EventSink) override
{
if (!Initialized)
{
return nullptr;
}
return MakeShareable(new FFFMPEGMediaPlayer(EventSink));
}
virtual TArray<FString> GetSupportedFileExtensions() override {
TMap<FString, FString> extensionMap;
void *ofmt_opaque = NULL;
const AVOutputFormat *ofmt = av_muxer_iterate(&ofmt_opaque);
while (ofmt) {
FString ext = ofmt->extensions;
TArray<FString> supportedExts;
ext.ParseIntoArray(supportedExts, TEXT(","));
for ( const FString& s: supportedExts) {
if ( extensionMap.Contains(s)) {
extensionMap[s] += TEXT(",") + FString(ofmt->name);
} else {
extensionMap.Add(s, ofmt->name );
}
}
//extensionMap.Add()
ofmt = av_muxer_iterate(&ofmt_opaque);
}
TArray<FString> extensions;
extensionMap.GetKeys(extensions);
return extensions;
}
virtual TArray<FString> GetSupportedUriSchemes() override {
void *opaque = NULL;
const char *name = avio_enum_protocols(&opaque, 1);
TArray<FString> protocols;
while (name) {
protocols.Add(name);
name = avio_enum_protocols(&opaque, 1);
}
return protocols;
}
public:
static void log_callback(void*, int level , const char* format, va_list arglist ) {
char buffer[2048];
#if PLATFORM_WINDOWS
vsprintf_s(buffer, 2048, format, arglist);
#else
vsnprintf(buffer, 2048, format, arglist);
#endif
FString str = TEXT("FFMPEG - ");
str += buffer;
switch (level) {
case AV_LOG_TRACE:
UE_LOG(LogFFMPEGMedia, VeryVerbose, TEXT("%s"), *str);
break;
case AV_LOG_DEBUG:
UE_LOG(LogFFMPEGMedia, VeryVerbose, TEXT("%s"), *str );
break;
case AV_LOG_VERBOSE:
UE_LOG(LogFFMPEGMedia, Verbose, TEXT("%s"), *str );
break;
case AV_LOG_INFO:
UE_LOG(LogFFMPEGMedia, Display, TEXT("%s"), *str );
break;
case AV_LOG_WARNING:
UE_LOG(LogFFMPEGMedia, Warning, TEXT("%s"), *str );
break;
case AV_LOG_ERROR:
UE_LOG(LogFFMPEGMedia, Error, TEXT("%s"), *str );
break;
case AV_LOG_FATAL:
UE_LOG(LogFFMPEGMedia, Fatal, TEXT("%s"), *str );
break;
default:
UE_LOG(LogFFMPEGMedia, Display, TEXT("%s"), *str );
}
}
//~ IModuleInterface interface
virtual void StartupModule() override
{
#if PLATFORM_ANDROID
UE_LOG(LogFFMPEGMedia, Verbose, TEXT("Avoid load the libraries once again on android"));
#else
AVUtilLibrary = LoadLibrary(TEXT("avutil"), TEXT("56"));
SWResampleLibrary = LoadLibrary(TEXT("swresample"), TEXT("3"));
AVCodecLibrary = LoadLibrary(TEXT("avcodec"), TEXT("58"));
AVFormatLibrary = LoadLibrary(TEXT("avformat"), TEXT("58"));
SWScaleLibrary = LoadLibrary(TEXT("swscale"), TEXT("5"));
PostProcLibrary = LoadLibrary(TEXT("postproc"), TEXT("55"));
AVFilterLibrary = LoadLibrary(TEXT("avfilter"), TEXT("7"));
AVDeviceLibrary = LoadLibrary(TEXT("avdevice"), TEXT("58"));
#endif
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
av_register_all();
#endif
avformat_network_init();
av_log_set_level(AV_LOG_INFO);
av_log_set_callback(&log_callback);
UE_LOG(LogFFMPEGMedia, Display, TEXT("FFmpeg AVCodec version: %d.%d.%d"), LIBAVFORMAT_VERSION_MAJOR, LIBAVFORMAT_VERSION_MINOR, LIBAVFORMAT_VERSION_MICRO);
UE_LOG(LogFFMPEGMedia, Display, TEXT("FFmpeg license: %s"), UTF8_TO_TCHAR(avformat_license()));
// register capture device support
auto MediaModule = FModuleManager::LoadModulePtr<IMediaModule>("Media");
if (MediaModule != nullptr)
{
//TODO: Implement Capture support
//MediaModule->RegisterCaptureSupport(*this);
} else {
UE_LOG(LogFFMPEGMedia, Error, TEXT("Coudn't find the media module"));
}
#if PLATFORM_ANDROID
// hopefully this is early enough; we don't have a way add into JNI_OnLoad in AndroidJNI.cpp
if (GJavaVM == NULL) {
UE_LOG(LogFFMPEGMedia, Error, TEXT("The global vm hasn't been initialized"));
} else {
UE_LOG(LogFFMPEGMedia, Display, TEXT("Initialize virtual machine for FFMPEG"));
av_jni_set_java_vm(GJavaVM, NULL);
}
#endif
Initialized = true;
}
virtual void ShutdownModule() override
{
if (!Initialized)
{
return;
}
// unregister capture support
auto MediaModule = FModuleManager::GetModulePtr<IMediaModule>("Media");
if (MediaModule != nullptr)
{
//MediaModule->UnregisterCaptureSupport(*this);
}
if (AVDeviceLibrary) FPlatformProcess::FreeDllHandle(AVDeviceLibrary);
if (AVFilterLibrary) FPlatformProcess::FreeDllHandle(AVFilterLibrary);
if (PostProcLibrary) FPlatformProcess::FreeDllHandle(PostProcLibrary);
if (SWScaleLibrary) FPlatformProcess::FreeDllHandle(SWScaleLibrary);
if (AVFormatLibrary) FPlatformProcess::FreeDllHandle(AVFormatLibrary);
if (AVCodecLibrary) FPlatformProcess::FreeDllHandle(AVCodecLibrary);
if (SWResampleLibrary) FPlatformProcess::FreeDllHandle(SWResampleLibrary);
if (AVUtilLibrary) FPlatformProcess::FreeDllHandle(AVUtilLibrary);
Initialized = false;
}
protected:
void* LoadLibrary(const FString& name, const FString& version) {
FString BaseDir = IPluginManager::Get().FindPlugin("FFMPEGMedia")->GetBaseDir();
FString LibDir;
FString extension;
FString prefix;
FString separator;
#if PLATFORM_MAC
LibDir = FPaths::Combine(*BaseDir, TEXT("ThirdParty/ffmpeg/lib/osx"));
extension = TEXT(".dylib");
prefix = "lib";
separator = ".";
#elif PLATFORM_WINDOWS
extension = TEXT(".dll");
prefix = "";
separator = "-";
#if PLATFORM_64BITS
LibDir = FPaths::Combine(*BaseDir, TEXT("ThirdParty/ffmpeg/bin/vs/x64"));
#else
LibDir = FPaths::Combine(*BaseDir, TEXT("ThirdParty/ffmpeg/bin/vs/win32"));
#endif
#endif
if (!LibDir.IsEmpty()) {
FString LibraryPath = FPaths::Combine(*LibDir, prefix + name + separator + version + extension);
return FPlatformProcess::GetDllHandle(*LibraryPath);
}
return nullptr;
}
private:
void* AVUtilLibrary;
void* SWResampleLibrary;
void* AVCodecLibrary;
void* SWScaleLibrary;
void* AVFormatLibrary;
void* PostProcLibrary;
void* AVFilterLibrary;
void* AVDeviceLibrary;
/** Whether the module has been initialized. */
bool Initialized;
};
IMPLEMENT_MODULE(FFFMPEGMediaModule, FFMPEGMedia);

View File

@ -0,0 +1,9 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Logging/LogMacros.h"
/** Log category for the WmfMedia module. */
DECLARE_LOG_CATEGORY_EXTERN(LogFFMPEGMedia, Log, All);

View File

@ -0,0 +1,22 @@
#include "LambdaFunctionRunnable.h"
LambdaFunctionRunnable::LambdaFunctionRunnable(std::function<void()> f) {
_f = f;
}
FRunnableThread* LambdaFunctionRunnable::RunThreaded(FString threadName, std::function<void()> f) {
static int currentThread = 0;
LambdaFunctionRunnable* runnable = new LambdaFunctionRunnable(f);
FString _threadName = threadName + FString::FromInt(currentThread++);
runnable->thread = FRunnableThread::Create(runnable, *_threadName);
return runnable->thread;
}
uint32 LambdaFunctionRunnable::Run() {
_f();
return 0;
}
void LambdaFunctionRunnable::Exit() {
delete this;
}

View File

@ -0,0 +1,16 @@
#pragma once
#include <HAL/RunnableThread.h>
#include <functional>
#include <HAL/Runnable.h>
class LambdaFunctionRunnable : public FRunnable {
public:
static FRunnableThread* RunThreaded(FString threadName, std::function<void()> f);
void Exit() override;
uint32 Run() override;
protected:
LambdaFunctionRunnable(std::function<void()> f);
std::function<void()> _f;
FRunnableThread* thread;
};

View File

@ -0,0 +1,127 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreTypes.h"
#include "Containers/Array.h"
#include "IMediaAudioSample.h"
#include "MediaObjectPool.h"
#include "MediaSampleQueue.h"
#include "Math/IntPoint.h"
#include "Misc/Timespan.h"
/**
* Implements a media audio sample for WmfMedia.
*/
class FFFMPEGMediaAudioSample
: public IMediaAudioSample
, public IMediaPoolable
{
public:
/** Default constructor. */
FFFMPEGMediaAudioSample()
: Channels(0)
, Duration(FTimespan::Zero())
, SampleRate(0)
, Time(FTimespan::Zero())
{ }
/** Virtual destructor. */
virtual ~FFFMPEGMediaAudioSample() { }
public:
/**
* Initialize the sample.
*
* @param InBuffer The sample's data buffer.
* @param InSize The size of the sample buffer (in bytes).
* @param InTime The sample time (relative to presentation clock).
* @param InDuration The duration for which the sample is valid.
*/
bool Initialize(
const uint8* InBuffer,
uint32 InSize,
uint32 InChannels,
uint32 InSampleRate,
FTimespan InTime,
FTimespan InDuration)
{
if ((InBuffer == nullptr) || (InSize == 0))
{
return false;
}
Buffer.Reset(InSize);
Buffer.Append(InBuffer, InSize);
Channels = InChannels;
Duration = InDuration;
SampleRate = InSampleRate;
Time = InTime;
return true;
}
public:
//~ IMediaAudioSample interface
virtual const void* GetBuffer() override
{
return Buffer.GetData();
}
virtual uint32 GetChannels() const override
{
return Channels;
}
virtual FTimespan GetDuration() const override
{
return Duration;
}
virtual EMediaAudioSampleFormat GetFormat() const override
{
return EMediaAudioSampleFormat::Int16;
}
virtual uint32 GetFrames() const override
{
return Buffer.Num() / (Channels * sizeof(int16));
}
virtual uint32 GetSampleRate() const override
{
return SampleRate;
}
virtual FMediaTimeStamp GetTime() const override
{
return Time;
}
private:
/** The sample's data buffer. */
TArray<uint8> Buffer;
/** Number of audio channels. */
uint32 Channels;
/** The duration for which the sample is valid. */
FTimespan Duration;
/** Audio sample rate (in samples per second). */
uint32 SampleRate;
/** Presentation time for which the sample was generated. */
FMediaTimeStamp Time;
};
/** Implements a pool for WMF audio sample objects. */
class FFFMPEGMediaAudioSamplePool : public TMediaObjectPool<FFFMPEGMediaAudioSample> { };

View File

@ -0,0 +1,93 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreTypes.h"
#include "Containers/Array.h"
#include "IMediaBinarySample.h"
#include "MediaSampleQueue.h"
#include "Misc/Timespan.h"
/**
* Implements a media binary data sample for WmfMedia.
*/
class FFFMPEGMediaBinarySample
: public IMediaBinarySample
{
public:
/** Default constructor. */
FFFMPEGMediaBinarySample()
: Duration(FTimespan::Zero())
, Time(FTimespan::Zero())
{ }
/** Virtual destructor. */
virtual ~FFFMPEGMediaBinarySample() { }
public:
/**
* Initialize the sample.
*
* @param InBuffer The sample's data buffer.
* @param InSize Size of the buffer.
* @param InTime The sample time (relative to presentation clock).
* @param InDuration The duration for which the sample is valid.
*/
bool Initialize(
const void* InBuffer,
uint32 InSize,
FTimespan InTime,
FTimespan InDuration)
{
if ((InBuffer == nullptr) || (InSize == 0))
{
return false;
}
Buffer.Reset(InSize);
Buffer.Append((uint8*)InBuffer, InSize);
Duration = InDuration;
Time = InTime;
return true;
}
public:
//~ IMediaBinarySample interface
virtual const void* GetData() override
{
return Buffer.GetData();
}
virtual FTimespan GetDuration() const override
{
return Duration;
}
virtual uint32 GetSize() const override
{
return Buffer.Num();
}
virtual FMediaTimeStamp GetTime() const override
{
return Time;
}
private:
/** The sample's data buffer. */
TArray<uint8> Buffer;
/** Duration for which the sample is valid. */
FTimespan Duration;
/** Presentation time for which the sample was generated. */
FMediaTimeStamp Time;
};

View File

@ -0,0 +1,126 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreTypes.h"
#include "IMediaOverlaySample.h"
#include "Internationalization/Regex.h"
#include "MediaSampleQueue.h"
#include "Misc/Timespan.h"
/**
* Implements an overlay text sample for WmfMedia.
*/
class FFFMPEGMediaOverlaySample
: public IMediaOverlaySample
{
public:
/** Default constructor. */
FFFMPEGMediaOverlaySample()
: Duration(FTimespan::Zero())
, Time(FTimespan::Zero())
{ }
/** Virtual destructor. */
virtual ~FFFMPEGMediaOverlaySample() { }
public:
/**
* Initialize the sample.
*
* @param InBuffer The sample's data buffer.
* @param InTime The sample time (relative to presentation clock).
* @param InDuration The duration for which the sample is valid.
*/
bool Initialize(
const char* InBuffer,
FVector2D InPosition,
FTimespan InTime,
FTimespan InDuration)
{
if (InBuffer == nullptr)
{
return false;
}
// simply strip all formatting for now
FString StrippedText;
{
static const FRegexPattern StripHtmlPattern(TEXT("<(?:[^>=]|='[^']*'|=\"[^\"]*\"|=[^'\"][^\\s>]*)*>"));
const FString InputText = ANSI_TO_TCHAR(InBuffer);
FRegexMatcher Matcher(StripHtmlPattern, InputText);
int32 TextBegin = INDEX_NONE;
while (Matcher.FindNext())
{
if (TextBegin != INDEX_NONE)
{
StrippedText += InputText.Mid(TextBegin, Matcher.GetMatchBeginning() - TextBegin);
}
TextBegin = Matcher.GetMatchEnding();
}
if (TextBegin > INDEX_NONE)
{
StrippedText += InputText.Mid(TextBegin);
}
}
Duration = (InDuration < FTimespan::Zero()) ? FTimespan::MaxValue() : InDuration;
Text = FText::FromString(StrippedText);
Time = InTime;
Position = InPosition;
return true;
}
public:
//~ IMediaOverlaySample interface
virtual FTimespan GetDuration() const override
{
return Duration;
}
virtual TOptional<FVector2D> GetPosition() const override
{
return TOptional<FVector2D>();
}
virtual FText GetText() const override
{
return Text;
}
virtual FMediaTimeStamp GetTime() const override
{
return Time;
}
virtual EMediaOverlaySampleType GetType() const override
{
return EMediaOverlaySampleType::Subtitle;
}
private:
/** The duration for which the sample is valid. */
FTimespan Duration;
/** The overlay text. */
FText Text;
/** Presentation time for which the sample was generated. */
FMediaTimeStamp Time;
/** Position for the subtitle */
FVector2D Position;
};

View File

@ -0,0 +1,589 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "FFMPEGMediaPlayer.h"
#include "Async/Async.h"
#include "IMediaEventSink.h"
#include "IMediaOptions.h"
#include "Misc/Optional.h"
#include "UObject/Class.h"
#include "FFMPEGMediaTracks.h"
#include "FFMPEGMediaSettings.h"
extern "C" {
#include "libavformat/avformat.h"
#include "libavutil/opt.h"
#include "libavutil/time.h"
}
#define FF_INPUT_BUFFER_PADDING_SIZE 32
/* FWmfVideoPlayer structors
*****************************************************************************/
FFFMPEGMediaPlayer::FFFMPEGMediaPlayer(IMediaEventSink& InEventSink)
:
EventSink(InEventSink)
, Tracks(MakeShared<FFFMPEGMediaTracks, ESPMode::ThreadSafe>())
{
check(Tracks.IsValid());
IOContext = nullptr;
FormatContext = nullptr;
stopped = true;
}
FFFMPEGMediaPlayer::~FFFMPEGMediaPlayer()
{
Close();
}
/* IMediaPlayer interface
*****************************************************************************/
void FFFMPEGMediaPlayer::Close()
{
if (Tracks->GetState() == EMediaState::Closed)
{
return;
}
// reset player
stopped = true;
MediaUrl = FString();
Tracks->Shutdown();
if (FormatContext) {
FormatContext->video_codec = NULL;
FormatContext->audio_codec = NULL;
avformat_close_input(&FormatContext);
FormatContext = nullptr;
}
if (IOContext) {
av_free(IOContext->buffer);
av_free(IOContext);
IOContext = nullptr;
}
// notify listeners
EventSink.ReceiveMediaEvent(EMediaEvent::TracksChanged);
EventSink.ReceiveMediaEvent(EMediaEvent::MediaClosed);
}
IMediaCache& FFFMPEGMediaPlayer::GetCache()
{
return *this;
}
IMediaControls& FFFMPEGMediaPlayer::GetControls()
{
return *Tracks;
}
FString FFFMPEGMediaPlayer::GetInfo() const
{
return Tracks->GetInfo();
}
FName FFFMPEGMediaPlayer::GetPlayerName() const
{
static FName PlayerName(TEXT("FFMPEGMedia"));
return PlayerName;
}
FGuid FFFMPEGMediaPlayer::GetPlayerPluginGUID() const
{
// {938BEEB4-2E88-450E-9C1C-6109456279B3}
static FGuid PlayerPluginGUID(0x938beeb4, 0x2e88450e, 0x9c1c6109, 0x456279b3);
return PlayerPluginGUID;
}
IMediaSamples& FFFMPEGMediaPlayer::GetSamples()
{
return *Tracks;
}
FString FFFMPEGMediaPlayer::GetStats() const
{
FString Result;
Tracks->AppendStats(Result);
return Result;
}
IMediaTracks& FFFMPEGMediaPlayer::GetTracks()
{
return *Tracks;
}
FString FFFMPEGMediaPlayer::GetUrl() const
{
return MediaUrl;
}
IMediaView& FFFMPEGMediaPlayer::GetView()
{
return *this;
}
bool FFFMPEGMediaPlayer::Open(const FString& Url, const IMediaOptions* Options, const FMediaPlayerOptions* PlayerOptions) {
Close();
if (Url.IsEmpty())
{
return false;
}
const bool Precache = (Options != nullptr) ? Options->GetMediaOption("PrecacheFile", false) : false;
return InitializePlayer(nullptr, Url, Precache, PlayerOptions);
}
bool FFFMPEGMediaPlayer::Open(const FString& Url, const IMediaOptions* Options)
{
return Open(Url, Options, nullptr);
}
bool FFFMPEGMediaPlayer::Open(const TSharedRef<FArchive, ESPMode::ThreadSafe>& Archive, const FString& OriginalUrl, const IMediaOptions* /*Options*/)
{
Close();
if (Archive->TotalSize() == 0)
{
UE_LOG(LogFFMPEGMedia, Verbose, TEXT("Player %p: Cannot open media from archive (archive is empty)"), this);
return false;
}
if (OriginalUrl.IsEmpty())
{
UE_LOG(LogFFMPEGMedia, Verbose, TEXT("Player %p: Cannot open media from archive (no original URL provided)"), this);
return false;
}
return InitializePlayer(Archive, OriginalUrl, false, nullptr);
}
void FFFMPEGMediaPlayer::TickFetch(FTimespan DeltaTime, FTimespan Timecode)
{
bool MediaSourceChanged = false;
bool TrackSelectionChanged = false;
Tracks->GetFlags(MediaSourceChanged, TrackSelectionChanged);
if (MediaSourceChanged)
{
EventSink.ReceiveMediaEvent(EMediaEvent::TracksChanged);
}
if (TrackSelectionChanged)
{
}
if (MediaSourceChanged || TrackSelectionChanged)
{
Tracks->ClearFlags();
}
}
void FFFMPEGMediaPlayer::TickInput(FTimespan DeltaTime, FTimespan Timecode)
{
Tracks->TickInput(DeltaTime, Timecode);
// forward session events
TArray<EMediaEvent> OutEvents;
Tracks->GetEvents(OutEvents);
for (const auto& Event : OutEvents)
{
EventSink.ReceiveMediaEvent(Event);
}
// process deferred tasks
TFunction<void()> Task;
while (PlayerTasks.Dequeue(Task))
{
Task();
}
}
/* FFFMPEGMediaPlayer implementation
*****************************************************************************/
bool FFFMPEGMediaPlayer::InitializePlayer(const TSharedPtr<FArchive, ESPMode::ThreadSafe>& Archive, const FString& Url, bool Precache, const FMediaPlayerOptions* PlayerOptions )
{
UE_LOG(LogFFMPEGMedia, Verbose, TEXT("Player %llx: Initializing %s (archive = %s, precache = %s)"), this, *Url, Archive.IsValid() ? TEXT("yes") : TEXT("no"), Precache ? TEXT("yes") : TEXT("no"));
const auto Settings = GetDefault<UFFMPEGMediaSettings>();
check(Settings != nullptr);
MediaUrl = Url;
// initialize presentation on a separate thread
const EAsyncExecution Execution = Precache ? EAsyncExecution::Thread : EAsyncExecution::ThreadPool;
TFunction <void()> Task = [Archive, Url, Precache, PlayerOptions, TracksPtr = TWeakPtr<FFFMPEGMediaTracks, ESPMode::ThreadSafe>(Tracks), ThisPtr=this]()
{
TSharedPtr<FFFMPEGMediaTracks, ESPMode::ThreadSafe> PinnedTracks = TracksPtr.Pin();
if (PinnedTracks.IsValid() )
{
AVFormatContext* context = ThisPtr->ReadContext(Archive, Url, Precache);
if (context) {
PinnedTracks->Initialize(context, Url, PlayerOptions);
}
}
};
Async(Execution, Task);
return true;
}
int FFFMPEGMediaPlayer::DecodeInterruptCallback(void *ctx) {
FFFMPEGMediaPlayer* player = static_cast<FFFMPEGMediaPlayer*>(ctx);
return player->stopped?1:0;
}
int FFFMPEGMediaPlayer::ReadtStreamCallback(void* opaque, uint8_t* buf, int buf_size) {
FFFMPEGMediaPlayer* player = static_cast<FFFMPEGMediaPlayer*>(opaque);
int64 Position = player->CurrentArchive->Tell();
int64 Size = player->CurrentArchive->TotalSize();
int64 BytesToRead = buf_size;
if (BytesToRead > (int64)Size)
{
BytesToRead = Size;
}
if ((Size - BytesToRead) < player->CurrentArchive->Tell())
{
BytesToRead = Size - Position;
}
if (BytesToRead > 0)
{
player->CurrentArchive->Serialize(buf, BytesToRead);
}
player->CurrentArchive->Seek(Position + BytesToRead);
return BytesToRead;
}
int64_t FFFMPEGMediaPlayer::SeekStreamCallback(void *opaque, int64_t offset, int whence) {
FFFMPEGMediaPlayer* player = static_cast<FFFMPEGMediaPlayer*>(opaque);
if (whence == AVSEEK_SIZE) {
return player->CurrentArchive->TotalSize();
}
int64_t pos = player->CurrentArchive->Tell();
player->CurrentArchive->Seek(pos + offset);
return player->CurrentArchive->Tell();
}
AVFormatContext* FFFMPEGMediaPlayer::ReadContext(const TSharedPtr<FArchive, ESPMode::ThreadSafe>& Archive, const FString& Url, bool Precache) {
AVDictionary *format_opts = NULL;
int scan_all_pmts_set = 0;
FormatContext = avformat_alloc_context();
stopped = false;
FormatContext->interrupt_callback.callback = DecodeInterruptCallback;
FormatContext->interrupt_callback.opaque = this;
if (!av_dict_get(format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
av_dict_set(&format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
scan_all_pmts_set = 1;
}
const auto Settings = GetDefault<UFFMPEGMediaSettings>();
if ( Settings->RtspTransport != ERTSPTransport::Default) {
switch (Settings->RtspTransport) {
case ERTSPTransport::Udp:
av_dict_set(&format_opts, "rtsp_transport", "udp", 0);
break;
case ERTSPTransport::Tcp:
av_dict_set(&format_opts, "rtsp_transport", "tcp", 0);
break;
case ERTSPTransport::UdpMulticast:
av_dict_set(&format_opts, "rtsp_transport", "udp_multicast", 0);
break;
case ERTSPTransport::Http:
av_dict_set(&format_opts, "rtsp_transport", "http", 0);
break;
case ERTSPTransport::Https:
av_dict_set(&format_opts, "rtsp_transport", "https", 0);
break;
default:
break;
}
}
if ( Settings->ZeroLatencyStreaming) {
av_dict_set(&format_opts, "fflags", "nobuffer", 0);
}
int err = 0;
if (!Archive.IsValid()) {
if (Url.StartsWith(TEXT("file://")))
{
const TCHAR* FilePath = &Url[7];
err = avformat_open_input(&FormatContext, TCHAR_TO_UTF8(FilePath), NULL, &format_opts);
} else {
err = avformat_open_input(&FormatContext, TCHAR_TO_UTF8(*Url), NULL, &format_opts);
}
} else {
CurrentArchive = Archive;
const int ioBufferSize = 32768;
unsigned char * ioBuffer = (unsigned char *)av_malloc(ioBufferSize + FF_INPUT_BUFFER_PADDING_SIZE);
IOContext = avio_alloc_context(ioBuffer, ioBufferSize, 0, this, ReadtStreamCallback, NULL, SeekStreamCallback);
FormatContext->pb = IOContext;
err = avformat_open_input(&FormatContext, "InMemoryFile", NULL, &format_opts);
}
if (err < 0) {
char errbuf[128];
const char *errbuf_ptr = errbuf;
#if PLATFORM_WINDOWS
if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
strerror_s(errbuf, 128, AVUNERROR(err));
#else
if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
errbuf_ptr = strerror(AVUNERROR(err));
#endif
PlayerTasks.Enqueue([=]() {
EventSink.ReceiveMediaEvent(EMediaEvent::MediaOpenFailed);
});
if ( FormatContext ) {
avformat_close_input(&FormatContext);
FormatContext = nullptr;
}
stopped = true;
return FormatContext;
}
if (scan_all_pmts_set)
av_dict_set(&format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
AVDictionaryEntry *t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX);
if (t) {
UE_LOG(LogFFMPEGMedia, Error, TEXT("Option %s not found"), UTF8_TO_TCHAR(t->key));
PlayerTasks.Enqueue([=]() {
EventSink.ReceiveMediaEvent(EMediaEvent::MediaOpenFailed);
});
if ( FormatContext ) {
avformat_close_input(&FormatContext);
FormatContext = nullptr;
}
stopped = true;
return FormatContext;
}
av_dict_free(&format_opts);
av_format_inject_global_side_data(FormatContext);
err = avformat_find_stream_info(FormatContext, NULL);
if (FormatContext->pb)
FormatContext->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use avio_feof() to test for the end
#ifdef UE_BUILD_DEBUG
dumpFFMPEGInfo();
#endif
return FormatContext;
}
static void print_option(const AVClass *clazz, const AVOption *o) {
FString type;
switch (o->type) {
case AV_OPT_TYPE_BINARY: type = TEXT("hexadecimal string"); break;
case AV_OPT_TYPE_STRING: type = TEXT("string"); break;
case AV_OPT_TYPE_INT:
case AV_OPT_TYPE_INT64: type = TEXT("integer"); break;
case AV_OPT_TYPE_FLOAT:
case AV_OPT_TYPE_DOUBLE: type = TEXT("float"); break;
case AV_OPT_TYPE_RATIONAL: type = TEXT("rational number"); break;
case AV_OPT_TYPE_FLAGS: type = TEXT("flags"); break;
case AV_OPT_TYPE_BOOL: type = TEXT("bool"); break;
case AV_OPT_TYPE_SAMPLE_FMT:type = TEXT("SampleFmt"); break;
default: type = TEXT("value"); break;
}
FString flags;
if (o->flags & AV_OPT_FLAG_ENCODING_PARAM) {
flags = TEXT("input");
if (o->flags & AV_OPT_FLAG_ENCODING_PARAM)
flags += TEXT("/");
}
if (o->flags & AV_OPT_FLAG_ENCODING_PARAM)
flags += TEXT("output");
FString help;
if (o->help)
help = o->help;
FString possibleValues;
if (o->unit) {
const AVOption *u = av_opt_next(&clazz, NULL);
while (u) {
bool found = false;
if (u->type == AV_OPT_TYPE_CONST && u->unit && !strcmp(u->unit, o->unit)) {
possibleValues += "\n";
possibleValues += "\t\t* ";
possibleValues += u->name;
found = true;
}
u = av_opt_next(&clazz, u);
}
}
if ( o->unit) {
UE_LOG(LogFFMPEGMedia, Display, TEXT("\t%s - %s: %s %s"), *type, UTF8_TO_TCHAR(o->name), *help, *possibleValues);
} else {
UE_LOG(LogFFMPEGMedia, Display, TEXT( "\t%s - %s: %s"), *type, UTF8_TO_TCHAR(o->name), *help);
}
}
void FFFMPEGMediaPlayer::dumpOptions(const AVClass *clazz) {
const AVOption *o = av_opt_next(&clazz, NULL);
while (o != NULL) {
if (o->type != AV_OPT_TYPE_CONST) {
print_option(clazz, o);
}
o = av_opt_next(clazz, o);
}
}
void FFFMPEGMediaPlayer::dumpFFMPEGInfo() {
UE_LOG(LogFFMPEGMedia, Display, TEXT("AVFormat configuration: %s"), UTF8_TO_TCHAR(avformat_configuration()));
if ( FormatContext ) {
if(FormatContext->iformat)
UE_LOG(LogFFMPEGMedia, Display, TEXT("Format Name: %s"), UTF8_TO_TCHAR(FormatContext->iformat->name));
FString sz_duration = TEXT(" Duration: ");
if (FormatContext->duration != AV_NOPTS_VALUE) {
int hours, mins, secs, us;
int64_t duration = FormatContext->duration + (FormatContext->duration <= INT64_MAX - 5000 ? 5000 : 0);
secs = duration / AV_TIME_BASE;
us = duration % AV_TIME_BASE;
mins = secs / 60;
secs %= 60;
hours = mins / 60;
mins %= 60;
sz_duration += FString::Printf(TEXT("%02d:%02d:%02d.%02d"), hours, mins, secs,(100 * us) / AV_TIME_BASE);
}
else {
sz_duration += TEXT("N/A");
}
if (FormatContext->start_time != AV_NOPTS_VALUE) {
int secs, us;
sz_duration += ", start: ";
secs = llabs(FormatContext->start_time / AV_TIME_BASE);
us = llabs(FormatContext->start_time % AV_TIME_BASE);
sz_duration += FString::Printf(TEXT("%s%d.%06d"),FormatContext->start_time >= 0 ? TEXT("") : TEXT("-"),secs,(int)av_rescale(us, 1000000, AV_TIME_BASE));
}
sz_duration += TEXT(", bitrate: ");
if (FormatContext->bit_rate)
{
int64_t br = FormatContext->bit_rate / 1000;
sz_duration += FString::Printf(TEXT("0x%08x%08x kb/s"), (uint32_t)(br >> 32),(uint32_t)(br & 0xFFFFFFFF));
}
else
sz_duration += TEXT("N/A");
sz_duration += TEXT("\n");
for (unsigned int i = 0; i < FormatContext->nb_chapters; i++) {
AVChapter *ch = FormatContext->chapters[i];
sz_duration += FString::Printf(TEXT(" Chapter %d: "), i);
sz_duration += FString::Printf(TEXT("start %f, "), ch->start * av_q2d(ch->time_base));
sz_duration += FString::Printf(TEXT("end %f\n"), ch->end * av_q2d(ch->time_base));
}
if (FormatContext->nb_programs) {
unsigned int total = 0;
for (unsigned int j = 0; j < FormatContext->nb_programs; j++) {
AVDictionaryEntry *name = av_dict_get(FormatContext->programs[j]->metadata,
"name", NULL, 0);
sz_duration += FString::Printf(TEXT(" Program %d %s\n"), FormatContext->programs[j]->id,
name ? name->value : "");
total += FormatContext->programs[j]->nb_stream_indexes;
}
if (total < FormatContext->nb_streams)
sz_duration += TEXT(" No Program\n");
}
UE_LOG(LogFFMPEGMedia, Display, TEXT("%s"), *sz_duration);
// UE_LOG(LogFFMPEGMedia, Display, TEXT("\n\nDefault format options"));
// dumpOptions(avformat_get_class());
//
// if (FormatContext->iformat && FormatContext->iformat->priv_class) {
// UE_LOG(LogFFMPEGMedia, Display, TEXT("\n\nFormat Options\n"));
// dumpOptions(FormatContext->iformat->priv_class);
// }
//
// UE_LOG(LogFFMPEGMedia, Display, TEXT("\n\nDefault codec options\n"));
// dumpOptions(avcodec_get_class());
//
// if ( FormatContext->video_codec && FormatContext->video_codec->priv_class ) {
// UE_LOG(LogFFMPEGMedia, Display, TEXT("\n\nVideo Codec\n"));
// dumpOptions( FormatContext->video_codec->priv_class);
// }
//
// if (FormatContext->audio_codec && FormatContext->audio_codec->priv_class) {
// UE_LOG(LogFFMPEGMedia, Display, TEXT("\n\nAudio Codec\n"));
// dumpOptions(FormatContext->audio_codec->priv_class);
// }
}
}

View File

@ -0,0 +1,129 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "FFMPEGMediaPrivate.h"
#include "Containers/UnrealString.h"
#include "Containers/Queue.h"
#include "IMediaCache.h"
#include "IMediaPlayer.h"
#include "IMediaView.h"
#include "Misc/Timespan.h"
class FFFMPEGMediaTracks;
class IMediaEventSink;
struct AVIOContext;
struct AVFormatContext;
struct AVClass;
/**
* Implements a media player using the Windows Media Foundation framework.
*/
class FFFMPEGMediaPlayer
: public IMediaPlayer
, protected IMediaCache
, protected IMediaView
{
public:
/**
* Create and initialize a new instance.
*
* @param InEventSink The object that receives media events from this player.
*/
FFFMPEGMediaPlayer(IMediaEventSink& InEventSink);
/** Virtual destructor. */
virtual ~FFFMPEGMediaPlayer();
public:
//~ IMediaPlayer interface
virtual void Close() override;
virtual IMediaCache& GetCache() override;
virtual IMediaControls& GetControls() override;
virtual FString GetInfo() const override;
virtual FName GetPlayerName() const;
virtual FGuid GetPlayerPluginGUID() const override;
virtual IMediaSamples& GetSamples() override;
virtual FString GetStats() const override;
virtual IMediaTracks& GetTracks() override;
virtual FString GetUrl() const override;
virtual IMediaView& GetView() override;
virtual bool Open(const FString& Url, const IMediaOptions* Options, const FMediaPlayerOptions* PlayerOptions) override;
virtual bool Open(const FString& Url, const IMediaOptions* Options) override;
virtual bool Open(const TSharedRef<FArchive, ESPMode::ThreadSafe>& Archive, const FString& OriginalUrl, const IMediaOptions* Options) override;
virtual void TickFetch(FTimespan DeltaTime, FTimespan Timecode) override;
virtual void TickInput(FTimespan DeltaTime, FTimespan Timecode) override;
protected:
/**
* Initialize the native AvPlayer instance.
*
* @param Archive The archive being used as a media source (optional).
* @param Url The media URL being opened.
* @param Precache Whether to precache media into RAM if InURL is a local file.
* @return true on success, false otherwise.
*/
bool InitializePlayer(const TSharedPtr<FArchive, ESPMode::ThreadSafe>& Archive, const FString& Url, bool Precache, const FMediaPlayerOptions* PlayerOptions);
private:
/** The media event handler. */
IMediaEventSink& EventSink;
/** The URL of the currently opened media. */
FString MediaUrl;
/** Tasks to be executed on the player thread. */
TQueue<TFunction<void()>> PlayerTasks;
/** Media streams collection. */
TSharedPtr<FFFMPEGMediaTracks, ESPMode::ThreadSafe> Tracks;
/** FFMPEG Callbacks */
/** Returns 1 when we would like to stop the application */
static int DecodeInterruptCallback(void *ctx);
/** This is called when it's reading an Archive instead of an url*/
static int ReadtStreamCallback(void* ptr, uint8_t* buf, int buf_size);
/** This is called when it's reading an Archive instead of an url*/
static int64_t SeekStreamCallback(void *opaque, int64_t offset, int whence);
/** FFMPEG Functions */
AVFormatContext* ReadContext(const TSharedPtr<FArchive, ESPMode::ThreadSafe>& Archive, const FString& Url, bool Precache);
static void dumpOptions(const AVClass *clazz);
void dumpFFMPEGInfo();
/** FFMPEG Structs */
AVFormatContext *FormatContext;
AVIOContext *IOContext;
bool stopped;
TSharedPtr<FArchive, ESPMode::ThreadSafe> CurrentArchive;
};

View File

@ -0,0 +1,162 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreTypes.h"
#include "Containers/Array.h"
#include "IMediaTextureSample.h"
#include "MediaObjectPool.h"
#include "MediaSampleQueue.h"
#include "Math/IntPoint.h"
#include "Misc/Timespan.h"
/**
* Texture sample generated by FFMPEGMedia player.
*/
class FFFMPEGMediaTextureSample
: public IMediaTextureSample
, public IMediaPoolable
{
public:
/** Default constructor. */
FFFMPEGMediaTextureSample()
: Dim(FIntPoint::ZeroValue)
, Duration(FTimespan::Zero())
, OutputDim(FIntPoint::ZeroValue)
, SampleFormat(EMediaTextureSampleFormat::Undefined)
, Stride(0)
, Time(FTimespan::Zero())
{ }
/** Virtual destructor. */
virtual ~FFFMPEGMediaTextureSample() { }
public:
/**
* Initialize the sample.
*
* @param InBuffer The sample's data buffer.
* @param InSize Size of the buffer.
* @param InDim The sample buffer's width and height (in pixels).
* @param InOutputDim The sample's output width and height (in pixels).
* @param InSampleFormat The sample format.
* @param InStride Number of bytes per pixel row.
* @param InTime The sample time (relative to presentation clock).
* @param InDuration The duration for which the sample is valid.
*/
bool Initialize(
const void* InBuffer,
uint32 InSize,
const FIntPoint& InDim,
uint32 InStride,
FTimespan InTime,
FTimespan InDuration)
{
if ((InBuffer == nullptr) || (InSize == 0) || (InStride == 0))
{
return false;
}
if ((InStride * InDim.Y) > InSize)
{
return false;
}
Buffer.Reset(InSize);
Buffer.Append((uint8*)InBuffer, InSize);
Duration = InDuration;
Dim = InDim;
SampleFormat = EMediaTextureSampleFormat::CharBGRA;
Stride = InStride;
Time = InTime;
return true;
}
public:
//~ IMediaTextureSample interface
virtual const void* GetBuffer() override
{
return Buffer.GetData();
}
virtual FIntPoint GetDim() const override
{
return Dim;
}
virtual FTimespan GetDuration() const override
{
return Duration;
}
virtual EMediaTextureSampleFormat GetFormat() const override
{
return SampleFormat;
}
virtual FIntPoint GetOutputDim() const override
{
return Dim;
}
virtual uint32 GetStride() const override
{
return Stride;
}
#if WITH_ENGINE
virtual FRHITexture* GetTexture() const override
{
return nullptr;
}
#endif //WITH_ENGINE
virtual FMediaTimeStamp GetTime() const override
{
return Time;
}
virtual bool IsCacheable() const override
{
return true;
}
virtual bool IsOutputSrgb() const override
{
return true;
}
private:
/** The sample's data buffer. */
TArray<uint8> Buffer;
/** Width and height of the texture sample. */
FIntPoint Dim;
/** Duration for which the sample is valid. */
FTimespan Duration;
/** Width and height of the output. */
FIntPoint OutputDim;
/** The sample format. */
EMediaTextureSampleFormat SampleFormat;
/** Number of bytes per pixel row. */
uint32 Stride;
/** Presentation for which the sample was generated. */
FMediaTimeStamp Time;
};
/** Implements a pool for WMF texture samples. */
class FFFMPEGMediaTextureSamplePool : public TMediaObjectPool<FFFMPEGMediaTextureSample> { };

View File

@ -0,0 +1,566 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "FFMPEGMediaSettings.h"
#include "FFMPEGMediaPrivate.h"
#include "FFMPEGFrameQueue.h"
#include "FFMPEGClock.h"
#include "CoreTypes.h"
#include "Containers/Array.h"
#include "Containers/UnrealString.h"
#include "Internationalization/Text.h"
#include "IMediaSamples.h"
#include "IMediaTracks.h"
#include "IMediaControls.h"
#include "Math/IntPoint.h"
#include "MediaSampleQueue.h"
#include "Templates/SharedPointer.h"
#include "MediaPlayerOptions.h"
#include "HAL/RunnableThread.h"
class FFFMPEGMediaAudioSamplePool;
class FFFMPEGMediaTextureSamplePool;
struct AVFormatContext;
struct AVCodec;
struct AVBufferRef;
struct AVCodecContext;
class FFMPEGDecoder;
/**
* Track collection for Windows Media Foundation based media players.
*/
class FFFMPEGMediaTracks
: public IMediaSamples
, public IMediaTracks
, public IMediaControls
{
/** Track format. */
struct FFormat
{
enum AVMediaType MediaType;
enum AVCodecID CodecID;
FString TypeName;
struct AudioFormat
{
uint32 FrameSize;
uint32 NumChannels;
uint32 SampleRate;
uint64_t ChannelLayout;
enum AVSampleFormat Format;
uint32 BytesPerSec;
uint32 HardwareSize;
}
Audio;
struct VideoFormat
{
int64_t BitRate;
float FrameRate;
FIntPoint OutputDim;
enum AVPixelFormat Format;
int LineSize[4];
}
Video;
};
/** Track information. */
struct FTrack
{
FText DisplayName;
FFormat Format;
FString Language;
FString Name;
bool Protected;
int StreamIndex;
};
public:
/** Default constructor. */
FFFMPEGMediaTracks();
/** Virtual destructor. */
virtual ~FFFMPEGMediaTracks();
public:
/**
* Append track statistics information to the given string.
*
* @param OutStats The string to append the statistics to.
*/
void AppendStats(FString &OutStats) const;
/**
* Clear the streams flags.
*
* @see GetFlags
*/
void ClearFlags();
/**
* Gets all deferred player events.
*
* @param OutEvents Will contain the events.
* @see GetCapabilities
*/
void GetEvents(TArray<EMediaEvent>& OutEvents);
/**
* Get the current flags.
*
* @param OutMediaSourceChanged Will indicate whether the media source changed.
* @param OutSelectionChanged Will indicate whether the track selection changed.
* @see ClearFlags
*/
void GetFlags(bool& OutMediaSourceChanged, bool& OutSelectionChanged) const;
/**
* Get the information string for the currently loaded media source.
*
* @return Info string.
* @see GetDuration, GetSamples
*/
const FString& GetInfo() const
{
return Info;
}
/**
* Initialize the track collection.
*
* @param AVFormatContext input format
* @param Url The media source URL.
* @see IsInitialized, Shutdown
*/
void Initialize(AVFormatContext *ic, const FString& Url, const FMediaPlayerOptions* PlayerOptions );
/**
* Reinitialize the track collection
*
* @see IsInitialized, Shutdown
*/
void ReInitialize();
/**
* Whether this object has been initialized.
*
* @return true if initialized, false otherwise.
* @see Initialize, Shutdown
*/
bool IsInitialized() const
{
//return (MediaSource != NULL);
return false;
}
/**
* Shut down the track collection.
*
* @see Initialize, IsInitialized
*/
void Shutdown();
/**
*
*
*/
void TickInput(FTimespan DeltaTime, FTimespan Timecode);
public:
//~ IMediaSamples interface
virtual bool FetchAudio(TRange<FTimespan> TimeRange, TSharedPtr<IMediaAudioSample, ESPMode::ThreadSafe>& OutSample) override;
virtual bool FetchCaption(TRange<FTimespan> TimeRange, TSharedPtr<IMediaOverlaySample, ESPMode::ThreadSafe>& OutSample) override;
virtual bool FetchMetadata(TRange<FTimespan> TimeRange, TSharedPtr<IMediaBinarySample, ESPMode::ThreadSafe>& OutSample) override;
virtual bool FetchVideo(TRange<FTimespan> TimeRange, TSharedPtr<IMediaTextureSample, ESPMode::ThreadSafe>& OutSample) override;
virtual void FlushSamples() override;
virtual bool PeekVideoSampleTime(FMediaTimeStamp& TimeStamp) override;
public:
//~ IMediaTracks interface
virtual bool GetAudioTrackFormat(int32 TrackIndex, int32 FormatIndex, FMediaAudioTrackFormat& OutFormat) const override;
virtual int32 GetNumTracks(EMediaTrackType TrackType) const override;
virtual int32 GetNumTrackFormats(EMediaTrackType TrackType, int32 TrackIndex) const override;
virtual int32 GetSelectedTrack(EMediaTrackType TrackType) const override;
virtual FText GetTrackDisplayName(EMediaTrackType TrackType, int32 TrackIndex) const override;
virtual int32 GetTrackFormat(EMediaTrackType TrackType, int32 TrackIndex) const override;
virtual FString GetTrackLanguage(EMediaTrackType TrackType, int32 TrackIndex) const override;
virtual FString GetTrackName(EMediaTrackType TrackType, int32 TrackIndex) const override;
virtual bool GetVideoTrackFormat(int32 TrackIndex, int32 FormatIndex, FMediaVideoTrackFormat& OutFormat) const override;
virtual bool SelectTrack(EMediaTrackType TrackType, int32 TrackIndex) override;
virtual bool SetTrackFormat(EMediaTrackType TrackType, int32 TrackIndex, int32 FormatIndex) override;
virtual bool SetVideoTrackFrameRate(int32 TrackIndex, int32 FormatIndex, float FrameRate) override;
public:
//~ IMediaControls interface
virtual bool CanControl(EMediaControl Control) const override;
virtual FTimespan GetDuration() const override;
virtual float GetRate() const override;
virtual EMediaState GetState() const override;
virtual EMediaStatus GetStatus() const override;
virtual TRangeSet<float> GetSupportedRates(EMediaRateThinning Thinning) const override;
virtual FTimespan GetTime() const override;
virtual bool IsLooping() const override;
virtual bool Seek(const FTimespan& Time) override;
virtual bool SetLooping(bool Looping) override;
virtual bool SetRate(float Rate) override;
/*
public:
static int cuvid_init(AVCodecContext *avctx);
#if PLATFORM_MAC
static int videotoolbox_init(AVCodecContext *s);
#endif*/
protected:
/**
* Add the specified stream to the track collection.
*
* @param StreamIndex The index of the stream to add.
* @param OutInfo Will contain appended debug information.
* @param IsVideoDevice Whether the stream belongs to a video capture device.
* @return true on success, false otherwise.
* @see AddTrackToTopology
*/
bool AddStreamToTracks(uint32 StreamIndex, bool IsVideoDevice, const FMediaPlayerTrackOptions& TrackOptions, FString& OutInfo);
/**
* Add the given track to the specified playback topology.
*
* @param Track The track to add.
* @param Topology The playback topology.
* @return true on success, false otherwise.
* @see AddStreamToTracks
*/
//bool AddTrackToTopology(const FTrack& Track, IMFTopology& Topology) const;
private:
/**
* Get the specified audio format.
*
* @param TrackIndex Index of the audio track that contains the format.
* @param FormatIndex Index of the format to return.
* @return Pointer to format, or nullptr if not found.
* @see GetVideoFormat
*/
const FFormat* GetAudioFormat(int32 TrackIndex, int32 FormatIndex) const;
/**
* Get the specified track information.
*
* @param TrackType The type of track.
* @param TrackIndex Index of the track to return.
* @return Pointer to track, or nullptr if not found.
*/
const FTrack* GetTrack(EMediaTrackType TrackType, int32 TrackIndex) const;
/**
* Get the specified video format.
*
* @param TrackIndex Index of the video track that contains the format.
* @param FormatIndex Index of the format to return.
* @return Pointer to format, or nullptr if not found.
* @see GetAudioFormat
*/
const FFormat* GetVideoFormat(int32 TrackIndex, int32 FormatIndex) const;
private:
/** Audio sample object pool. */
FFFMPEGMediaAudioSamplePool* AudioSamplePool;
/** Audio sample queue. */
TMediaSampleQueue<IMediaAudioSample> AudioSampleQueue;
/** The available audio tracks. */
TArray<FTrack> AudioTracks;
/** Overlay sample queue. */
TMediaSampleQueue<IMediaOverlaySample> CaptionSampleQueue;
/** The available caption tracks. */
TArray<FTrack> CaptionTracks;
/** Synchronizes write access to track arrays, selections & sinks. */
mutable FCriticalSection CriticalSection;
/** Media information string. */
FString Info;
/** The initial media url. */
FString SourceUrl;
/** The currently opened media. */
AVFormatContext* FormatContext;
/** Whether the media source has changed. */
bool MediaSourceChanged;
/** Metadata sample queue. */
TMediaSampleQueue<IMediaBinarySample> MetadataSampleQueue;
/** The available metadata tracks. */
TArray<FTrack> MetadataTracks;
/** The presentation descriptor of the currently opened media. */
//TComPtr<IMFPresentationDescriptor> PresentationDescriptor;
/** Index of the selected audio track. */
int32 SelectedAudioTrack;
/** Index of the selected caption track. */
int32 SelectedCaptionTrack;
/** Index of the selected binary track. */
int32 SelectedMetadataTrack;
/** Index of the selected video track. */
int32 SelectedVideoTrack;
/** Whether the track selection changed. */
bool SelectionChanged;
/** Video sample object pool. */
FFFMPEGMediaTextureSamplePool* VideoSamplePool;
/** Video sample queue. */
TMediaSampleQueue<IMediaTextureSample> VideoSampleQueue;
/** The available video tracks. */
TArray<FTrack> VideoTracks;
/** The current playback rate. */
float CurrentRate;
/** Media events to be forwarded to main thread. */
TQueue<EMediaEvent> DeferredEvents;
/** Media playback state. */
EMediaState CurrentState;
EMediaState LastState;
/** The current time of the playback. */
FTimespan CurrentTime;
/** The duration of the media. */
FTimespan Duration;
FTimespan TargetTime;
/** Should the video loop to the beginning at completion */
bool ShouldLoop;
bool bPrerolled;
/** FFMPEG methods */
/** Check if a codec have hardware acceleration options */
static bool isHwAccel(const AVCodec* codec);
/** Check if a codec have hardware acceleration options */
static TArray<const AVCodec*> FindDecoders(int codecId, bool hwaccell);
/** Find the better accelerated device type for the given codec*/
static enum AVHWDeviceType FindBetterDeviceType(const AVCodec* codec, int& lastSelection);
/** Callback for ffmpeg to return the right format when is hardware accelerated*/
static enum AVPixelFormat GetFormatCallback(AVCodecContext *s, const enum AVPixelFormat *pix_fmts);
/** Callback for ffmpeg to transfer the gpu data to the cpu when is harware accelerated*/
static int HWAccelRetrieveDataCallback(AVCodecContext *avctx, AVFrame *input);
/** Invoked to seek in the stream*/
void StreamSeek( int64_t pos, int64_t rel, int seek_by_bytes);
/** Check if the stream buffer has enought callbacks*/
int StreamHasEnoughPackets(AVStream *st, int stream_id, FFMPEGPacketQueue *queue);
/** Open the given stream using the stream_index*/
int StreamComponentOpen(int stream_index);
/** Close the given stream using the stream_index*/
void StreamComponentClose(int stream_index);
/** Returns the current synchronization type*/
ESynchronizationType getMasterSyncType();
/** Transfer the obtained ffmpeg texture to the IMediaTexture */
int UploadTexture(FFMPEGFrame* vp, AVFrame *frame, struct SwsContext **img_convert_ctx);
/** Waits for the audio to be in sync when the synchronization is not made through the audio clock */
int SynchronizeAudio( int nb_samples);
/** Decode a frame from the packet queue and extract the AVFrame*/
int GetVideoFrame(AVFrame *frame);
/** Function to run while is reading the file*/
int ReadThread();
/** Decode the audio frames from the packet queue*/
int AudioThread();
/** Decode the subtitle frames from the packet queue*/
int SubtitleThread();
/** Extract the picture queue */
int VideoThread();
/** Thread to convert the video frames*/
int DisplayThread();
/** Decode an audio frame and extract the current time and duration for each sample*/
int AudioDecodeFrame (FTimespan& Time, FTimespan& Duration);
/** Convert the audio frame to be played by the media player*/
void RenderAudio();
/** Thread to convert the audio frames */
int AudioRenderThread();
/** Refresh the media sample when is need it */
void VideoRefresh(double *remaining_time);
/** Starts the display thread*/
void StartDisplayThread();
/** Stops the display thread*/
void StopDisplayThread();
/** Starts the audio render thread*/
void StartAudioRenderThread();
/** Stops the audio render thread*/
void StopAudioRenderThread();
void VideoDisplay ();
void StepToNextFrame();
void StreamTogglePause();
double ComputeTargetDelay(double delay);
void UpdateVideoPts( double pts, int64_t pos, int serial);
void CheckExternalClockSpeed();
double GetMasterClock();
static int IsRealtime(AVFormatContext *s);
struct SwsContext *imgConvertCtx;
FRunnableThread* readThread;
FRunnableThread* audioThread;
FRunnableThread* videoThread;
FRunnableThread* subtitleThread;
FRunnableThread* displayThread;
FRunnableThread* audioRenderThread;
AVStream *audioStream;
AVStream *videoStream;
AVStream *subTitleStream;
AVCodecContext* video_ctx;
AVBufferRef* hw_device_ctx;
AVBufferRef* hw_frames_ctx;
FFMPEGFrameQueue pictq;
FFMPEGFrameQueue subpq;
FFMPEGFrameQueue sampq;
FFMPEGPacketQueue audioq;
FFMPEGPacketQueue videoq;
FFMPEGPacketQueue subtitleq;
FFMPEGClock audclk;
FFMPEGClock vidclk;
FFMPEGClock extclk;
struct SwrContext *swrContext;
CondWait continueReadCond;
TSharedPtr<FFMPEGDecoder> auddec;
TSharedPtr<FFMPEGDecoder> viddec;
TSharedPtr<FFMPEGDecoder> subdec;
bool aborted;
bool displayRunning;
bool audioRunning;
int eof;
bool step;
//Seek options
bool seekReq;
int64_t seekPos;
int64_t seekRel;
int seekFlags;
bool queueAttachmentsReq;
int readPauseReturn;
int videoStreamIdx;
int audioStreamIdx;
int subtitleStreamIdx;
bool forceRefresh;
int frameDropsLate;
int frameDropsEarly;
double frameTimer;
double maxFrameDuration;
bool realtime;
TArray<uint8> dataBuffer;
ESynchronizationType sychronizationType;
FFormat::AudioFormat srcAudio;
FFormat::AudioFormat targetAudio;
uint8_t *audioBuf;
uint8_t *audioBuf1;
unsigned int audioBufSize; /* in bytes */
unsigned int audioBuf1Size;
int audioClockSerial;
double audioClock;
int64_t audioCallbackTime;
double audioDiffAvgCoef;
double audioDiffThreshold;
int audioDiffAvgCount;
double audioDiffCum; /* used for AV difference average computation */
int totalStreams;
int currentStreams;
std::function<int(AVCodecContext *s, AVFrame *frame)> hwaccel_retrieve_data;
enum AVPixelFormat hwAccelPixFmt;
enum AVHWDeviceType hwAccelDeviceType;
};

View File

@ -0,0 +1,36 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Templates/SharedPointer.h"
#include "Modules/ModuleInterface.h"
class IMediaEventSink;
class IMediaPlayer;
/**
* Interface for the WmfMedia module.
*/
class IFFMPEGMediaModule
: public IModuleInterface
{
public:
/**
* Creates a Windows Media Foundation based media player.
*
* @param EventSink The object that receives media events from the player.
* @return A new media player, or nullptr if a player couldn't be created.
*/
virtual TSharedPtr<IMediaPlayer, ESPMode::ThreadSafe> CreatePlayer(IMediaEventSink& EventSink) = 0;
virtual TArray<FString> GetSupportedFileExtensions() = 0;
virtual TArray<FString> GetSupportedUriSchemes() = 0;
public:
/** Virtual destructor. */
virtual ~IFFMPEGMediaModule() { }
};

View File

@ -0,0 +1,55 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
namespace UnrealBuildTool.Rules
{
public class FFMPEGMediaFactory : ModuleRules
{
public FFMPEGMediaFactory(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
ShadowVariableWarningLevel = WarningLevel.Error;
OptimizeCode = CodeOptimization.Never;
DynamicallyLoadedModuleNames.AddRange(
new string[] {
"Media",
});
PrivateDependencyModuleNames.AddRange(
new string[] {
"Core",
"CoreUObject",
"MediaAssets",
});
PrivateIncludePathModuleNames.AddRange(
new string[] {
"Media",
"FFMPEGMedia",
});
PrivateIncludePaths.AddRange(
new string[] {
"FFMPEGMediaFactory/Private",
});
PublicDependencyModuleNames.AddRange(
new string[] {
"Core",
"CoreUObject",
});
if (Target.Type == TargetType.Editor)
{
DynamicallyLoadedModuleNames.Add("Settings");
PrivateIncludePathModuleNames.Add("Settings");
}
if (
(Target.Platform == UnrealTargetPlatform.Win64))
{
DynamicallyLoadedModuleNames.Add("FFMPEGMedia");
}
}
}
}

View File

@ -0,0 +1,17 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "FFMPEGMediaSettings.h"
UFFMPEGMediaSettings::UFFMPEGMediaSettings()
: UseInfiniteBuffer (false)
, AllowFrameDrop(true)
, UseHardwareAcceleratedCodecs (true)
, DisableAudio (false)
, ZeroLatencyStreaming(false)
, RtspTransport(ERTSPTransport::Default)
, SpeedUpTricks (false)
, AudioThreads(0)
, VideoThreads(0)
, SyncType (ESynchronizationType::AudioMaster)
{ }

View File

@ -0,0 +1,225 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "FFMPEGMediaFactoryPrivate.h"
#include "Containers/Array.h"
#include "Containers/UnrealString.h"
#include "IMediaModule.h"
#include "IMediaOptions.h"
#include "IMediaPlayerFactory.h"
#include "Internationalization/Internationalization.h"
#include "Misc/Paths.h"
#include "Modules/ModuleInterface.h"
#include "Modules/ModuleManager.h"
#include "UObject/NameTypes.h"
#if PLATFORM_WINDOWS
#include "Windows/WindowsHWrapper.h"
#endif
#if WITH_EDITOR
#include "ISettingsModule.h"
#include "Templates/SharedPointer.h"
#include "UObject/Class.h"
#include "UObject/WeakObjectPtr.h"
#include "FFMPEGMediaSettings.h"
#endif
#include "../../FFMPEGMedia/Public/IFFMPEGMediaModule.h"
DEFINE_LOG_CATEGORY(LogFFMPEGMediaFactory);
#define LOCTEXT_NAMESPACE "FMPEGMediaFactoryModule"
/**
* Implements the WmfMediaFactory module.
*/
class FFFMPEGMediaFactoryModule
: public IMediaPlayerFactory
, public IModuleInterface
{
public:
/** Default constructor. */
FFFMPEGMediaFactoryModule() { }
public:
//~ IMediaPlayerFactory interface
virtual bool CanPlayUrl(const FString& Url, const IMediaOptions* Options, TArray<FText>* OutWarnings, TArray<FText>* OutErrors) const override
{
FString Scheme;
FString Location;
// check scheme
if (!Url.Split(TEXT("://"), &Scheme, &Location, ESearchCase::CaseSensitive))
{
if (OutErrors != nullptr)
{
OutErrors->Add(LOCTEXT("NoSchemeFound", "No URI scheme found"));
}
return false;
}
if (!SupportedUriSchemes.Contains(Scheme))
{
if (OutErrors != nullptr)
{
OutErrors->Add(FText::Format(LOCTEXT("SchemeNotSupported", "The URI scheme '{0}' is not supported"), FText::FromString(Scheme)));
}
return false;
}
// check file extension
if (Scheme == TEXT("file"))
{
const FString Extension = FPaths::GetExtension(Location, false);
if (!SupportedFileExtensions.Contains(Extension))
{
if (OutErrors != nullptr)
{
OutErrors->Add(FText::Format(LOCTEXT("ExtensionNotSupported", "The file extension '{0}' is not supported"), FText::FromString(Extension)));
}
return false;
}
}
// check options
if ((OutWarnings != nullptr) && (Options != nullptr))
{
if (Options->GetMediaOption("PrecacheFile", false) && (Scheme != TEXT("file")))
{
OutWarnings->Add(LOCTEXT("PrecachingNotSupported", "Precaching is supported for local files only"));
}
}
return true;
}
virtual FGuid GetPlayerPluginGUID() const override
{
// {938BEEB4-2E88-450E-9C1C-6109456279B3}
static FGuid PlayerPluginGUID(0x938beeb4, 0x2e88450e, 0x9c1c6109, 0x456279b3);
return PlayerPluginGUID;
}
virtual TSharedPtr<IMediaPlayer, ESPMode::ThreadSafe> CreatePlayer(IMediaEventSink& EventSink) override
{
auto FFMPEGMediaModule = FModuleManager::LoadModulePtr<IFFMPEGMediaModule>("FFMPEGMedia");
return (FFMPEGMediaModule != nullptr) ? FFMPEGMediaModule->CreatePlayer(EventSink) : nullptr;
}
virtual FText GetDisplayName() const override
{
return LOCTEXT("MediaPlayerDisplayName", "FFMPEG");
}
virtual FName GetPlayerName() const override
{
static FName PlayerName(TEXT("FFMPEGMedia"));
return PlayerName;
}
virtual const TArray<FString>& GetSupportedPlatforms() const override
{
return SupportedPlatforms;
}
virtual bool SupportsFeature(EMediaFeature Feature) const override
{
return ((Feature == EMediaFeature::AudioSamples) ||
(Feature == EMediaFeature::AudioTracks) ||
(Feature == EMediaFeature::CaptionTracks) ||
(Feature == EMediaFeature::MetadataTracks) ||
(Feature == EMediaFeature::OverlaySamples) ||
(Feature == EMediaFeature::SubtitleTracks) ||
(Feature == EMediaFeature::VideoSamples) ||
(Feature == EMediaFeature::VideoTracks));
}
public:
//~ IModuleInterface interface
virtual void StartupModule() override
{
auto FFMPEGMediaModule = FModuleManager::LoadModulePtr<IFFMPEGMediaModule>("FFMPEGMedia");
SupportedFileExtensions.Append(FFMPEGMediaModule->GetSupportedFileExtensions());
SupportedUriSchemes.Append(FFMPEGMediaModule->GetSupportedUriSchemes() );
// supported platforms
SupportedPlatforms.Add(TEXT("Windows"));
SupportedPlatforms.Add(TEXT("Mac"));
SupportedPlatforms.Add(TEXT("Android"));
#if WITH_EDITOR
// register settings
ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings");
if (SettingsModule != nullptr)
{
SettingsModule->RegisterSettings("Project", "Plugins", "FFMPEGMedia",
LOCTEXT("FFMPEGMediaSettingsName", "FFMPEG Media"),
LOCTEXT("FFMPEGMediaSettingsDescription", "Configure the FFMPEG Media plug-in."),
GetMutableDefault<UFFMPEGMediaSettings>()
);
}
#endif //WITH_EDITOR
// register player factory
auto MediaModule = FModuleManager::LoadModulePtr<IMediaModule>("Media");
if (MediaModule != nullptr)
{
MediaModule->RegisterPlayerFactory(*this);
}
}
virtual void ShutdownModule() override
{
// unregister player factory
auto MediaModule = FModuleManager::GetModulePtr<IMediaModule>("Media");
if (MediaModule != nullptr)
{
MediaModule->UnregisterPlayerFactory(*this);
}
#if WITH_EDITOR
// unregister settings
ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings");
if (SettingsModule != nullptr)
{
SettingsModule->UnregisterSettings("Project", "Plugins", "FFMPEGMedia");
}
#endif //WITH_EDITOR
}
private:
/** List of supported media file types. */
TArray<FString> SupportedFileExtensions;
/** List of platforms that the media player support. */
TArray<FString> SupportedPlatforms;
/** List of supported URI schemes. */
TArray<FString> SupportedUriSchemes;
};
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FFFMPEGMediaFactoryModule, FFMPEGMediaFactory);

View File

@ -0,0 +1,10 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Logging/LogMacros.h"
#include "../../FFMPEGMediaFactory/Public/FFMPEGMediaSettings.h"
/** Log category for the WmfMediaFactory module. */
DECLARE_LOG_CATEGORY_EXTERN(LogFFMPEGMediaFactory, Log, All);

View File

@ -0,0 +1,79 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "UObject/Object.h"
#include "UObject/ObjectMacros.h"
#include "FFMPEGMediaSettings.generated.h"
UENUM()
enum class ESynchronizationType : uint8 {
AudioMaster = 0,
VideoMaster,
ExternalClock
};
UENUM()
enum class ERTSPTransport : uint8 {
Default = 0,
Udp,
UdpMulticast,
Tcp,
Http,
Https
};
/**
* Settings for the WmfMedia plug-in.
*/
UCLASS(config=Engine)
class FFMPEGMEDIAFACTORY_API UFFMPEGMediaSettings
: public UObject
{
GENERATED_BODY()
public:
/** Default constructor. */
UFFMPEGMediaSettings();
public:
UPROPERTY(config, EditAnywhere, Category=Media)
bool UseInfiniteBuffer;
UPROPERTY(config, EditAnywhere, Category = Media)
bool AllowFrameDrop;
UPROPERTY(config, EditAnywhere, Category = Media)
bool UseHardwareAcceleratedCodecs;
UPROPERTY(config, EditAnywhere, Category = Media)
bool DisableAudio;
UPROPERTY(config, EditAnywhere, Category=Media)
bool ZeroLatencyStreaming;
UPROPERTY(config, EditAnywhere, Category = Media)
ERTSPTransport RtspTransport;
//Allow non spec compliant speedup tricks.
UPROPERTY(config, EditAnywhere, Category = Media)
bool SpeedUpTricks;
UPROPERTY(config, EditAnywhere, Category = Media, meta = (UIMin=0, UIMax = 16))
int AudioThreads;
UPROPERTY(config, EditAnywhere, Category = Media, meta = (UIMin=0, UIMax = 16))
int VideoThreads;
UPROPERTY(config, EditAnywhere, Category = Media)
ESynchronizationType SyncType;
};

View File

@ -0,0 +1,10 @@
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_FFMPEG_INCLUDE_WIN_INTTYPES_H_
#define THIRD_PARTY_FFMPEG_INCLUDE_WIN_INTTYPES_H_
#include "stdint.h"
#endif // THIRD_PARTY_FFMPEG_INCLUDE_WIN_INTTYPES_H_

View File

@ -0,0 +1,52 @@
/*
* a64 video encoder - c64 colors in rgb (Pepto)
* Copyright (c) 2009 Tobias Bindhammer
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* a64 video encoder - c64 colors in rgb
*/
#ifndef AVCODEC_A64COLORS_H
#define AVCODEC_A64COLORS_H
#include <stdint.h>
/* c64 palette in RGB */
static const uint8_t a64_palette[16][3] = {
{0x00, 0x00, 0x00},
{0xff, 0xff, 0xff},
{0x68, 0x37, 0x2b},
{0x70, 0xa4, 0xb2},
{0x6f, 0x3d, 0x86},
{0x58, 0x8d, 0x43},
{0x35, 0x28, 0x79},
{0xb8, 0xc7, 0x6f},
{0x6f, 0x4f, 0x25},
{0x43, 0x39, 0x00},
{0x9a, 0x67, 0x59},
{0x44, 0x44, 0x44},
{0x6c, 0x6c, 0x6c},
{0x9a, 0xd2, 0x84},
{0x6c, 0x5e, 0xb5},
{0x95, 0x95, 0x95},
};
#endif /* AVCODEC_A64COLORS_H */

View File

@ -0,0 +1,150 @@
/*
* a64 video encoder - tables used by a64 encoders
* Copyright (c) 2009 Tobias Bindhammer
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* a64 video encoder - tables used by a64 encoders
*/
#ifndef AVCODEC_A64TABLES_H
#define AVCODEC_A64TABLES_H
#include <stdint.h>
/**
* dither patterns used vor rendering the multicolor charset
*/
static const uint8_t multi_dither_patterns[9][4][4] = {
{
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
},
{
{1, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 0}
},
{
{1, 0, 0, 0},
{0, 0, 1, 0},
{0, 1, 0, 0},
{0, 0, 0, 1}
},
{
{1, 0, 0, 0},
{0, 1, 0, 1},
{0, 0, 1, 0},
{0, 1, 0, 1}
},
{
{1, 0, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 0},
{0, 1, 0, 1}
},
{
{1, 1, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 1},
{0, 1, 0, 1}
},
{
{0, 1, 1, 1},
{1, 1, 0, 1},
{1, 0, 1, 1},
{1, 1, 1, 0}
},
{
{0, 1, 1, 1},
{1, 1, 1, 1},
{1, 1, 0, 1},
{1, 1, 1, 1}
},
{
{1, 1, 1, 1},
{1, 1, 1, 1},
{1, 1, 1, 1},
{1, 1, 1, 1}
},
};
static const uint8_t interlaced_dither_patterns[9][8][4] = {
{
{0, 0, 0, 0}, {0, 0, 0, 0},
{0, 0, 0, 0}, {0, 0, 0, 0},
{0, 0, 0, 0}, {0, 0, 0, 0},
{0, 0, 0, 0}, {0, 0, 0, 0},
},
{
{1, 0, 1, 0}, {0, 0, 0, 0},
{0, 0, 0, 0}, {0, 0, 0, 0},
{1, 0, 1, 0}, {0, 0, 0, 0},
{0, 0, 0, 0}, {0, 0, 0, 0},
},
{
{1, 0, 1, 0}, {0, 0, 0, 0},
{0, 0, 0, 0}, {0, 1, 0, 1},
{1, 0, 1, 0}, {0, 0, 0, 0},
{0, 0, 0, 0}, {0, 1, 0, 1},
},
{
{1, 0, 1, 0}, {0, 1, 0, 1},
{0, 1, 0, 1}, {0, 0, 0, 0},
{1, 0, 1, 0}, {0, 1, 0, 1},
{0, 1, 0, 1}, {0, 0, 0, 0},
},
{
{1, 0, 1, 0}, {0, 1, 0, 1},
{0, 1, 0, 1}, {1, 0, 1, 0},
{1, 0, 1, 0}, {0, 1, 0, 1},
{0, 1, 0, 1}, {1, 0, 1, 0},
},
{
{1, 0, 1, 0}, {0, 1, 0, 1},
{1, 1, 1, 1}, {1, 0, 1, 0},
{1, 0, 1, 0}, {0, 1, 0, 1},
{1, 1, 1, 1}, {1, 0, 1, 0},
},
{
{1, 0, 1, 0}, {1, 1, 1, 1},
{1, 1, 1, 1}, {0, 1, 0, 1},
{1, 0, 1, 0}, {1, 1, 1, 1},
{1, 1, 1, 1}, {0, 1, 0, 1},
},
{
{1, 1, 1, 1}, {1, 1, 1, 1},
{1, 1, 1, 1}, {0, 1, 0, 1},
{1, 1, 1, 1}, {1, 1, 1, 1},
{1, 1, 1, 1}, {0, 1, 0, 1},
},
{
{1, 1, 1, 1}, {1, 1, 1, 1},
{1, 1, 1, 1}, {1, 1, 1, 1},
{1, 1, 1, 1}, {1, 1, 1, 1},
{1, 1, 1, 1}, {1, 1, 1, 1},
}
};
#endif /* AVCODEC_A64TABLES_H */

View File

@ -0,0 +1,377 @@
/*
* AAC definitions and structures
* Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
* Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC definitions and structures
* @author Oded Shimon ( ods15 ods15 dyndns org )
* @author Maxim Gavrilov ( maxim.gavrilov gmail com )
*/
#ifndef AVCODEC_AAC_H
#define AVCODEC_AAC_H
#include "aac_defines.h"
#include "libavutil/float_dsp.h"
#include "libavutil/fixed_dsp.h"
#include "avcodec.h"
#if !USE_FIXED
#include "mdct15.h"
#endif
#include "fft.h"
#include "mpeg4audio.h"
#include "sbr.h"
#include <stdint.h>
#define MAX_CHANNELS 64
#define MAX_ELEM_ID 16
#define TNS_MAX_ORDER 20
#define MAX_LTP_LONG_SFB 40
#define CLIP_AVOIDANCE_FACTOR 0.95f
enum RawDataBlockType {
TYPE_SCE,
TYPE_CPE,
TYPE_CCE,
TYPE_LFE,
TYPE_DSE,
TYPE_PCE,
TYPE_FIL,
TYPE_END,
};
enum ExtensionPayloadID {
EXT_FILL,
EXT_FILL_DATA,
EXT_DATA_ELEMENT,
EXT_DYNAMIC_RANGE = 0xb,
EXT_SBR_DATA = 0xd,
EXT_SBR_DATA_CRC = 0xe,
};
enum WindowSequence {
ONLY_LONG_SEQUENCE,
LONG_START_SEQUENCE,
EIGHT_SHORT_SEQUENCE,
LONG_STOP_SEQUENCE,
};
enum BandType {
ZERO_BT = 0, ///< Scalefactors and spectral data are all zero.
FIRST_PAIR_BT = 5, ///< This and later band types encode two values (rather than four) with one code word.
ESC_BT = 11, ///< Spectral data are coded with an escape sequence.
RESERVED_BT = 12, ///< Band types following are encoded differently from others.
NOISE_BT = 13, ///< Spectral data are scaled white noise not coded in the bitstream.
INTENSITY_BT2 = 14, ///< Scalefactor data are intensity stereo positions (out of phase).
INTENSITY_BT = 15, ///< Scalefactor data are intensity stereo positions (in phase).
};
#define IS_CODEBOOK_UNSIGNED(x) (((x) - 1) & 10)
enum ChannelPosition {
AAC_CHANNEL_OFF = 0,
AAC_CHANNEL_FRONT = 1,
AAC_CHANNEL_SIDE = 2,
AAC_CHANNEL_BACK = 3,
AAC_CHANNEL_LFE = 4,
AAC_CHANNEL_CC = 5,
};
/**
* The point during decoding at which channel coupling is applied.
*/
enum CouplingPoint {
BEFORE_TNS,
BETWEEN_TNS_AND_IMDCT,
AFTER_IMDCT = 3,
};
/**
* Output configuration status
*/
enum OCStatus {
OC_NONE, ///< Output unconfigured
OC_TRIAL_PCE, ///< Output configuration under trial specified by an inband PCE
OC_TRIAL_FRAME, ///< Output configuration under trial specified by a frame header
OC_GLOBAL_HDR, ///< Output configuration set in a global header but not yet locked
OC_LOCKED, ///< Output configuration locked in place
};
typedef struct OutputConfiguration {
MPEG4AudioConfig m4ac;
uint8_t layout_map[MAX_ELEM_ID*4][3];
int layout_map_tags;
int channels;
uint64_t channel_layout;
enum OCStatus status;
} OutputConfiguration;
/**
* Predictor State
*/
typedef struct PredictorState {
AAC_FLOAT cor0;
AAC_FLOAT cor1;
AAC_FLOAT var0;
AAC_FLOAT var1;
AAC_FLOAT r0;
AAC_FLOAT r1;
AAC_FLOAT k1;
AAC_FLOAT x_est;
} PredictorState;
#define MAX_PREDICTORS 672
#define SCALE_DIV_512 36 ///< scalefactor difference that corresponds to scale difference in 512 times
#define SCALE_ONE_POS 140 ///< scalefactor index that corresponds to scale=1.0
#define SCALE_MAX_POS 255 ///< scalefactor index maximum value
#define SCALE_MAX_DIFF 60 ///< maximum scalefactor difference allowed by standard
#define SCALE_DIFF_ZERO 60 ///< codebook index corresponding to zero scalefactor indices difference
#define POW_SF2_ZERO 200 ///< ff_aac_pow2sf_tab index corresponding to pow(2, 0);
#define NOISE_PRE 256 ///< preamble for NOISE_BT, put in bitstream with the first noise band
#define NOISE_PRE_BITS 9 ///< length of preamble
#define NOISE_OFFSET 90 ///< subtracted from global gain, used as offset for the preamble
/**
* Long Term Prediction
*/
typedef struct LongTermPrediction {
int8_t present;
int16_t lag;
int coef_idx;
INTFLOAT coef;
int8_t used[MAX_LTP_LONG_SFB];
} LongTermPrediction;
/**
* Individual Channel Stream
*/
typedef struct IndividualChannelStream {
uint8_t max_sfb; ///< number of scalefactor bands per group
enum WindowSequence window_sequence[2];
uint8_t use_kb_window[2]; ///< If set, use Kaiser-Bessel window, otherwise use a sine window.
int num_window_groups;
uint8_t group_len[8];
LongTermPrediction ltp;
const uint16_t *swb_offset; ///< table of offsets to the lowest spectral coefficient of a scalefactor band, sfb, for a particular window
const uint8_t *swb_sizes; ///< table of scalefactor band sizes for a particular window
int num_swb; ///< number of scalefactor window bands
int num_windows;
int tns_max_bands;
int predictor_present;
int predictor_initialized;
int predictor_reset_group;
int predictor_reset_count[31]; ///< used by encoder to count prediction resets
uint8_t prediction_used[41];
uint8_t window_clipping[8]; ///< set if a certain window is near clipping
float clip_avoidance_factor; ///< set if any window is near clipping to the necessary atennuation factor to avoid it
} IndividualChannelStream;
/**
* Temporal Noise Shaping
*/
typedef struct TemporalNoiseShaping {
int present;
int n_filt[8];
int length[8][4];
int direction[8][4];
int order[8][4];
int coef_idx[8][4][TNS_MAX_ORDER];
INTFLOAT coef[8][4][TNS_MAX_ORDER];
} TemporalNoiseShaping;
/**
* Dynamic Range Control - decoded from the bitstream but not processed further.
*/
typedef struct DynamicRangeControl {
int pce_instance_tag; ///< Indicates with which program the DRC info is associated.
int dyn_rng_sgn[17]; ///< DRC sign information; 0 - positive, 1 - negative
int dyn_rng_ctl[17]; ///< DRC magnitude information
int exclude_mask[MAX_CHANNELS]; ///< Channels to be excluded from DRC processing.
int band_incr; ///< Number of DRC bands greater than 1 having DRC info.
int interpolation_scheme; ///< Indicates the interpolation scheme used in the SBR QMF domain.
int band_top[17]; ///< Indicates the top of the i-th DRC band in units of 4 spectral lines.
int prog_ref_level; /**< A reference level for the long-term program audio level for all
* channels combined.
*/
} DynamicRangeControl;
typedef struct Pulse {
int num_pulse;
int start;
int pos[4];
int amp[4];
} Pulse;
/**
* coupling parameters
*/
typedef struct ChannelCoupling {
enum CouplingPoint coupling_point; ///< The point during decoding at which coupling is applied.
int num_coupled; ///< number of target elements
enum RawDataBlockType type[8]; ///< Type of channel element to be coupled - SCE or CPE.
int id_select[8]; ///< element id
int ch_select[8]; /**< [0] shared list of gains; [1] list of gains for right channel;
* [2] list of gains for left channel; [3] lists of gains for both channels
*/
INTFLOAT gain[16][120];
} ChannelCoupling;
/**
* Single Channel Element - used for both SCE and LFE elements.
*/
typedef struct SingleChannelElement {
IndividualChannelStream ics;
TemporalNoiseShaping tns;
Pulse pulse;
enum BandType band_type[128]; ///< band types
enum BandType band_alt[128]; ///< alternative band type (used by encoder)
int band_type_run_end[120]; ///< band type run end points
INTFLOAT sf[120]; ///< scalefactors
int sf_idx[128]; ///< scalefactor indices (used by encoder)
uint8_t zeroes[128]; ///< band is not coded (used by encoder)
uint8_t can_pns[128]; ///< band is allowed to PNS (informative)
float is_ener[128]; ///< Intensity stereo pos (used by encoder)
float pns_ener[128]; ///< Noise energy values (used by encoder)
DECLARE_ALIGNED(32, INTFLOAT, pcoeffs)[1024]; ///< coefficients for IMDCT, pristine
DECLARE_ALIGNED(32, INTFLOAT, coeffs)[1024]; ///< coefficients for IMDCT, maybe processed
DECLARE_ALIGNED(32, INTFLOAT, saved)[1536]; ///< overlap
DECLARE_ALIGNED(32, INTFLOAT, ret_buf)[2048]; ///< PCM output buffer
DECLARE_ALIGNED(16, INTFLOAT, ltp_state)[3072]; ///< time signal for LTP
DECLARE_ALIGNED(32, AAC_FLOAT, lcoeffs)[1024]; ///< MDCT of LTP coefficients (used by encoder)
DECLARE_ALIGNED(32, AAC_FLOAT, prcoeffs)[1024]; ///< Main prediction coefs (used by encoder)
PredictorState predictor_state[MAX_PREDICTORS];
INTFLOAT *ret; ///< PCM output
} SingleChannelElement;
/**
* channel element - generic struct for SCE/CPE/CCE/LFE
*/
typedef struct ChannelElement {
int present;
// CPE specific
int common_window; ///< Set if channels share a common 'IndividualChannelStream' in bitstream.
int ms_mode; ///< Signals mid/side stereo flags coding mode (used by encoder)
uint8_t is_mode; ///< Set if any bands have been encoded using intensity stereo (used by encoder)
uint8_t ms_mask[128]; ///< Set if mid/side stereo is used for each scalefactor window band
uint8_t is_mask[128]; ///< Set if intensity stereo is used (used by encoder)
// shared
SingleChannelElement ch[2];
// CCE specific
ChannelCoupling coup;
SpectralBandReplication sbr;
} ChannelElement;
/**
* main AAC context
*/
struct AACContext {
AVClass *class;
AVCodecContext *avctx;
AVFrame *frame;
int is_saved; ///< Set if elements have stored overlap from previous frame.
DynamicRangeControl che_drc;
/**
* @name Channel element related data
* @{
*/
ChannelElement *che[4][MAX_ELEM_ID];
ChannelElement *tag_che_map[4][MAX_ELEM_ID];
int tags_mapped;
int warned_remapping_once;
/** @} */
/**
* @name temporary aligned temporary buffers
* (We do not want to have these on the stack.)
* @{
*/
DECLARE_ALIGNED(32, INTFLOAT, buf_mdct)[1024];
/** @} */
/**
* @name Computed / set up during initialization
* @{
*/
FFTContext mdct;
FFTContext mdct_small;
FFTContext mdct_ld;
FFTContext mdct_ltp;
#if USE_FIXED
AVFixedDSPContext *fdsp;
#else
MDCT15Context *mdct120;
MDCT15Context *mdct480;
MDCT15Context *mdct960;
AVFloatDSPContext *fdsp;
#endif /* USE_FIXED */
int random_state;
/** @} */
/**
* @name Members used for output
* @{
*/
SingleChannelElement *output_element[MAX_CHANNELS]; ///< Points to each SingleChannelElement
/** @} */
/**
* @name Japanese DTV specific extension
* @{
*/
int force_dmono_mode;///< 0->not dmono, 1->use first channel, 2->use second channel
int dmono_mode; ///< 0->not dmono, 1->use first channel, 2->use second channel
/** @} */
DECLARE_ALIGNED(32, INTFLOAT, temp)[128];
OutputConfiguration oc[2];
int warned_num_aac_frames;
int warned_960_sbr;
int warned_gain_control;
/* aacdec functions pointers */
void (*imdct_and_windowing)(AACContext *ac, SingleChannelElement *sce);
void (*apply_ltp)(AACContext *ac, SingleChannelElement *sce);
void (*apply_tns)(INTFLOAT coef[1024], TemporalNoiseShaping *tns,
IndividualChannelStream *ics, int decode);
void (*windowing_and_mdct_ltp)(AACContext *ac, INTFLOAT *out,
INTFLOAT *in, IndividualChannelStream *ics);
void (*update_ltp)(AACContext *ac, SingleChannelElement *sce);
void (*vector_pow43)(int *coefs, int len);
void (*subband_scale)(int *dst, int *src, int scale, int offset, int len);
};
void ff_aacdec_init_mips(AACContext *c);
#endif /* AVCODEC_AAC_H */

View File

@ -0,0 +1,66 @@
/*
* Common AAC and AC-3 parser prototypes
* Copyright (c) 2003 Fabrice Bellard
* Copyright (c) 2003 Michael Niedermayer
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AAC_AC3_PARSER_H
#define AVCODEC_AAC_AC3_PARSER_H
#include <stdint.h>
#include "avcodec.h"
#include "parser.h"
typedef enum {
AAC_AC3_PARSE_ERROR_SYNC = -0x1030c0a,
AAC_AC3_PARSE_ERROR_BSID = -0x2030c0a,
AAC_AC3_PARSE_ERROR_SAMPLE_RATE = -0x3030c0a,
AAC_AC3_PARSE_ERROR_FRAME_SIZE = -0x4030c0a,
AAC_AC3_PARSE_ERROR_FRAME_TYPE = -0x5030c0a,
AAC_AC3_PARSE_ERROR_CRC = -0x6030c0a,
AAC_AC3_PARSE_ERROR_CHANNEL_CFG = -0x7030c0a,
} AACAC3ParseError;
typedef struct AACAC3ParseContext {
ParseContext pc;
int frame_size;
int header_size;
int (*sync)(uint64_t state, struct AACAC3ParseContext *hdr_info,
int *need_next_header, int *new_frame_start);
int channels;
int sample_rate;
int bit_rate;
int samples;
uint64_t channel_layout;
int service_type;
int remaining_size;
uint64_t state;
int need_next_header;
enum AVCodecID codec_id;
} AACAC3ParseContext;
int ff_aac_ac3_parse(AVCodecParserContext *s1,
AVCodecContext *avctx,
const uint8_t **poutbuf, int *poutbuf_size,
const uint8_t *buf, int buf_size);
#endif /* AVCODEC_AAC_AC3_PARSER_H */

View File

@ -0,0 +1,116 @@
/*
* AAC defines
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AAC_DEFINES_H
#define AVCODEC_AAC_DEFINES_H
#ifndef USE_FIXED
#define USE_FIXED 0
#endif
#if USE_FIXED
#include "libavutil/softfloat.h"
#define FFT_FLOAT 0
#define FFT_FIXED_32 1
#define AAC_RENAME(x) x ## _fixed
#define AAC_RENAME_32(x) x ## _fixed_32
typedef int INTFLOAT;
typedef unsigned UINTFLOAT; ///< Equivalent to INTFLOAT, Used as temporal cast to avoid undefined sign overflow operations.
typedef int64_t INT64FLOAT;
typedef int16_t SHORTFLOAT;
typedef SoftFloat AAC_FLOAT;
typedef int AAC_SIGNE;
#define FIXR(a) ((int)((a) * 1 + 0.5))
#define FIXR10(a) ((int)((a) * 1024.0 + 0.5))
#define Q23(a) (int)((a) * 8388608.0 + 0.5)
#define Q30(x) (int)((x)*1073741824.0 + 0.5)
#define Q31(x) (int)((x)*2147483648.0 + 0.5)
#define RANGE15(x) x
#define GET_GAIN(x, y) (-(y) * (1 << (x))) + 1024
#define AAC_MUL16(x, y) (int)(((int64_t)(x) * (y) + 0x8000) >> 16)
#define AAC_MUL26(x, y) (int)(((int64_t)(x) * (y) + 0x2000000) >> 26)
#define AAC_MUL30(x, y) (int)(((int64_t)(x) * (y) + 0x20000000) >> 30)
#define AAC_MUL31(x, y) (int)(((int64_t)(x) * (y) + 0x40000000) >> 31)
#define AAC_MADD28(x, y, a, b) (int)((((int64_t)(x) * (y)) + \
((int64_t)(a) * (b)) + \
0x8000000) >> 28)
#define AAC_MADD30(x, y, a, b) (int)((((int64_t)(x) * (y)) + \
((int64_t)(a) * (b)) + \
0x20000000) >> 30)
#define AAC_MADD30_V8(x, y, a, b, c, d, e, f) (int)((((int64_t)(x) * (y)) + \
((int64_t)(a) * (b)) + \
((int64_t)(c) * (d)) + \
((int64_t)(e) * (f)) + \
0x20000000) >> 30)
#define AAC_MSUB30(x, y, a, b) (int)((((int64_t)(x) * (y)) - \
((int64_t)(a) * (b)) + \
0x20000000) >> 30)
#define AAC_MSUB30_V8(x, y, a, b, c, d, e, f) (int)((((int64_t)(x) * (y)) + \
((int64_t)(a) * (b)) - \
((int64_t)(c) * (d)) - \
((int64_t)(e) * (f)) + \
0x20000000) >> 30)
#define AAC_MSUB31_V3(x, y, z) (int)((((int64_t)(x) * (z)) - \
((int64_t)(y) * (z)) + \
0x40000000) >> 31)
#define AAC_HALF_SUM(x, y) (((x) >> 1) + ((y) >> 1))
#define AAC_SRA_R(x, y) (int)(((x) + (1 << ((y) - 1))) >> (y))
#else
#define FFT_FLOAT 1
#define FFT_FIXED_32 0
#define AAC_RENAME(x) x
#define AAC_RENAME_32(x) x
typedef float INTFLOAT;
typedef float UINTFLOAT;
typedef float INT64FLOAT;
typedef float SHORTFLOAT;
typedef float AAC_FLOAT;
typedef unsigned AAC_SIGNE;
#define FIXR(x) ((float)(x))
#define FIXR10(x) ((float)(x))
#define Q23(x) ((float)(x))
#define Q30(x) ((float)(x))
#define Q31(x) ((float)(x))
#define RANGE15(x) (32768.0 * (x))
#define GET_GAIN(x, y) powf((x), -(y))
#define AAC_MUL16(x, y) ((x) * (y))
#define AAC_MUL26(x, y) ((x) * (y))
#define AAC_MUL30(x, y) ((x) * (y))
#define AAC_MUL31(x, y) ((x) * (y))
#define AAC_MADD28(x, y, a, b) ((x) * (y) + (a) * (b))
#define AAC_MADD30(x, y, a, b) ((x) * (y) + (a) * (b))
#define AAC_MADD30_V8(x, y, a, b, c, d, e, f) ((x) * (y) + (a) * (b) + \
(c) * (d) + (e) * (f))
#define AAC_MSUB30(x, y, a, b) ((x) * (y) - (a) * (b))
#define AAC_MSUB30_V8(x, y, a, b, c, d, e, f) ((x) * (y) + (a) * (b) - \
(c) * (d) - (e) * (f))
#define AAC_MSUB31_V3(x, y, z) ((x) - (y)) * (z)
#define AAC_HALF_SUM(x, y) ((x) + (y)) * 0.5f
#define AAC_SRA_R(x, y) (x)
#endif /* USE_FIXED */
#endif /* AVCODEC_AAC_DEFINES_H */

View File

@ -0,0 +1,192 @@
/*
* AAC encoder trellis codebook selector
* Copyright (C) 2008-2009 Konstantin Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC encoder trellis codebook selector
* @author Konstantin Shishkov
*/
/**
* This file contains a template for the codebook_trellis_rate selector function.
* It needs to be provided, externally, as an already included declaration,
* the following functions from aacenc_quantization/util.h. They're not included
* explicitly here to make it possible to provide alternative implementations:
* - quantize_band_cost_bits
* - abs_pow34_v
*/
#ifndef AVCODEC_AACCODER_TRELLIS_H
#define AVCODEC_AACCODER_TRELLIS_H
#include <float.h>
#include "libavutil/mathematics.h"
#include "avcodec.h"
#include "put_bits.h"
#include "aac.h"
#include "aacenc.h"
#include "aactab.h"
#include "aacenctab.h"
/**
* structure used in optimal codebook search
*/
typedef struct TrellisBandCodingPath {
int prev_idx; ///< pointer to the previous path point
float cost; ///< path cost
int run;
} TrellisBandCodingPath;
static void codebook_trellis_rate(AACEncContext *s, SingleChannelElement *sce,
int win, int group_len, const float lambda)
{
TrellisBandCodingPath path[120][CB_TOT_ALL];
int w, swb, cb, start, size;
int i, j;
const int max_sfb = sce->ics.max_sfb;
const int run_bits = sce->ics.num_windows == 1 ? 5 : 3;
const int run_esc = (1 << run_bits) - 1;
int idx, ppos, count;
int stackrun[120], stackcb[120], stack_len;
float next_minbits = INFINITY;
int next_mincb = 0;
s->abs_pow34(s->scoefs, sce->coeffs, 1024);
start = win*128;
for (cb = 0; cb < CB_TOT_ALL; cb++) {
path[0][cb].cost = run_bits+4;
path[0][cb].prev_idx = -1;
path[0][cb].run = 0;
}
for (swb = 0; swb < max_sfb; swb++) {
size = sce->ics.swb_sizes[swb];
if (sce->zeroes[win*16 + swb]) {
float cost_stay_here = path[swb][0].cost;
float cost_get_here = next_minbits + run_bits + 4;
if ( run_value_bits[sce->ics.num_windows == 8][path[swb][0].run]
!= run_value_bits[sce->ics.num_windows == 8][path[swb][0].run+1])
cost_stay_here += run_bits;
if (cost_get_here < cost_stay_here) {
path[swb+1][0].prev_idx = next_mincb;
path[swb+1][0].cost = cost_get_here;
path[swb+1][0].run = 1;
} else {
path[swb+1][0].prev_idx = 0;
path[swb+1][0].cost = cost_stay_here;
path[swb+1][0].run = path[swb][0].run + 1;
}
next_minbits = path[swb+1][0].cost;
next_mincb = 0;
for (cb = 1; cb < CB_TOT_ALL; cb++) {
path[swb+1][cb].cost = 61450;
path[swb+1][cb].prev_idx = -1;
path[swb+1][cb].run = 0;
}
} else {
float minbits = next_minbits;
int mincb = next_mincb;
int startcb = sce->band_type[win*16+swb];
startcb = aac_cb_in_map[startcb];
next_minbits = INFINITY;
next_mincb = 0;
for (cb = 0; cb < startcb; cb++) {
path[swb+1][cb].cost = 61450;
path[swb+1][cb].prev_idx = -1;
path[swb+1][cb].run = 0;
}
for (cb = startcb; cb < CB_TOT_ALL; cb++) {
float cost_stay_here, cost_get_here;
float bits = 0.0f;
if (cb >= 12 && sce->band_type[win*16+swb] != aac_cb_out_map[cb]) {
path[swb+1][cb].cost = 61450;
path[swb+1][cb].prev_idx = -1;
path[swb+1][cb].run = 0;
continue;
}
for (w = 0; w < group_len; w++) {
bits += quantize_band_cost_bits(s, &sce->coeffs[start + w*128],
&s->scoefs[start + w*128], size,
sce->sf_idx[win*16+swb],
aac_cb_out_map[cb],
0, INFINITY, NULL, NULL, 0);
}
cost_stay_here = path[swb][cb].cost + bits;
cost_get_here = minbits + bits + run_bits + 4;
if ( run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]
!= run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])
cost_stay_here += run_bits;
if (cost_get_here < cost_stay_here) {
path[swb+1][cb].prev_idx = mincb;
path[swb+1][cb].cost = cost_get_here;
path[swb+1][cb].run = 1;
} else {
path[swb+1][cb].prev_idx = cb;
path[swb+1][cb].cost = cost_stay_here;
path[swb+1][cb].run = path[swb][cb].run + 1;
}
if (path[swb+1][cb].cost < next_minbits) {
next_minbits = path[swb+1][cb].cost;
next_mincb = cb;
}
}
}
start += sce->ics.swb_sizes[swb];
}
//convert resulting path from backward-linked list
stack_len = 0;
idx = 0;
for (cb = 1; cb < CB_TOT_ALL; cb++)
if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)
idx = cb;
ppos = max_sfb;
while (ppos > 0) {
av_assert1(idx >= 0);
cb = idx;
stackrun[stack_len] = path[ppos][cb].run;
stackcb [stack_len] = cb;
idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;
ppos -= path[ppos][cb].run;
stack_len++;
}
//perform actual band info encoding
start = 0;
for (i = stack_len - 1; i >= 0; i--) {
cb = aac_cb_out_map[stackcb[i]];
put_bits(&s->pb, 4, cb);
count = stackrun[i];
memset(sce->zeroes + win*16 + start, !cb, count);
//XXX: memset when band_type is also uint8_t
for (j = 0; j < count; j++) {
sce->band_type[win*16 + start] = cb;
start++;
}
while (count >= run_esc) {
put_bits(&s->pb, run_bits, run_esc);
count -= run_esc;
}
put_bits(&s->pb, run_bits, count);
}
}
#endif /* AVCODEC_AACCODER_TRELLIS_H */

View File

@ -0,0 +1,763 @@
/*
* AAC encoder twoloop coder
* Copyright (C) 2008-2009 Konstantin Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC encoder twoloop coder
* @author Konstantin Shishkov, Claudio Freire
*/
/**
* This file contains a template for the twoloop coder function.
* It needs to be provided, externally, as an already included declaration,
* the following functions from aacenc_quantization/util.h. They're not included
* explicitly here to make it possible to provide alternative implementations:
* - quantize_band_cost
* - abs_pow34_v
* - find_max_val
* - find_min_book
* - find_form_factor
*/
#ifndef AVCODEC_AACCODER_TWOLOOP_H
#define AVCODEC_AACCODER_TWOLOOP_H
#include <float.h>
#include "libavutil/mathematics.h"
#include "mathops.h"
#include "avcodec.h"
#include "put_bits.h"
#include "aac.h"
#include "aacenc.h"
#include "aactab.h"
#include "aacenctab.h"
/** Frequency in Hz for lower limit of noise substitution **/
#define NOISE_LOW_LIMIT 4000
#define sclip(x) av_clip(x,60,218)
/* Reflects the cost to change codebooks */
static inline int ff_pns_bits(SingleChannelElement *sce, int w, int g)
{
return (!g || !sce->zeroes[w*16+g-1] || !sce->can_pns[w*16+g-1]) ? 9 : 5;
}
/**
* two-loop quantizers search taken from ISO 13818-7 Appendix C
*/
static void search_for_quantizers_twoloop(AVCodecContext *avctx,
AACEncContext *s,
SingleChannelElement *sce,
const float lambda)
{
int start = 0, i, w, w2, g, recomprd;
int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate
/ ((avctx->flags & AV_CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels)
* (lambda / 120.f);
int refbits = destbits;
int toomanybits, toofewbits;
char nzs[128];
uint8_t nextband[128];
int maxsf[128], minsf[128];
float dists[128] = { 0 }, qenergies[128] = { 0 }, uplims[128], euplims[128], energies[128];
float maxvals[128], spread_thr_r[128];
float min_spread_thr_r, max_spread_thr_r;
/**
* rdlambda controls the maximum tolerated distortion. Twoloop
* will keep iterating until it fails to lower it or it reaches
* ulimit * rdlambda. Keeping it low increases quality on difficult
* signals, but lower it too much, and bits will be taken from weak
* signals, creating "holes". A balance is necessary.
* rdmax and rdmin specify the relative deviation from rdlambda
* allowed for tonality compensation
*/
float rdlambda = av_clipf(2.0f * 120.f / lambda, 0.0625f, 16.0f);
const float nzslope = 1.5f;
float rdmin = 0.03125f;
float rdmax = 1.0f;
/**
* sfoffs controls an offset of optmium allocation that will be
* applied based on lambda. Keep it real and modest, the loop
* will take care of the rest, this just accelerates convergence
*/
float sfoffs = av_clipf(log2f(120.0f / lambda) * 4.0f, -5, 10);
int fflag, minscaler, maxscaler, nminscaler;
int its = 0;
int maxits = 30;
int allz = 0;
int tbits;
int cutoff = 1024;
int pns_start_pos;
int prev;
/**
* zeroscale controls a multiplier of the threshold, if band energy
* is below this, a zero is forced. Keep it lower than 1, unless
* low lambda is used, because energy < threshold doesn't mean there's
* no audible signal outright, it's just energy. Also make it rise
* slower than rdlambda, as rdscale has due compensation with
* noisy band depriorization below, whereas zeroing logic is rather dumb
*/
float zeroscale;
if (lambda > 120.f) {
zeroscale = av_clipf(powf(120.f / lambda, 0.25f), 0.0625f, 1.0f);
} else {
zeroscale = 1.f;
}
if (s->psy.bitres.alloc >= 0) {
/**
* Psy granted us extra bits to use, from the reservoire
* adjust for lambda except what psy already did
*/
destbits = s->psy.bitres.alloc
* (lambda / (avctx->global_quality ? avctx->global_quality : 120));
}
if (avctx->flags & AV_CODEC_FLAG_QSCALE) {
/**
* Constant Q-scale doesn't compensate MS coding on its own
* No need to be overly precise, this only controls RD
* adjustment CB limits when going overboard
*/
if (s->options.mid_side && s->cur_type == TYPE_CPE)
destbits *= 2;
/**
* When using a constant Q-scale, don't adjust bits, just use RD
* Don't let it go overboard, though... 8x psy target is enough
*/
toomanybits = 5800;
toofewbits = destbits / 16;
/** Don't offset scalers, just RD */
sfoffs = sce->ics.num_windows - 1;
rdlambda = sqrtf(rdlambda);
/** search further */
maxits *= 2;
} else {
/* When using ABR, be strict, but a reasonable leeway is
* critical to allow RC to smoothly track desired bitrate
* without sudden quality drops that cause audible artifacts.
* Symmetry is also desirable, to avoid systematic bias.
*/
toomanybits = destbits + destbits/8;
toofewbits = destbits - destbits/8;
sfoffs = 0;
rdlambda = sqrtf(rdlambda);
}
/** and zero out above cutoff frequency */
{
int wlen = 1024 / sce->ics.num_windows;
int bandwidth;
/**
* Scale, psy gives us constant quality, this LP only scales
* bitrate by lambda, so we save bits on subjectively unimportant HF
* rather than increase quantization noise. Adjust nominal bitrate
* to effective bitrate according to encoding parameters,
* AAC_CUTOFF_FROM_BITRATE is calibrated for effective bitrate.
*/
float rate_bandwidth_multiplier = 1.5f;
int frame_bit_rate = (avctx->flags & AV_CODEC_FLAG_QSCALE)
? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024)
: (avctx->bit_rate / avctx->channels);
/** Compensate for extensions that increase efficiency */
if (s->options.pns || s->options.intensity_stereo)
frame_bit_rate *= 1.15f;
if (avctx->cutoff > 0) {
bandwidth = avctx->cutoff;
} else {
bandwidth = FFMAX(3000, AAC_CUTOFF_FROM_BITRATE(frame_bit_rate, 1, avctx->sample_rate));
s->psy.cutoff = bandwidth;
}
cutoff = bandwidth * 2 * wlen / avctx->sample_rate;
pns_start_pos = NOISE_LOW_LIMIT * 2 * wlen / avctx->sample_rate;
}
/**
* for values above this the decoder might end up in an endless loop
* due to always having more bits than what can be encoded.
*/
destbits = FFMIN(destbits, 5800);
toomanybits = FFMIN(toomanybits, 5800);
toofewbits = FFMIN(toofewbits, 5800);
/**
* XXX: some heuristic to determine initial quantizers will reduce search time
* determine zero bands and upper distortion limits
*/
min_spread_thr_r = -1;
max_spread_thr_r = -1;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
for (g = start = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) {
int nz = 0;
float uplim = 0.0f, energy = 0.0f, spread = 0.0f;
for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
if (start >= cutoff || band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0f) {
sce->zeroes[(w+w2)*16+g] = 1;
continue;
}
nz = 1;
}
if (!nz) {
uplim = 0.0f;
} else {
nz = 0;
for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
if (band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0f)
continue;
uplim += band->threshold;
energy += band->energy;
spread += band->spread;
nz++;
}
}
uplims[w*16+g] = uplim;
energies[w*16+g] = energy;
nzs[w*16+g] = nz;
sce->zeroes[w*16+g] = !nz;
allz |= nz;
if (nz && sce->can_pns[w*16+g]) {
spread_thr_r[w*16+g] = energy * nz / (uplim * spread);
if (min_spread_thr_r < 0) {
min_spread_thr_r = max_spread_thr_r = spread_thr_r[w*16+g];
} else {
min_spread_thr_r = FFMIN(min_spread_thr_r, spread_thr_r[w*16+g]);
max_spread_thr_r = FFMAX(max_spread_thr_r, spread_thr_r[w*16+g]);
}
}
}
}
/** Compute initial scalers */
minscaler = 65535;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
for (g = 0; g < sce->ics.num_swb; g++) {
if (sce->zeroes[w*16+g]) {
sce->sf_idx[w*16+g] = SCALE_ONE_POS;
continue;
}
/**
* log2f-to-distortion ratio is, technically, 2 (1.5db = 4, but it's power vs level so it's 2).
* But, as offsets are applied, low-frequency signals are too sensitive to the induced distortion,
* so we make scaling more conservative by choosing a lower log2f-to-distortion ratio, and thus
* more robust.
*/
sce->sf_idx[w*16+g] = av_clip(
SCALE_ONE_POS
+ 1.75*log2f(FFMAX(0.00125f,uplims[w*16+g]) / sce->ics.swb_sizes[g])
+ sfoffs,
60, SCALE_MAX_POS);
minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
}
}
/** Clip */
minscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512);
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
for (g = 0; g < sce->ics.num_swb; g++)
if (!sce->zeroes[w*16+g])
sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF - 1);
if (!allz)
return;
s->abs_pow34(s->scoefs, sce->coeffs, 1024);
ff_quantize_band_cost_cache_init(s);
for (i = 0; i < sizeof(minsf) / sizeof(minsf[0]); ++i)
minsf[i] = 0;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
start = w*128;
for (g = 0; g < sce->ics.num_swb; g++) {
const float *scaled = s->scoefs + start;
int minsfidx;
maxvals[w*16+g] = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], scaled);
if (maxvals[w*16+g] > 0) {
minsfidx = coef2minsf(maxvals[w*16+g]);
for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
minsf[(w+w2)*16+g] = minsfidx;
}
start += sce->ics.swb_sizes[g];
}
}
/**
* Scale uplims to match rate distortion to quality
* bu applying noisy band depriorization and tonal band priorization.
* Maxval-energy ratio gives us an idea of how noisy/tonal the band is.
* If maxval^2 ~ energy, then that band is mostly noise, and we can relax
* rate distortion requirements.
*/
memcpy(euplims, uplims, sizeof(euplims));
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
/** psy already priorizes transients to some extent */
float de_psy_factor = (sce->ics.num_windows > 1) ? 8.0f / sce->ics.group_len[w] : 1.0f;
start = w*128;
for (g = 0; g < sce->ics.num_swb; g++) {
if (nzs[g] > 0) {
float cleanup_factor = ff_sqrf(av_clipf(start / (cutoff * 0.75f), 1.0f, 2.0f));
float energy2uplim = find_form_factor(
sce->ics.group_len[w], sce->ics.swb_sizes[g],
uplims[w*16+g] / (nzs[g] * sce->ics.swb_sizes[w]),
sce->coeffs + start,
nzslope * cleanup_factor);
energy2uplim *= de_psy_factor;
if (!(avctx->flags & AV_CODEC_FLAG_QSCALE)) {
/** In ABR, we need to priorize less and let rate control do its thing */
energy2uplim = sqrtf(energy2uplim);
}
energy2uplim = FFMAX(0.015625f, FFMIN(1.0f, energy2uplim));
uplims[w*16+g] *= av_clipf(rdlambda * energy2uplim, rdmin, rdmax)
* sce->ics.group_len[w];
energy2uplim = find_form_factor(
sce->ics.group_len[w], sce->ics.swb_sizes[g],
uplims[w*16+g] / (nzs[g] * sce->ics.swb_sizes[w]),
sce->coeffs + start,
2.0f);
energy2uplim *= de_psy_factor;
if (!(avctx->flags & AV_CODEC_FLAG_QSCALE)) {
/** In ABR, we need to priorize less and let rate control do its thing */
energy2uplim = sqrtf(energy2uplim);
}
energy2uplim = FFMAX(0.015625f, FFMIN(1.0f, energy2uplim));
euplims[w*16+g] *= av_clipf(rdlambda * energy2uplim * sce->ics.group_len[w],
0.5f, 1.0f);
}
start += sce->ics.swb_sizes[g];
}
}
for (i = 0; i < sizeof(maxsf) / sizeof(maxsf[0]); ++i)
maxsf[i] = SCALE_MAX_POS;
//perform two-loop search
//outer loop - improve quality
do {
//inner loop - quantize spectrum to fit into given number of bits
int overdist;
int qstep = its ? 1 : 32;
do {
int changed = 0;
prev = -1;
recomprd = 0;
tbits = 0;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
start = w*128;
for (g = 0; g < sce->ics.num_swb; g++) {
const float *coefs = &sce->coeffs[start];
const float *scaled = &s->scoefs[start];
int bits = 0;
int cb;
float dist = 0.0f;
float qenergy = 0.0f;
if (sce->zeroes[w*16+g] || sce->sf_idx[w*16+g] >= 218) {
start += sce->ics.swb_sizes[g];
if (sce->can_pns[w*16+g]) {
/** PNS isn't free */
tbits += ff_pns_bits(sce, w, g);
}
continue;
}
cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
int b;
float sqenergy;
dist += quantize_band_cost_cached(s, w + w2, g, coefs + w2*128,
scaled + w2*128,
sce->ics.swb_sizes[g],
sce->sf_idx[w*16+g],
cb,
1.0f,
INFINITY,
&b, &sqenergy,
0);
bits += b;
qenergy += sqenergy;
}
dists[w*16+g] = dist - bits;
qenergies[w*16+g] = qenergy;
if (prev != -1) {
int sfdiff = av_clip(sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO, 0, 2*SCALE_MAX_DIFF);
bits += ff_aac_scalefactor_bits[sfdiff];
}
tbits += bits;
start += sce->ics.swb_sizes[g];
prev = sce->sf_idx[w*16+g];
}
}
if (tbits > toomanybits) {
recomprd = 1;
for (i = 0; i < 128; i++) {
if (sce->sf_idx[i] < (SCALE_MAX_POS - SCALE_DIV_512)) {
int maxsf_i = (tbits > 5800) ? SCALE_MAX_POS : maxsf[i];
int new_sf = FFMIN(maxsf_i, sce->sf_idx[i] + qstep);
if (new_sf != sce->sf_idx[i]) {
sce->sf_idx[i] = new_sf;
changed = 1;
}
}
}
} else if (tbits < toofewbits) {
recomprd = 1;
for (i = 0; i < 128; i++) {
if (sce->sf_idx[i] > SCALE_ONE_POS) {
int new_sf = FFMAX3(minsf[i], SCALE_ONE_POS, sce->sf_idx[i] - qstep);
if (new_sf != sce->sf_idx[i]) {
sce->sf_idx[i] = new_sf;
changed = 1;
}
}
}
}
qstep >>= 1;
if (!qstep && tbits > toomanybits && sce->sf_idx[0] < 217 && changed)
qstep = 1;
} while (qstep);
overdist = 1;
fflag = tbits < toofewbits;
for (i = 0; i < 2 && (overdist || recomprd); ++i) {
if (recomprd) {
/** Must recompute distortion */
prev = -1;
tbits = 0;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
start = w*128;
for (g = 0; g < sce->ics.num_swb; g++) {
const float *coefs = sce->coeffs + start;
const float *scaled = s->scoefs + start;
int bits = 0;
int cb;
float dist = 0.0f;
float qenergy = 0.0f;
if (sce->zeroes[w*16+g] || sce->sf_idx[w*16+g] >= 218) {
start += sce->ics.swb_sizes[g];
if (sce->can_pns[w*16+g]) {
/** PNS isn't free */
tbits += ff_pns_bits(sce, w, g);
}
continue;
}
cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
int b;
float sqenergy;
dist += quantize_band_cost_cached(s, w + w2, g, coefs + w2*128,
scaled + w2*128,
sce->ics.swb_sizes[g],
sce->sf_idx[w*16+g],
cb,
1.0f,
INFINITY,
&b, &sqenergy,
0);
bits += b;
qenergy += sqenergy;
}
dists[w*16+g] = dist - bits;
qenergies[w*16+g] = qenergy;
if (prev != -1) {
int sfdiff = av_clip(sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO, 0, 2*SCALE_MAX_DIFF);
bits += ff_aac_scalefactor_bits[sfdiff];
}
tbits += bits;
start += sce->ics.swb_sizes[g];
prev = sce->sf_idx[w*16+g];
}
}
}
if (!i && s->options.pns && its > maxits/2 && tbits > toofewbits) {
float maxoverdist = 0.0f;
float ovrfactor = 1.f+(maxits-its)*16.f/maxits;
overdist = recomprd = 0;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
for (g = start = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) {
if (!sce->zeroes[w*16+g] && sce->sf_idx[w*16+g] > SCALE_ONE_POS && dists[w*16+g] > uplims[w*16+g]*ovrfactor) {
float ovrdist = dists[w*16+g] / FFMAX(uplims[w*16+g],euplims[w*16+g]);
maxoverdist = FFMAX(maxoverdist, ovrdist);
overdist++;
}
}
}
if (overdist) {
/* We have overdistorted bands, trade for zeroes (that can be noise)
* Zero the bands in the lowest 1.25% spread-energy-threshold ranking
*/
float minspread = max_spread_thr_r;
float maxspread = min_spread_thr_r;
float zspread;
int zeroable = 0;
int zeroed = 0;
int maxzeroed, zloop;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
for (g = start = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) {
if (start >= pns_start_pos && !sce->zeroes[w*16+g] && sce->can_pns[w*16+g]) {
minspread = FFMIN(minspread, spread_thr_r[w*16+g]);
maxspread = FFMAX(maxspread, spread_thr_r[w*16+g]);
zeroable++;
}
}
}
zspread = (maxspread-minspread) * 0.0125f + minspread;
/* Don't PNS everything even if allowed. It suppresses bit starvation signals from RC,
* and forced the hand of the later search_for_pns step.
* Instead, PNS a fraction of the spread_thr_r range depending on how starved for bits we are,
* and leave further PNSing to search_for_pns if worthwhile.
*/
zspread = FFMIN3(min_spread_thr_r * 8.f, zspread,
((toomanybits - tbits) * min_spread_thr_r + (tbits - toofewbits) * max_spread_thr_r) / (toomanybits - toofewbits + 1));
maxzeroed = FFMIN(zeroable, FFMAX(1, (zeroable * its + maxits - 1) / (2 * maxits)));
for (zloop = 0; zloop < 2; zloop++) {
/* Two passes: first distorted stuff - two birds in one shot and all that,
* then anything viable. Viable means not zero, but either CB=zero-able
* (too high SF), not SF <= 1 (that means we'd be operating at very high
* quality, we don't want PNS when doing VHQ), PNS allowed, and within
* the lowest ranking percentile.
*/
float loopovrfactor = (zloop) ? 1.0f : ovrfactor;
int loopminsf = (zloop) ? (SCALE_ONE_POS - SCALE_DIV_512) : SCALE_ONE_POS;
int mcb;
for (g = sce->ics.num_swb-1; g > 0 && zeroed < maxzeroed; g--) {
if (sce->ics.swb_offset[g] < pns_start_pos)
continue;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
if (!sce->zeroes[w*16+g] && sce->can_pns[w*16+g] && spread_thr_r[w*16+g] <= zspread
&& sce->sf_idx[w*16+g] > loopminsf
&& (dists[w*16+g] > loopovrfactor*uplims[w*16+g] || !(mcb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]))
|| (mcb <= 1 && dists[w*16+g] > FFMIN(uplims[w*16+g], euplims[w*16+g]))) ) {
sce->zeroes[w*16+g] = 1;
sce->band_type[w*16+g] = 0;
zeroed++;
}
}
}
}
if (zeroed)
recomprd = fflag = 1;
} else {
overdist = 0;
}
}
}
minscaler = SCALE_MAX_POS;
maxscaler = 0;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
for (g = 0; g < sce->ics.num_swb; g++) {
if (!sce->zeroes[w*16+g]) {
minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
maxscaler = FFMAX(maxscaler, sce->sf_idx[w*16+g]);
}
}
}
minscaler = nminscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512);
prev = -1;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
/** Start with big steps, end up fine-tunning */
int depth = (its > maxits/2) ? ((its > maxits*2/3) ? 1 : 3) : 10;
int edepth = depth+2;
float uplmax = its / (maxits*0.25f) + 1.0f;
uplmax *= (tbits > destbits) ? FFMIN(2.0f, tbits / (float)FFMAX(1,destbits)) : 1.0f;
start = w * 128;
for (g = 0; g < sce->ics.num_swb; g++) {
int prevsc = sce->sf_idx[w*16+g];
if (prev < 0 && !sce->zeroes[w*16+g])
prev = sce->sf_idx[0];
if (!sce->zeroes[w*16+g]) {
const float *coefs = sce->coeffs + start;
const float *scaled = s->scoefs + start;
int cmb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
int mindeltasf = FFMAX(0, prev - SCALE_MAX_DIFF);
int maxdeltasf = FFMIN(SCALE_MAX_POS - SCALE_DIV_512, prev + SCALE_MAX_DIFF);
if ((!cmb || dists[w*16+g] > uplims[w*16+g]) && sce->sf_idx[w*16+g] > FFMAX(mindeltasf, minsf[w*16+g])) {
/* Try to make sure there is some energy in every nonzero band
* NOTE: This algorithm must be forcibly imbalanced, pushing harder
* on holes or more distorted bands at first, otherwise there's
* no net gain (since the next iteration will offset all bands
* on the opposite direction to compensate for extra bits)
*/
for (i = 0; i < edepth && sce->sf_idx[w*16+g] > mindeltasf; ++i) {
int cb, bits;
float dist, qenergy;
int mb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1);
cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
dist = qenergy = 0.f;
bits = 0;
if (!cb) {
maxsf[w*16+g] = FFMIN(sce->sf_idx[w*16+g]-1, maxsf[w*16+g]);
} else if (i >= depth && dists[w*16+g] < euplims[w*16+g]) {
break;
}
/* !g is the DC band, it's important, since quantization error here
* applies to less than a cycle, it creates horrible intermodulation
* distortion if it doesn't stick to what psy requests
*/
if (!g && sce->ics.num_windows > 1 && dists[w*16+g] >= euplims[w*16+g])
maxsf[w*16+g] = FFMIN(sce->sf_idx[w*16+g], maxsf[w*16+g]);
for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
int b;
float sqenergy;
dist += quantize_band_cost_cached(s, w + w2, g, coefs + w2*128,
scaled + w2*128,
sce->ics.swb_sizes[g],
sce->sf_idx[w*16+g]-1,
cb,
1.0f,
INFINITY,
&b, &sqenergy,
0);
bits += b;
qenergy += sqenergy;
}
sce->sf_idx[w*16+g]--;
dists[w*16+g] = dist - bits;
qenergies[w*16+g] = qenergy;
if (mb && (sce->sf_idx[w*16+g] < mindeltasf || (
(dists[w*16+g] < FFMIN(uplmax*uplims[w*16+g], euplims[w*16+g]))
&& (fabsf(qenergies[w*16+g]-energies[w*16+g]) < euplims[w*16+g])
) )) {
break;
}
}
} else if (tbits > toofewbits && sce->sf_idx[w*16+g] < FFMIN(maxdeltasf, maxsf[w*16+g])
&& (dists[w*16+g] < FFMIN(euplims[w*16+g], uplims[w*16+g]))
&& (fabsf(qenergies[w*16+g]-energies[w*16+g]) < euplims[w*16+g])
) {
/** Um... over target. Save bits for more important stuff. */
for (i = 0; i < depth && sce->sf_idx[w*16+g] < maxdeltasf; ++i) {
int cb, bits;
float dist, qenergy;
cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]+1);
if (cb > 0) {
dist = qenergy = 0.f;
bits = 0;
for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
int b;
float sqenergy;
dist += quantize_band_cost_cached(s, w + w2, g, coefs + w2*128,
scaled + w2*128,
sce->ics.swb_sizes[g],
sce->sf_idx[w*16+g]+1,
cb,
1.0f,
INFINITY,
&b, &sqenergy,
0);
bits += b;
qenergy += sqenergy;
}
dist -= bits;
if (dist < FFMIN(euplims[w*16+g], uplims[w*16+g])) {
sce->sf_idx[w*16+g]++;
dists[w*16+g] = dist;
qenergies[w*16+g] = qenergy;
} else {
break;
}
} else {
maxsf[w*16+g] = FFMIN(sce->sf_idx[w*16+g], maxsf[w*16+g]);
break;
}
}
}
prev = sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], mindeltasf, maxdeltasf);
if (sce->sf_idx[w*16+g] != prevsc)
fflag = 1;
nminscaler = FFMIN(nminscaler, sce->sf_idx[w*16+g]);
sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
}
start += sce->ics.swb_sizes[g];
}
}
/** SF difference limit violation risk. Must re-clamp. */
prev = -1;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
for (g = 0; g < sce->ics.num_swb; g++) {
if (!sce->zeroes[w*16+g]) {
int prevsf = sce->sf_idx[w*16+g];
if (prev < 0)
prev = prevsf;
sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], prev - SCALE_MAX_DIFF, prev + SCALE_MAX_DIFF);
sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
prev = sce->sf_idx[w*16+g];
if (!fflag && prevsf != sce->sf_idx[w*16+g])
fflag = 1;
}
}
}
its++;
} while (fflag && its < maxits);
/** Scout out next nonzero bands */
ff_init_nextband_map(sce, nextband);
prev = -1;
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
/** Make sure proper codebooks are set */
for (g = 0; g < sce->ics.num_swb; g++) {
if (!sce->zeroes[w*16+g]) {
sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
if (sce->band_type[w*16+g] <= 0) {
if (!ff_sfdelta_can_remove_band(sce, nextband, prev, w*16+g)) {
/** Cannot zero out, make sure it's not attempted */
sce->band_type[w*16+g] = 1;
} else {
sce->zeroes[w*16+g] = 1;
sce->band_type[w*16+g] = 0;
}
}
} else {
sce->band_type[w*16+g] = 0;
}
/** Check that there's no SF delta range violations */
if (!sce->zeroes[w*16+g]) {
if (prev != -1) {
av_unused int sfdiff = sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO;
av_assert1(sfdiff >= 0 && sfdiff <= 2*SCALE_MAX_DIFF);
} else if (sce->zeroes[0]) {
/** Set global gain to something useful */
sce->sf_idx[0] = sce->sf_idx[w*16+g];
}
prev = sce->sf_idx[w*16+g];
}
}
}
}
#endif /* AVCODEC_AACCODER_TWOLOOP_H */

View File

@ -0,0 +1,74 @@
/*
* AAC decoder data
* Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
* Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC decoder data
* @author Oded Shimon ( ods15 ods15 dyndns org )
* @author Maxim Gavrilov ( maxim.gavrilov gmail com )
*/
#ifndef AVCODEC_AACDECTAB_H
#define AVCODEC_AACDECTAB_H
#include "libavutil/channel_layout.h"
#include "aac.h"
#include <stdint.h>
static const int8_t tags_per_config[16] = { 0, 1, 1, 2, 3, 3, 4, 5, 0, 0, 0, 4, 5, 0, 5, 0 };
static const uint8_t aac_channel_layout_map[16][5][3] = {
{ { TYPE_SCE, 0, AAC_CHANNEL_FRONT }, },
{ { TYPE_CPE, 0, AAC_CHANNEL_FRONT }, },
{ { TYPE_SCE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 0, AAC_CHANNEL_FRONT }, },
{ { TYPE_SCE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 0, AAC_CHANNEL_FRONT }, { TYPE_SCE, 1, AAC_CHANNEL_BACK }, },
{ { TYPE_SCE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 1, AAC_CHANNEL_BACK }, },
{ { TYPE_SCE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 1, AAC_CHANNEL_BACK }, { TYPE_LFE, 0, AAC_CHANNEL_LFE }, },
{ { TYPE_SCE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 1, AAC_CHANNEL_FRONT }, { TYPE_CPE, 2, AAC_CHANNEL_BACK }, { TYPE_LFE, 0, AAC_CHANNEL_LFE }, },
{ { 0, } },
{ { 0, } },
{ { 0, } },
{ { TYPE_SCE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 1, AAC_CHANNEL_BACK }, { TYPE_SCE, 1, AAC_CHANNEL_BACK }, { TYPE_LFE, 0, AAC_CHANNEL_LFE }, },
{ { TYPE_SCE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 0, AAC_CHANNEL_FRONT }, { TYPE_CPE, 1, AAC_CHANNEL_SIDE }, { TYPE_CPE, 2, AAC_CHANNEL_BACK }, { TYPE_LFE, 0, AAC_CHANNEL_LFE }, },
{ { 0, } },
/* TODO: Add 7+1 TOP configuration */
};
static const uint64_t aac_channel_layout[16] = {
AV_CH_LAYOUT_MONO,
AV_CH_LAYOUT_STEREO,
AV_CH_LAYOUT_SURROUND,
AV_CH_LAYOUT_4POINT0,
AV_CH_LAYOUT_5POINT0_BACK,
AV_CH_LAYOUT_5POINT1_BACK,
AV_CH_LAYOUT_7POINT1_WIDE_BACK,
0,
0,
0,
AV_CH_LAYOUT_6POINT1,
AV_CH_LAYOUT_7POINT1,
0,
/* AV_CH_LAYOUT_7POINT1_TOP, */
};
#endif /* AVCODEC_AACDECTAB_H */

View File

@ -0,0 +1,428 @@
/*
* AAC encoder
* Copyright (C) 2008 Konstantin Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AACENC_H
#define AVCODEC_AACENC_H
#include "libavutil/float_dsp.h"
#include "avcodec.h"
#include "put_bits.h"
#include "aac.h"
#include "audio_frame_queue.h"
#include "psymodel.h"
#include "lpc.h"
typedef enum AACCoder {
AAC_CODER_ANMR = 0,
AAC_CODER_TWOLOOP,
AAC_CODER_FAST,
AAC_CODER_NB,
}AACCoder;
typedef struct AACEncOptions {
int coder;
int pns;
int tns;
int ltp;
int pce;
int pred;
int mid_side;
int intensity_stereo;
} AACEncOptions;
struct AACEncContext;
typedef struct AACCoefficientsEncoder {
void (*search_for_quantizers)(AVCodecContext *avctx, struct AACEncContext *s,
SingleChannelElement *sce, const float lambda);
void (*encode_window_bands_info)(struct AACEncContext *s, SingleChannelElement *sce,
int win, int group_len, const float lambda);
void (*quantize_and_encode_band)(struct AACEncContext *s, PutBitContext *pb, const float *in, float *out, int size,
int scale_idx, int cb, const float lambda, int rtz);
void (*encode_tns_info)(struct AACEncContext *s, SingleChannelElement *sce);
void (*encode_ltp_info)(struct AACEncContext *s, SingleChannelElement *sce, int common_window);
void (*encode_main_pred)(struct AACEncContext *s, SingleChannelElement *sce);
void (*adjust_common_pred)(struct AACEncContext *s, ChannelElement *cpe);
void (*adjust_common_ltp)(struct AACEncContext *s, ChannelElement *cpe);
void (*apply_main_pred)(struct AACEncContext *s, SingleChannelElement *sce);
void (*apply_tns_filt)(struct AACEncContext *s, SingleChannelElement *sce);
void (*update_ltp)(struct AACEncContext *s, SingleChannelElement *sce);
void (*ltp_insert_new_frame)(struct AACEncContext *s);
void (*set_special_band_scalefactors)(struct AACEncContext *s, SingleChannelElement *sce);
void (*search_for_pns)(struct AACEncContext *s, AVCodecContext *avctx, SingleChannelElement *sce);
void (*mark_pns)(struct AACEncContext *s, AVCodecContext *avctx, SingleChannelElement *sce);
void (*search_for_tns)(struct AACEncContext *s, SingleChannelElement *sce);
void (*search_for_ltp)(struct AACEncContext *s, SingleChannelElement *sce, int common_window);
void (*search_for_ms)(struct AACEncContext *s, ChannelElement *cpe);
void (*search_for_is)(struct AACEncContext *s, AVCodecContext *avctx, ChannelElement *cpe);
void (*search_for_pred)(struct AACEncContext *s, SingleChannelElement *sce);
} AACCoefficientsEncoder;
extern const AACCoefficientsEncoder ff_aac_coders[];
typedef struct AACQuantizeBandCostCacheEntry {
float rd;
float energy;
int bits;
char cb;
char rtz;
uint16_t generation;
} AACQuantizeBandCostCacheEntry;
typedef struct AACPCEInfo {
int64_t layout;
int num_ele[4]; ///< front, side, back, lfe
int pairing[3][8]; ///< front, side, back
int index[4][8]; ///< front, side, back, lfe
uint8_t config_map[16]; ///< configs the encoder's channel specific settings
uint8_t reorder_map[16]; ///< maps channels from lavc to aac order
} AACPCEInfo;
/**
* List of PCE (Program Configuration Element) for the channel layouts listed
* in channel_layout.h
*
* For those wishing in the future to add other layouts:
*
* - num_ele: number of elements in each group of front, side, back, lfe channels
* (an element is of type SCE (single channel), CPE (channel pair) for
* the first 3 groups; and is LFE for LFE group).
*
* - pairing: 0 for an SCE element or 1 for a CPE; does not apply to LFE group
*
* - index: there are three independent indices for SCE, CPE and LFE;
* they are incremented irrespective of the group to which the element belongs;
* they are not reset when going from one group to another
*
* Example: for 7.0 channel layout,
* .pairing = { { 1, 0 }, { 1 }, { 1 }, }, (3 CPE and 1 SCE in front group)
* .index = { { 0, 0 }, { 1 }, { 2 }, },
* (index is 0 for the single SCE but goes from 0 to 2 for the CPEs)
*
* The index order impacts the channel ordering. But is otherwise arbitrary
* (the sequence could have been 2, 0, 1 instead of 0, 1, 2).
*
* Spec allows for discontinuous indices, e.g. if one has a total of two SCE,
* SCE.0 SCE.15 is OK per spec; BUT it won't be decoded by our AAC decoder
* which at this time requires that indices fully cover some range starting
* from 0 (SCE.1 SCE.0 is OK but not SCE.0 SCE.15).
*
* - config_map: total number of elements and their types. Beware, the way the
* types are ordered impacts the final channel ordering.
*
* - reorder_map: reorders the channels.
*
*/
static const AACPCEInfo aac_pce_configs[] = {
{
.layout = AV_CH_LAYOUT_MONO,
.num_ele = { 1, 0, 0, 0 },
.pairing = { { 0 }, },
.index = { { 0 }, },
.config_map = { 1, TYPE_SCE, },
.reorder_map = { 0 },
},
{
.layout = AV_CH_LAYOUT_STEREO,
.num_ele = { 1, 0, 0, 0 },
.pairing = { { 1 }, },
.index = { { 0 }, },
.config_map = { 1, TYPE_CPE, },
.reorder_map = { 0, 1 },
},
{
.layout = AV_CH_LAYOUT_2POINT1,
.num_ele = { 1, 0, 0, 1 },
.pairing = { { 1 }, },
.index = { { 0 },{ 0 },{ 0 },{ 0 } },
.config_map = { 2, TYPE_CPE, TYPE_LFE },
.reorder_map = { 0, 1, 2 },
},
{
.layout = AV_CH_LAYOUT_2_1,
.num_ele = { 1, 0, 1, 0 },
.pairing = { { 1 },{ 0 },{ 0 } },
.index = { { 0 },{ 0 },{ 0 }, },
.config_map = { 2, TYPE_CPE, TYPE_SCE },
.reorder_map = { 0, 1, 2 },
},
{
.layout = AV_CH_LAYOUT_SURROUND,
.num_ele = { 2, 0, 0, 0 },
.pairing = { { 1, 0 }, },
.index = { { 0, 0 }, },
.config_map = { 2, TYPE_CPE, TYPE_SCE, },
.reorder_map = { 0, 1, 2 },
},
{
.layout = AV_CH_LAYOUT_3POINT1,
.num_ele = { 2, 0, 0, 1 },
.pairing = { { 1, 0 }, },
.index = { { 0, 0 }, { 0 }, { 0 }, { 0 }, },
.config_map = { 3, TYPE_CPE, TYPE_SCE, TYPE_LFE },
.reorder_map = { 0, 1, 2, 3 },
},
{
.layout = AV_CH_LAYOUT_4POINT0,
.num_ele = { 2, 0, 1, 0 },
.pairing = { { 1, 0 }, { 0 }, { 0 }, },
.index = { { 0, 0 }, { 0 }, { 1 } },
.config_map = { 3, TYPE_CPE, TYPE_SCE, TYPE_SCE },
.reorder_map = { 0, 1, 2, 3 },
},
{
.layout = AV_CH_LAYOUT_4POINT1,
.num_ele = { 2, 1, 1, 0 },
.pairing = { { 1, 0 }, { 0 }, { 0 }, },
.index = { { 0, 0 }, { 1 }, { 2 }, { 0 } },
.config_map = { 4, TYPE_CPE, TYPE_SCE, TYPE_SCE, TYPE_SCE },
.reorder_map = { 0, 1, 2, 3, 4 },
},
{
.layout = AV_CH_LAYOUT_2_2,
.num_ele = { 1, 1, 0, 0 },
.pairing = { { 1 }, { 1 }, },
.index = { { 0 }, { 1 }, },
.config_map = { 2, TYPE_CPE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3 },
},
{
.layout = AV_CH_LAYOUT_QUAD,
.num_ele = { 1, 0, 1, 0 },
.pairing = { { 1 }, { 0 }, { 1 }, },
.index = { { 0 }, { 0 }, { 1 } },
.config_map = { 2, TYPE_CPE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3 },
},
{
.layout = AV_CH_LAYOUT_5POINT0,
.num_ele = { 2, 1, 0, 0 },
.pairing = { { 1, 0 }, { 1 }, },
.index = { { 0, 0 }, { 1 } },
.config_map = { 3, TYPE_CPE, TYPE_SCE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3, 4 },
},
{
.layout = AV_CH_LAYOUT_5POINT1,
.num_ele = { 2, 1, 1, 0 },
.pairing = { { 1, 0 }, { 0 }, { 1 }, },
.index = { { 0, 0 }, { 1 }, { 1 } },
.config_map = { 4, TYPE_CPE, TYPE_SCE, TYPE_SCE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3, 4, 5 },
},
{
.layout = AV_CH_LAYOUT_5POINT0_BACK,
.num_ele = { 2, 0, 1, 0 },
.pairing = { { 1, 0 }, { 0 }, { 1 } },
.index = { { 0, 0 }, { 0 }, { 1 } },
.config_map = { 3, TYPE_CPE, TYPE_SCE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3, 4 },
},
{
.layout = AV_CH_LAYOUT_5POINT1_BACK,
.num_ele = { 2, 1, 1, 0 },
.pairing = { { 1, 0 }, { 0 }, { 1 }, },
.index = { { 0, 0 }, { 1 }, { 1 } },
.config_map = { 4, TYPE_CPE, TYPE_SCE, TYPE_SCE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3, 4, 5 },
},
{
.layout = AV_CH_LAYOUT_6POINT0,
.num_ele = { 2, 1, 1, 0 },
.pairing = { { 1, 0 }, { 1 }, { 0 }, },
.index = { { 0, 0 }, { 1 }, { 1 } },
.config_map = { 4, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_SCE },
.reorder_map = { 0, 1, 2, 3, 4, 5 },
},
{
.layout = AV_CH_LAYOUT_6POINT0_FRONT,
.num_ele = { 2, 1, 0, 0 },
.pairing = { { 1, 1 }, { 1 } },
.index = { { 1, 0 }, { 2 }, },
.config_map = { 3, TYPE_CPE, TYPE_CPE, TYPE_CPE, },
.reorder_map = { 0, 1, 2, 3, 4, 5 },
},
{
.layout = AV_CH_LAYOUT_HEXAGONAL,
.num_ele = { 2, 0, 2, 0 },
.pairing = { { 1, 0 },{ 0 },{ 1, 0 }, },
.index = { { 0, 0 },{ 0 },{ 1, 1 } },
.config_map = { 4, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_SCE, },
.reorder_map = { 0, 1, 2, 3, 4, 5 },
},
{
.layout = AV_CH_LAYOUT_6POINT1,
.num_ele = { 2, 1, 2, 0 },
.pairing = { { 1, 0 },{ 0 },{ 1, 0 }, },
.index = { { 0, 0 },{ 1 },{ 1, 2 } },
.config_map = { 5, TYPE_CPE, TYPE_SCE, TYPE_SCE, TYPE_CPE, TYPE_SCE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6 },
},
{
.layout = AV_CH_LAYOUT_6POINT1_BACK,
.num_ele = { 2, 1, 2, 0 },
.pairing = { { 1, 0 }, { 0 }, { 1, 0 }, },
.index = { { 0, 0 }, { 1 }, { 1, 2 } },
.config_map = { 5, TYPE_CPE, TYPE_SCE, TYPE_SCE, TYPE_CPE, TYPE_SCE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6 },
},
{
.layout = AV_CH_LAYOUT_6POINT1_FRONT,
.num_ele = { 2, 1, 2, 0 },
.pairing = { { 1, 0 }, { 0 }, { 1, 0 }, },
.index = { { 0, 0 }, { 1 }, { 1, 2 } },
.config_map = { 5, TYPE_CPE, TYPE_SCE, TYPE_SCE, TYPE_CPE, TYPE_SCE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6 },
},
{
.layout = AV_CH_LAYOUT_7POINT0,
.num_ele = { 2, 1, 1, 0 },
.pairing = { { 1, 0 }, { 1 }, { 1 }, },
.index = { { 0, 0 }, { 1 }, { 2 }, },
.config_map = { 4, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6 },
},
{
.layout = AV_CH_LAYOUT_7POINT0_FRONT,
.num_ele = { 2, 1, 1, 0 },
.pairing = { { 1, 0 }, { 1 }, { 1 }, },
.index = { { 0, 0 }, { 1 }, { 2 }, },
.config_map = { 4, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6 },
},
{
.layout = AV_CH_LAYOUT_7POINT1,
.num_ele = { 2, 1, 2, 0 },
.pairing = { { 1, 0 }, { 0 }, { 1, 1 }, },
.index = { { 0, 0 }, { 1 }, { 1, 2 }, { 0 } },
.config_map = { 5, TYPE_CPE, TYPE_SCE, TYPE_SCE, TYPE_CPE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6, 7 },
},
{
.layout = AV_CH_LAYOUT_7POINT1_WIDE,
.num_ele = { 2, 1, 2, 0 },
.pairing = { { 1, 0 }, { 0 },{ 1, 1 }, },
.index = { { 0, 0 }, { 1 }, { 1, 2 }, { 0 } },
.config_map = { 5, TYPE_CPE, TYPE_SCE, TYPE_SCE, TYPE_CPE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6, 7 },
},
{
.layout = AV_CH_LAYOUT_7POINT1_WIDE_BACK,
.num_ele = { 2, 1, 2, 0 },
.pairing = { { 1, 0 }, { 0 }, { 1, 1 }, },
.index = { { 0, 0 }, { 1 }, { 1, 2 }, { 0 } },
.config_map = { 5, TYPE_CPE, TYPE_SCE, TYPE_SCE, TYPE_CPE, TYPE_CPE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6, 7 },
},
{
.layout = AV_CH_LAYOUT_OCTAGONAL,
.num_ele = { 2, 1, 2, 0 },
.pairing = { { 1, 0 }, { 1 }, { 1, 0 }, },
.index = { { 0, 0 }, { 1 }, { 2, 1 } },
.config_map = { 5, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_CPE, TYPE_SCE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6, 7 },
},
{ /* Meant for order 2/mixed ambisonics */
.layout = AV_CH_LAYOUT_OCTAGONAL | AV_CH_TOP_CENTER,
.num_ele = { 2, 2, 2, 0 },
.pairing = { { 1, 0 }, { 1, 0 }, { 1, 0 }, },
.index = { { 0, 0 }, { 1, 1 }, { 2, 2 } },
.config_map = { 6, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_SCE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
},
{ /* Meant for order 2/mixed ambisonics */
.layout = AV_CH_LAYOUT_6POINT0_FRONT | AV_CH_BACK_CENTER |
AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT | AV_CH_TOP_CENTER,
.num_ele = { 2, 2, 2, 0 },
.pairing = { { 1, 1 }, { 1, 0 }, { 1, 0 }, },
.index = { { 0, 1 }, { 2, 0 }, { 3, 1 } },
.config_map = { 6, TYPE_CPE, TYPE_CPE, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_SCE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
},
{
.layout = AV_CH_LAYOUT_HEXADECAGONAL,
.num_ele = { 4, 2, 4, 0 },
.pairing = { { 1, 0, 1, 0 }, { 1, 1 }, { 1, 0, 1, 0 }, },
.index = { { 0, 0, 1, 1 }, { 2, 3 }, { 4, 2, 5, 3 } },
.config_map = { 10, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_CPE, TYPE_CPE, TYPE_SCE, TYPE_CPE, TYPE_SCE },
.reorder_map = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
},
};
/**
* AAC encoder context
*/
typedef struct AACEncContext {
AVClass *av_class;
AACEncOptions options; ///< encoding options
PutBitContext pb;
FFTContext mdct1024; ///< long (1024 samples) frame transform context
FFTContext mdct128; ///< short (128 samples) frame transform context
AVFloatDSPContext *fdsp;
AACPCEInfo pce; ///< PCE data, if needed
float *planar_samples[16]; ///< saved preprocessed input
int profile; ///< copied from avctx
int needs_pce; ///< flag for non-standard layout
LPCContext lpc; ///< used by TNS
int samplerate_index; ///< MPEG-4 samplerate index
int channels; ///< channel count
const uint8_t *reorder_map; ///< lavc to aac reorder map
const uint8_t *chan_map; ///< channel configuration map
ChannelElement *cpe; ///< channel elements
FFPsyContext psy;
struct FFPsyPreprocessContext* psypp;
const AACCoefficientsEncoder *coder;
int cur_channel; ///< current channel for coder context
int random_state;
float lambda;
int last_frame_pb_count; ///< number of bits for the previous frame
float lambda_sum; ///< sum(lambda), for Qvg reporting
int lambda_count; ///< count(lambda), for Qvg reporting
enum RawDataBlockType cur_type; ///< channel group type cur_channel belongs to
AudioFrameQueue afq;
DECLARE_ALIGNED(16, int, qcoefs)[96]; ///< quantized coefficients
DECLARE_ALIGNED(32, float, scoefs)[1024]; ///< scaled coefficients
uint16_t quantize_band_cost_cache_generation;
AACQuantizeBandCostCacheEntry quantize_band_cost_cache[256][128]; ///< memoization area for quantize_band_cost
void (*abs_pow34)(float *out, const float *in, const int size);
void (*quant_bands)(int *out, const float *in, const float *scaled,
int size, int is_signed, int maxval, const float Q34,
const float rounding);
struct {
float *samples;
} buffer;
} AACEncContext;
void ff_aac_dsp_init_x86(AACEncContext *s);
void ff_aac_coder_init_mips(AACEncContext *c);
void ff_quantize_band_cost_cache_init(struct AACEncContext *s);
#endif /* AVCODEC_AACENC_H */

View File

@ -0,0 +1,51 @@
/*
* AAC encoder intensity stereo
* Copyright (C) 2015 Rostislav Pehlivanov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC encoder Intensity Stereo
* @author Rostislav Pehlivanov ( atomnuker gmail com )
*/
#ifndef AVCODEC_AACENC_IS_H
#define AVCODEC_AACENC_IS_H
#include "aacenc.h"
/** Frequency in Hz for lower limit of intensity stereo **/
#define INT_STEREO_LOW_LIMIT 6100
struct AACISError {
int pass; /* 1 if dist2 <= dist1 */
int phase; /* -1 or +1 */
float error; /* fabs(dist1 - dist2) */
float dist1; /* From original coeffs */
float dist2; /* From IS'd coeffs */
float ener01;
};
struct AACISError ff_aac_is_encoding_err(AACEncContext *s, ChannelElement *cpe,
int start, int w, int g, float ener0,
float ener1, float ener01,
int use_pcoeffs, int phase);
void ff_aac_search_for_is(AACEncContext *s, AVCodecContext *avctx, ChannelElement *cpe);
#endif /* AVCODEC_AACENC_IS_H */

View File

@ -0,0 +1,41 @@
/*
* AAC encoder long term prediction extension
* Copyright (C) 2015 Rostislav Pehlivanov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC encoder long term prediction extension
* @author Rostislav Pehlivanov ( atomnuker gmail com )
*/
#ifndef AVCODEC_AACENC_LTP_H
#define AVCODEC_AACENC_LTP_H
#include "aacenc.h"
void ff_aac_encode_ltp_info(AACEncContext *s, SingleChannelElement *sce,
int common_window);
void ff_aac_update_ltp(AACEncContext *s, SingleChannelElement *sce);
void ff_aac_adjust_common_ltp(AACEncContext *s, ChannelElement *cpe);
void ff_aac_ltp_insert_new_frame(AACEncContext *s);
void ff_aac_search_for_ltp(AACEncContext *s, SingleChannelElement *sce,
int common_window);
#endif /* AVCODEC_AACENC_LTP_H */

View File

@ -0,0 +1,47 @@
/*
* AAC encoder main-type prediction
* Copyright (C) 2015 Rostislav Pehlivanov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC encoder main-type prediction
* @author Rostislav Pehlivanov ( atomnuker gmail com )
*/
#ifndef AVCODEC_AACENC_PRED_H
#define AVCODEC_AACENC_PRED_H
#include "aacenc.h"
/* Every predictor group needs to get reset at least once in this many frames */
#define PRED_RESET_FRAME_MIN 240
/* Any frame with less than this amount of frames since last reset is ok */
#define PRED_RESET_MIN 64
/* Raise to filter any low frequency artifacts due to prediction */
#define PRED_SFB_START 10
void ff_aac_apply_main_pred(AACEncContext *s, SingleChannelElement *sce);
void ff_aac_adjust_common_pred(AACEncContext *s, ChannelElement *cpe);
void ff_aac_search_for_pred(AACEncContext *s, SingleChannelElement *sce);
void ff_aac_encode_main_pred(AACEncContext *s, SingleChannelElement *sce);
#endif /* AVCODEC_AACENC_PRED_H */

View File

@ -0,0 +1,283 @@
/*
* AAC encoder quantizer
* Copyright (C) 2015 Rostislav Pehlivanov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC encoder quantizer
* @author Rostislav Pehlivanov ( atomnuker gmail com )
*/
#ifndef AVCODEC_AACENC_QUANTIZATION_H
#define AVCODEC_AACENC_QUANTIZATION_H
#include "aactab.h"
#include "aacenc.h"
#include "aacenctab.h"
#include "aacenc_utils.h"
/**
* Calculate rate distortion cost for quantizing with given codebook
*
* @return quantization distortion
*/
static av_always_inline float quantize_and_encode_band_cost_template(
struct AACEncContext *s,
PutBitContext *pb, const float *in, float *out,
const float *scaled, int size, int scale_idx,
int cb, const float lambda, const float uplim,
int *bits, float *energy, int BT_ZERO, int BT_UNSIGNED,
int BT_PAIR, int BT_ESC, int BT_NOISE, int BT_STEREO,
const float ROUNDING)
{
const int q_idx = POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512;
const float Q = ff_aac_pow2sf_tab [q_idx];
const float Q34 = ff_aac_pow34sf_tab[q_idx];
const float IQ = ff_aac_pow2sf_tab [POW_SF2_ZERO + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];
const float CLIPPED_ESCAPE = 165140.0f*IQ;
int i, j;
float cost = 0;
float qenergy = 0;
const int dim = BT_PAIR ? 2 : 4;
int resbits = 0;
int off;
if (BT_ZERO || BT_NOISE || BT_STEREO) {
for (i = 0; i < size; i++)
cost += in[i]*in[i];
if (bits)
*bits = 0;
if (energy)
*energy = qenergy;
if (out) {
for (i = 0; i < size; i += dim)
for (j = 0; j < dim; j++)
out[i+j] = 0.0f;
}
return cost * lambda;
}
if (!scaled) {
s->abs_pow34(s->scoefs, in, size);
scaled = s->scoefs;
}
s->quant_bands(s->qcoefs, in, scaled, size, !BT_UNSIGNED, aac_cb_maxval[cb], Q34, ROUNDING);
if (BT_UNSIGNED) {
off = 0;
} else {
off = aac_cb_maxval[cb];
}
for (i = 0; i < size; i += dim) {
const float *vec;
int *quants = s->qcoefs + i;
int curidx = 0;
int curbits;
float quantized, rd = 0.0f;
for (j = 0; j < dim; j++) {
curidx *= aac_cb_range[cb];
curidx += quants[j] + off;
}
curbits = ff_aac_spectral_bits[cb-1][curidx];
vec = &ff_aac_codebook_vectors[cb-1][curidx*dim];
if (BT_UNSIGNED) {
for (j = 0; j < dim; j++) {
float t = fabsf(in[i+j]);
float di;
if (BT_ESC && vec[j] == 64.0f) { //FIXME: slow
if (t >= CLIPPED_ESCAPE) {
quantized = CLIPPED_ESCAPE;
curbits += 21;
} else {
int c = av_clip_uintp2(quant(t, Q, ROUNDING), 13);
quantized = c*cbrtf(c)*IQ;
curbits += av_log2(c)*2 - 4 + 1;
}
} else {
quantized = vec[j]*IQ;
}
di = t - quantized;
if (out)
out[i+j] = in[i+j] >= 0 ? quantized : -quantized;
if (vec[j] != 0.0f)
curbits++;
qenergy += quantized*quantized;
rd += di*di;
}
} else {
for (j = 0; j < dim; j++) {
quantized = vec[j]*IQ;
qenergy += quantized*quantized;
if (out)
out[i+j] = quantized;
rd += (in[i+j] - quantized)*(in[i+j] - quantized);
}
}
cost += rd * lambda + curbits;
resbits += curbits;
if (cost >= uplim)
return uplim;
if (pb) {
put_bits(pb, ff_aac_spectral_bits[cb-1][curidx], ff_aac_spectral_codes[cb-1][curidx]);
if (BT_UNSIGNED)
for (j = 0; j < dim; j++)
if (ff_aac_codebook_vectors[cb-1][curidx*dim+j] != 0.0f)
put_bits(pb, 1, in[i+j] < 0.0f);
if (BT_ESC) {
for (j = 0; j < 2; j++) {
if (ff_aac_codebook_vectors[cb-1][curidx*2+j] == 64.0f) {
int coef = av_clip_uintp2(quant(fabsf(in[i+j]), Q, ROUNDING), 13);
int len = av_log2(coef);
put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
put_sbits(pb, len, coef);
}
}
}
}
}
if (bits)
*bits = resbits;
if (energy)
*energy = qenergy;
return cost;
}
static inline float quantize_and_encode_band_cost_NONE(struct AACEncContext *s, PutBitContext *pb,
const float *in, float *quant, const float *scaled,
int size, int scale_idx, int cb,
const float lambda, const float uplim,
int *bits, float *energy) {
av_assert0(0);
return 0.0f;
}
#define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, BT_NOISE, BT_STEREO, ROUNDING) \
static float quantize_and_encode_band_cost_ ## NAME( \
struct AACEncContext *s, \
PutBitContext *pb, const float *in, float *quant, \
const float *scaled, int size, int scale_idx, \
int cb, const float lambda, const float uplim, \
int *bits, float *energy) { \
return quantize_and_encode_band_cost_template( \
s, pb, in, quant, scaled, size, scale_idx, \
BT_ESC ? ESC_BT : cb, lambda, uplim, bits, energy, \
BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, BT_NOISE, BT_STEREO, \
ROUNDING); \
}
QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO, 1, 0, 0, 0, 0, 0, ROUND_STANDARD)
QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD, 0, 0, 0, 0, 0, 0, ROUND_STANDARD)
QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD, 0, 1, 0, 0, 0, 0, ROUND_STANDARD)
QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR, 0, 0, 1, 0, 0, 0, ROUND_STANDARD)
QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR, 0, 1, 1, 0, 0, 0, ROUND_STANDARD)
QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC, 0, 1, 1, 1, 0, 0, ROUND_STANDARD)
QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC_RTZ, 0, 1, 1, 1, 0, 0, ROUND_TO_ZERO)
QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NOISE, 0, 0, 0, 0, 1, 0, ROUND_STANDARD)
QUANTIZE_AND_ENCODE_BAND_COST_FUNC(STEREO,0, 0, 0, 0, 0, 1, ROUND_STANDARD)
static float (*const quantize_and_encode_band_cost_arr[])(
struct AACEncContext *s,
PutBitContext *pb, const float *in, float *quant,
const float *scaled, int size, int scale_idx,
int cb, const float lambda, const float uplim,
int *bits, float *energy) = {
quantize_and_encode_band_cost_ZERO,
quantize_and_encode_band_cost_SQUAD,
quantize_and_encode_band_cost_SQUAD,
quantize_and_encode_band_cost_UQUAD,
quantize_and_encode_band_cost_UQUAD,
quantize_and_encode_band_cost_SPAIR,
quantize_and_encode_band_cost_SPAIR,
quantize_and_encode_band_cost_UPAIR,
quantize_and_encode_band_cost_UPAIR,
quantize_and_encode_band_cost_UPAIR,
quantize_and_encode_band_cost_UPAIR,
quantize_and_encode_band_cost_ESC,
quantize_and_encode_band_cost_NONE, /* CB 12 doesn't exist */
quantize_and_encode_band_cost_NOISE,
quantize_and_encode_band_cost_STEREO,
quantize_and_encode_band_cost_STEREO,
};
static float (*const quantize_and_encode_band_cost_rtz_arr[])(
struct AACEncContext *s,
PutBitContext *pb, const float *in, float *quant,
const float *scaled, int size, int scale_idx,
int cb, const float lambda, const float uplim,
int *bits, float *energy) = {
quantize_and_encode_band_cost_ZERO,
quantize_and_encode_band_cost_SQUAD,
quantize_and_encode_band_cost_SQUAD,
quantize_and_encode_band_cost_UQUAD,
quantize_and_encode_band_cost_UQUAD,
quantize_and_encode_band_cost_SPAIR,
quantize_and_encode_band_cost_SPAIR,
quantize_and_encode_band_cost_UPAIR,
quantize_and_encode_band_cost_UPAIR,
quantize_and_encode_band_cost_UPAIR,
quantize_and_encode_band_cost_UPAIR,
quantize_and_encode_band_cost_ESC_RTZ,
quantize_and_encode_band_cost_NONE, /* CB 12 doesn't exist */
quantize_and_encode_band_cost_NOISE,
quantize_and_encode_band_cost_STEREO,
quantize_and_encode_band_cost_STEREO,
};
#define quantize_and_encode_band_cost( \
s, pb, in, quant, scaled, size, scale_idx, cb, \
lambda, uplim, bits, energy, rtz) \
((rtz) ? quantize_and_encode_band_cost_rtz_arr : quantize_and_encode_band_cost_arr)[cb]( \
s, pb, in, quant, scaled, size, scale_idx, cb, \
lambda, uplim, bits, energy)
static inline float quantize_band_cost(struct AACEncContext *s, const float *in,
const float *scaled, int size, int scale_idx,
int cb, const float lambda, const float uplim,
int *bits, float *energy, int rtz)
{
return quantize_and_encode_band_cost(s, NULL, in, NULL, scaled, size, scale_idx,
cb, lambda, uplim, bits, energy, rtz);
}
static inline int quantize_band_cost_bits(struct AACEncContext *s, const float *in,
const float *scaled, int size, int scale_idx,
int cb, const float lambda, const float uplim,
int *bits, float *energy, int rtz)
{
int auxbits;
quantize_and_encode_band_cost(s, NULL, in, NULL, scaled, size, scale_idx,
cb, 0.0f, uplim, &auxbits, energy, rtz);
if (bits) {
*bits = auxbits;
}
return auxbits;
}
static inline void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb,
const float *in, float *out, int size, int scale_idx,
int cb, const float lambda, int rtz)
{
quantize_and_encode_band_cost(s, pb, in, out, NULL, size, scale_idx, cb, lambda,
INFINITY, NULL, NULL, rtz);
}
#include "aacenc_quantization_misc.h"
#endif /* AVCODEC_AACENC_QUANTIZATION_H */

View File

@ -0,0 +1,53 @@
/*
* AAC encoder quantization
* Copyright (C) 2015 Claudio Freire
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC encoder quantization misc reusable function templates
* @author Claudio Freire ( klaussfreire gmail com )
*/
#ifndef AVCODEC_AACENC_QUANTIZATION_MISC_H
#define AVCODEC_AACENC_QUANTIZATION_MISC_H
static inline float quantize_band_cost_cached(struct AACEncContext *s, int w, int g, const float *in,
const float *scaled, int size, int scale_idx,
int cb, const float lambda, const float uplim,
int *bits, float *energy, int rtz)
{
AACQuantizeBandCostCacheEntry *entry;
av_assert1(scale_idx >= 0 && scale_idx < 256);
entry = &s->quantize_band_cost_cache[scale_idx][w*16+g];
if (entry->generation != s->quantize_band_cost_cache_generation || entry->cb != cb || entry->rtz != rtz) {
entry->rd = quantize_band_cost(s, in, scaled, size, scale_idx,
cb, lambda, uplim, &entry->bits, &entry->energy, rtz);
entry->cb = cb;
entry->rtz = rtz;
entry->generation = s->quantize_band_cost_cache_generation;
}
if (bits)
*bits = entry->bits;
if (energy)
*energy = entry->energy;
return entry->rd;
}
#endif /* AVCODEC_AACENC_QUANTIZATION_MISC_H */

View File

@ -0,0 +1,37 @@
/*
* AAC encoder TNS
* Copyright (C) 2015 Rostislav Pehlivanov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC encoder temporal noise shaping
* @author Rostislav Pehlivanov ( atomnuker gmail com )
*/
#ifndef AVCODEC_AACENC_TNS_H
#define AVCODEC_AACENC_TNS_H
#include "aacenc.h"
void ff_aac_encode_tns_info(AACEncContext *s, SingleChannelElement *sce);
void ff_aac_apply_tns(AACEncContext *s, SingleChannelElement *sce);
void ff_aac_search_for_tns(AACEncContext *s, SingleChannelElement *sce);
#endif /* AVCODEC_AACENC_TNS_H */

View File

@ -0,0 +1,279 @@
/*
* AAC encoder utilities
* Copyright (C) 2015 Rostislav Pehlivanov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC encoder utilities
* @author Rostislav Pehlivanov ( atomnuker gmail com )
*/
#ifndef AVCODEC_AACENC_UTILS_H
#define AVCODEC_AACENC_UTILS_H
#include "libavutil/ffmath.h"
#include "aac.h"
#include "aacenctab.h"
#include "aactab.h"
#define ROUND_STANDARD 0.4054f
#define ROUND_TO_ZERO 0.1054f
#define C_QUANT 0.4054f
static inline void abs_pow34_v(float *out, const float *in, const int size)
{
int i;
for (i = 0; i < size; i++) {
float a = fabsf(in[i]);
out[i] = sqrtf(a * sqrtf(a));
}
}
static inline float pos_pow34(float a)
{
return sqrtf(a * sqrtf(a));
}
/**
* Quantize one coefficient.
* @return absolute value of the quantized coefficient
* @see 3GPP TS26.403 5.6.2 "Scalefactor determination"
*/
static inline int quant(float coef, const float Q, const float rounding)
{
float a = coef * Q;
return sqrtf(a * sqrtf(a)) + rounding;
}
static inline void quantize_bands(int *out, const float *in, const float *scaled,
int size, int is_signed, int maxval, const float Q34,
const float rounding)
{
int i;
for (i = 0; i < size; i++) {
float qc = scaled[i] * Q34;
int tmp = (int)FFMIN(qc + rounding, (float)maxval);
if (is_signed && in[i] < 0.0f) {
tmp = -tmp;
}
out[i] = tmp;
}
}
static inline float find_max_val(int group_len, int swb_size, const float *scaled)
{
float maxval = 0.0f;
int w2, i;
for (w2 = 0; w2 < group_len; w2++) {
for (i = 0; i < swb_size; i++) {
maxval = FFMAX(maxval, scaled[w2*128+i]);
}
}
return maxval;
}
static inline int find_min_book(float maxval, int sf)
{
float Q34 = ff_aac_pow34sf_tab[POW_SF2_ZERO - sf + SCALE_ONE_POS - SCALE_DIV_512];
int qmaxval, cb;
qmaxval = maxval * Q34 + C_QUANT;
if (qmaxval >= (FF_ARRAY_ELEMS(aac_maxval_cb)))
cb = 11;
else
cb = aac_maxval_cb[qmaxval];
return cb;
}
static inline float find_form_factor(int group_len, int swb_size, float thresh,
const float *scaled, float nzslope) {
const float iswb_size = 1.0f / swb_size;
const float iswb_sizem1 = 1.0f / (swb_size - 1);
const float ethresh = thresh;
float form = 0.0f, weight = 0.0f;
int w2, i;
for (w2 = 0; w2 < group_len; w2++) {
float e = 0.0f, e2 = 0.0f, var = 0.0f, maxval = 0.0f;
float nzl = 0;
for (i = 0; i < swb_size; i++) {
float s = fabsf(scaled[w2*128+i]);
maxval = FFMAX(maxval, s);
e += s;
e2 += s *= s;
/* We really don't want a hard non-zero-line count, since
* even below-threshold lines do add up towards band spectral power.
* So, fall steeply towards zero, but smoothly
*/
if (s >= ethresh) {
nzl += 1.0f;
} else {
if (nzslope == 2.f)
nzl += (s / ethresh) * (s / ethresh);
else
nzl += ff_fast_powf(s / ethresh, nzslope);
}
}
if (e2 > thresh) {
float frm;
e *= iswb_size;
/** compute variance */
for (i = 0; i < swb_size; i++) {
float d = fabsf(scaled[w2*128+i]) - e;
var += d*d;
}
var = sqrtf(var * iswb_sizem1);
e2 *= iswb_size;
frm = e / FFMIN(e+4*var,maxval);
form += e2 * sqrtf(frm) / FFMAX(0.5f,nzl);
weight += e2;
}
}
if (weight > 0) {
return form / weight;
} else {
return 1.0f;
}
}
/** Return the minimum scalefactor where the quantized coef does not clip. */
static inline uint8_t coef2minsf(float coef)
{
return av_clip_uint8(log2f(coef)*4 - 69 + SCALE_ONE_POS - SCALE_DIV_512);
}
/** Return the maximum scalefactor where the quantized coef is not zero. */
static inline uint8_t coef2maxsf(float coef)
{
return av_clip_uint8(log2f(coef)*4 + 6 + SCALE_ONE_POS - SCALE_DIV_512);
}
/*
* Returns the closest possible index to an array of float values, given a value.
*/
static inline int quant_array_idx(const float val, const float *arr, const int num)
{
int i, index = 0;
float quant_min_err = INFINITY;
for (i = 0; i < num; i++) {
float error = (val - arr[i])*(val - arr[i]);
if (error < quant_min_err) {
quant_min_err = error;
index = i;
}
}
return index;
}
/**
* approximates exp10f(-3.0f*(0.5f + 0.5f * cosf(FFMIN(b,15.5f) / 15.5f)))
*/
static av_always_inline float bval2bmax(float b)
{
return 0.001f + 0.0035f * (b*b*b) / (15.5f*15.5f*15.5f);
}
/*
* Compute a nextband map to be used with SF delta constraint utilities.
* The nextband array should contain 128 elements, and positions that don't
* map to valid, nonzero bands of the form w*16+g (with w being the initial
* window of the window group, only) are left indetermined.
*/
static inline void ff_init_nextband_map(const SingleChannelElement *sce, uint8_t *nextband)
{
unsigned char prevband = 0;
int w, g;
/** Just a safe default */
for (g = 0; g < 128; g++)
nextband[g] = g;
/** Now really navigate the nonzero band chain */
for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
for (g = 0; g < sce->ics.num_swb; g++) {
if (!sce->zeroes[w*16+g] && sce->band_type[w*16+g] < RESERVED_BT)
prevband = nextband[prevband] = w*16+g;
}
}
nextband[prevband] = prevband; /* terminate */
}
/*
* Updates nextband to reflect a removed band (equivalent to
* calling ff_init_nextband_map after marking a band as zero)
*/
static inline void ff_nextband_remove(uint8_t *nextband, int prevband, int band)
{
nextband[prevband] = nextband[band];
}
/*
* Checks whether the specified band could be removed without inducing
* scalefactor delta that violates SF delta encoding constraints.
* prev_sf has to be the scalefactor of the previous nonzero, nonspecial
* band, in encoding order, or negative if there was no such band.
*/
static inline int ff_sfdelta_can_remove_band(const SingleChannelElement *sce,
const uint8_t *nextband, int prev_sf, int band)
{
return prev_sf >= 0
&& sce->sf_idx[nextband[band]] >= (prev_sf - SCALE_MAX_DIFF)
&& sce->sf_idx[nextband[band]] <= (prev_sf + SCALE_MAX_DIFF);
}
/*
* Checks whether the specified band's scalefactor could be replaced
* with another one without violating SF delta encoding constraints.
* prev_sf has to be the scalefactor of the previous nonzero, nonsepcial
* band, in encoding order, or negative if there was no such band.
*/
static inline int ff_sfdelta_can_replace(const SingleChannelElement *sce,
const uint8_t *nextband, int prev_sf, int new_sf, int band)
{
return new_sf >= (prev_sf - SCALE_MAX_DIFF)
&& new_sf <= (prev_sf + SCALE_MAX_DIFF)
&& sce->sf_idx[nextband[band]] >= (new_sf - SCALE_MAX_DIFF)
&& sce->sf_idx[nextband[band]] <= (new_sf + SCALE_MAX_DIFF);
}
/**
* linear congruential pseudorandom number generator
*
* @param previous_val pointer to the current state of the generator
*
* @return Returns a 32-bit pseudorandom integer
*/
static av_always_inline int lcg_random(unsigned previous_val)
{
union { unsigned u; int s; } v = { previous_val * 1664525u + 1013904223 };
return v.s;
}
#define ERROR_IF(cond, ...) \
if (cond) { \
av_log(avctx, AV_LOG_ERROR, __VA_ARGS__); \
return AVERROR(EINVAL); \
}
#define WARN_IF(cond, ...) \
if (cond) { \
av_log(avctx, AV_LOG_WARNING, __VA_ARGS__); \
}
#endif /* AVCODEC_AACENC_UTILS_H */

View File

@ -0,0 +1,139 @@
/*
* AAC encoder data
* Copyright (c) 2015 Rostislav Pehlivanov ( atomnuker gmail com )
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC encoder data
* @author Rostislav Pehlivanov ( atomnuker gmail com )
*/
#ifndef AVCODEC_AACENCTAB_H
#define AVCODEC_AACENCTAB_H
#include "aac.h"
/** Total number of usable codebooks **/
#define CB_TOT 12
/** Total number of codebooks, including special ones **/
#define CB_TOT_ALL 15
#define AAC_MAX_CHANNELS 16
extern const uint8_t *ff_aac_swb_size_1024[];
extern const int ff_aac_swb_size_1024_len;
extern const uint8_t *ff_aac_swb_size_128[];
extern const int ff_aac_swb_size_128_len;
/* Supported layouts without using a PCE */
static const int64_t aac_normal_chan_layouts[7] = {
AV_CH_LAYOUT_MONO,
AV_CH_LAYOUT_STEREO,
AV_CH_LAYOUT_SURROUND,
AV_CH_LAYOUT_4POINT0,
AV_CH_LAYOUT_5POINT0_BACK,
AV_CH_LAYOUT_5POINT1_BACK,
AV_CH_LAYOUT_7POINT1,
};
/** default channel configurations */
static const uint8_t aac_chan_configs[AAC_MAX_CHANNELS][6] = {
{1, TYPE_SCE}, // 1 channel - single channel element
{1, TYPE_CPE}, // 2 channels - channel pair
{2, TYPE_SCE, TYPE_CPE}, // 3 channels - center + stereo
{3, TYPE_SCE, TYPE_CPE, TYPE_SCE}, // 4 channels - front center + stereo + back center
{3, TYPE_SCE, TYPE_CPE, TYPE_CPE}, // 5 channels - front center + stereo + back stereo
{4, TYPE_SCE, TYPE_CPE, TYPE_CPE, TYPE_LFE}, // 6 channels - front center + stereo + back stereo + LFE
{0}, // 7 channels - invalid without PCE
{5, TYPE_SCE, TYPE_CPE, TYPE_CPE, TYPE_CPE, TYPE_LFE}, // 8 channels - front center + front stereo + side stereo + back stereo + LFE
};
/**
* Table to remap channels from libavcodec's default order to AAC order.
*/
static const uint8_t aac_chan_maps[AAC_MAX_CHANNELS][AAC_MAX_CHANNELS] = {
{ 0 },
{ 0, 1 },
{ 2, 0, 1 },
{ 2, 0, 1, 3 },
{ 2, 0, 1, 3, 4 },
{ 2, 0, 1, 4, 5, 3 },
{ 0 },
{ 2, 0, 1, 6, 7, 4, 5, 3 },
};
/* duplicated from avpriv_mpeg4audio_sample_rates to avoid shared build
* failures */
static const int mpeg4audio_sample_rates[16] = {
96000, 88200, 64000, 48000, 44100, 32000,
24000, 22050, 16000, 12000, 11025, 8000, 7350
};
/** bits needed to code codebook run value for long windows */
static const uint8_t run_value_bits_long[64] = {
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 15
};
/** bits needed to code codebook run value for short windows */
static const uint8_t run_value_bits_short[16] = {
3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 6, 6, 9
};
/* TNS starting SFBs for long and short windows */
static const uint8_t tns_min_sfb_short[16] = {
2, 2, 2, 3, 3, 4, 6, 6, 8, 10, 10, 12, 12, 12, 12, 12
};
static const uint8_t tns_min_sfb_long[16] = {
12, 13, 15, 16, 17, 20, 25, 26, 24, 28, 30, 31, 31, 31, 31, 31
};
static const uint8_t * const tns_min_sfb[2] = {
tns_min_sfb_long, tns_min_sfb_short
};
static const uint8_t * const run_value_bits[2] = {
run_value_bits_long, run_value_bits_short
};
/** Map to convert values from BandCodingPath index to a codebook index **/
static const uint8_t aac_cb_out_map[CB_TOT_ALL] = {0,1,2,3,4,5,6,7,8,9,10,11,13,14,15};
/** Inverse map to convert from codebooks to BandCodingPath indices **/
static const uint8_t aac_cb_in_map[CB_TOT_ALL+1] = {0,1,2,3,4,5,6,7,8,9,10,11,0,12,13,14};
static const uint8_t aac_cb_range [12] = {0, 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17};
static const uint8_t aac_cb_maxval[12] = {0, 1, 1, 2, 2, 4, 4, 7, 7, 12, 12, 16};
static const unsigned char aac_maxval_cb[] = {
0, 1, 3, 5, 5, 7, 7, 7, 9, 9, 9, 9, 9, 11
};
static const int aacenc_profiles[] = {
FF_PROFILE_AAC_MAIN,
FF_PROFILE_AAC_LOW,
FF_PROFILE_AAC_LTP,
FF_PROFILE_MPEG2_AAC_LOW,
};
#endif /* AVCODEC_AACENCTAB_H */

View File

@ -0,0 +1,86 @@
/*
* MPEG-4 Parametric Stereo definitions and declarations
* Copyright (c) 2010 Alex Converse <alex.converse@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AACPS_H
#define AVCODEC_AACPS_H
#include <stdint.h>
#include "aacpsdsp.h"
#include "avcodec.h"
#include "get_bits.h"
#define PS_MAX_NUM_ENV 5
#define PS_MAX_NR_IIDICC 34
#define PS_MAX_NR_IPDOPD 17
#define PS_MAX_SSB 91
#define PS_MAX_AP_BANDS 50
#define PS_QMF_TIME_SLOTS 32
#define PS_MAX_DELAY 14
#define PS_AP_LINKS 3
#define PS_MAX_AP_DELAY 5
typedef struct PSContext {
int start;
int enable_iid;
int iid_quant;
int nr_iid_par;
int nr_ipdopd_par;
int enable_icc;
int icc_mode;
int nr_icc_par;
int enable_ext;
int frame_class;
int num_env_old;
int num_env;
int enable_ipdopd;
int border_position[PS_MAX_NUM_ENV+1];
int8_t iid_par[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC]; ///< Inter-channel Intensity Difference Parameters
int8_t icc_par[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC]; ///< Inter-Channel Coherence Parameters
/* ipd/opd is iid/icc sized so that the same functions can handle both */
int8_t ipd_par[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC]; ///< Inter-channel Phase Difference Parameters
int8_t opd_par[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC]; ///< Overall Phase Difference Parameters
int is34bands;
int is34bands_old;
DECLARE_ALIGNED(16, INTFLOAT, in_buf)[5][44][2];
DECLARE_ALIGNED(16, INTFLOAT, delay)[PS_MAX_SSB][PS_QMF_TIME_SLOTS + PS_MAX_DELAY][2];
DECLARE_ALIGNED(16, INTFLOAT, ap_delay)[PS_MAX_AP_BANDS][PS_AP_LINKS][PS_QMF_TIME_SLOTS + PS_MAX_AP_DELAY][2];
DECLARE_ALIGNED(16, INTFLOAT, peak_decay_nrg)[34];
DECLARE_ALIGNED(16, INTFLOAT, power_smooth)[34];
DECLARE_ALIGNED(16, INTFLOAT, peak_decay_diff_smooth)[34];
DECLARE_ALIGNED(16, INTFLOAT, H11)[2][PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC];
DECLARE_ALIGNED(16, INTFLOAT, H12)[2][PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC];
DECLARE_ALIGNED(16, INTFLOAT, H21)[2][PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC];
DECLARE_ALIGNED(16, INTFLOAT, H22)[2][PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC];
DECLARE_ALIGNED(16, INTFLOAT, Lbuf)[91][32][2];
DECLARE_ALIGNED(16, INTFLOAT, Rbuf)[91][32][2];
int8_t opd_hist[PS_MAX_NR_IIDICC];
int8_t ipd_hist[PS_MAX_NR_IIDICC];
PSDSPContext dsp;
} PSContext;
void AAC_RENAME(ff_ps_init)(void);
void AAC_RENAME(ff_ps_ctx_init)(PSContext *ps);
int AAC_RENAME(ff_ps_read_data)(AVCodecContext *avctx, GetBitContext *gb, PSContext *ps, int bits_left);
int AAC_RENAME(ff_ps_apply)(AVCodecContext *avctx, PSContext *ps, INTFLOAT L[2][38][64], INTFLOAT R[2][38][64], int top);
#endif /* AVCODEC_AACPS_H */

View File

@ -0,0 +1,403 @@
/*
* Header file for hardcoded Parametric Stereo tables
*
* Copyright (c) 2010 Alex Converse <alex.converse@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Note: Rounding-to-nearest used unless otherwise stated
*
*/
#ifndef AVCODEC_AACPS_FIXED_TABLEGEN_H
#define AVCODEC_AACPS_FIXED_TABLEGEN_H
#include <math.h>
#include <stdint.h>
#if CONFIG_HARDCODED_TABLES
#define ps_tableinit()
#define TABLE_CONST const
#include "libavcodec/aacps_fixed_tables.h"
#else
#include "libavutil/common.h"
#include "libavutil/mathematics.h"
#include "libavutil/mem.h"
#include "aac_defines.h"
#include "libavutil/softfloat.h"
#define NR_ALLPASS_BANDS20 30
#define NR_ALLPASS_BANDS34 50
#define PS_AP_LINKS 3
#define TABLE_CONST
static int pd_re_smooth[8*8*8];
static int pd_im_smooth[8*8*8];
static int HA[46][8][4];
static int HB[46][8][4];
static DECLARE_ALIGNED(16, int, f20_0_8) [ 8][8][2];
static DECLARE_ALIGNED(16, int, f34_0_12)[12][8][2];
static DECLARE_ALIGNED(16, int, f34_1_8) [ 8][8][2];
static DECLARE_ALIGNED(16, int, f34_2_4) [ 4][8][2];
static TABLE_CONST DECLARE_ALIGNED(16, int, Q_fract_allpass)[2][50][3][2];
static DECLARE_ALIGNED(16, int, phi_fract)[2][50][2];
static const int g0_Q8[] = {
Q31(0.00746082949812f), Q31(0.02270420949825f), Q31(0.04546865930473f), Q31(0.07266113929591f),
Q31(0.09885108575264f), Q31(0.11793710567217f), Q31(0.125f)
};
static const int g0_Q12[] = {
Q31(0.04081179924692f), Q31(0.03812810994926f), Q31(0.05144908135699f), Q31(0.06399831151592f),
Q31(0.07428313801106f), Q31(0.08100347892914f), Q31(0.08333333333333f)
};
static const int g1_Q8[] = {
Q31(0.01565675600122f), Q31(0.03752716391991f), Q31(0.05417891378782f), Q31(0.08417044116767f),
Q31(0.10307344158036f), Q31(0.12222452249753f), Q31(0.125f)
};
static const int g2_Q4[] = {
Q31(-0.05908211155639f), Q31(-0.04871498374946f), Q31(0.0f), Q31(0.07778723915851f),
Q31( 0.16486303567403f), Q31( 0.23279856662996f), Q31(0.25f)
};
static const int sintbl_4[4] = { 0, 1073741824, 0, -1073741824 };
static const int costbl_4[4] = { 1073741824, 0, -1073741824, 0 };
static const int sintbl_8[8] = { 0, 759250125, 1073741824, 759250125,
0, -759250125, -1073741824, -759250125 };
static const int costbl_8[8] = { 1073741824, 759250125, 0, -759250125,
-1073741824, -759250125, 0, 759250125 };
static const int sintbl_12[12] = { 0, 536870912, 929887697, 1073741824,
929887697, 536870912, 0, -536870912,
-929887697, -1073741824, -929887697, -536870912 };
static const int costbl_12[12] = { 1073741824, 929887697, 536870912, 0,
-536870912, -929887697, -1073741824, -929887697,
-536870912, 0, 536870912, 929887697 };
static void make_filters_from_proto(int (*filter)[8][2], const int *proto, int bands)
{
const int *sinptr, *cosptr;
int s, c, sinhalf, coshalf;
int q, n;
if (bands == 4) {
sinptr = sintbl_4;
cosptr = costbl_4;
sinhalf = 759250125;
coshalf = 759250125;
} else if (bands == 8) {
sinptr = sintbl_8;
cosptr = costbl_8;
sinhalf = 410903207;
coshalf = 992008094;
} else {
sinptr = sintbl_12;
cosptr = costbl_12;
sinhalf = 277904834;
coshalf = 1037154959;
}
for (q = 0; q < bands; q++) {
for (n = 0; n < 7; n++) {
int theta = (q*(n-6) + (n>>1) - 3) % bands;
if (theta < 0)
theta += bands;
s = sinptr[theta];
c = cosptr[theta];
if (n & 1) {
theta = (int)(((int64_t)c * coshalf - (int64_t)s * sinhalf + 0x20000000) >> 30);
s = (int)(((int64_t)s * coshalf + (int64_t)c * sinhalf + 0x20000000) >> 30);
c = theta;
}
filter[q][n][0] = (int)(((int64_t)proto[n] * c + 0x20000000) >> 30);
filter[q][n][1] = -(int)(((int64_t)proto[n] * s + 0x20000000) >> 30);
}
}
}
static void ps_tableinit(void)
{
static const int ipdopd_sin[] = { Q30(0), Q30(M_SQRT1_2), Q30(1), Q30( M_SQRT1_2), Q30( 0), Q30(-M_SQRT1_2), Q30(-1), Q30(-M_SQRT1_2) };
static const int ipdopd_cos[] = { Q30(1), Q30(M_SQRT1_2), Q30(0), Q30(-M_SQRT1_2), Q30(-1), Q30(-M_SQRT1_2), Q30( 0), Q30( M_SQRT1_2) };
int pd0, pd1, pd2;
int idx;
static const int alpha_tab[] =
{
Q30(1.5146213770f/M_PI), Q30(1.5181334019f/M_PI), Q30(1.5234849453f/M_PI), Q30(1.5369486809f/M_PI), Q30(1.5500687361f/M_PI), Q30(1.5679757595f/M_PI),
Q30(1.4455626011f/M_PI), Q30(1.4531552792f/M_PI), Q30(1.4648091793f/M_PI), Q30(1.4945238829f/M_PI), Q30(1.5239057541f/M_PI), Q30(1.5644006729f/M_PI),
Q30(1.3738563061f/M_PI), Q30(1.3851221800f/M_PI), Q30(1.4026404619f/M_PI), Q30(1.4484288692f/M_PI), Q30(1.4949874878f/M_PI), Q30(1.5604078770f/M_PI),
Q30(1.2645189762f/M_PI), Q30(1.2796478271f/M_PI), Q30(1.3038636446f/M_PI), Q30(1.3710125685f/M_PI), Q30(1.4443849325f/M_PI), Q30(1.5532352924f/M_PI),
Q30(1.1507037878f/M_PI), Q30(1.1669205427f/M_PI), Q30(1.1938756704f/M_PI), Q30(1.2754167318f/M_PI), Q30(1.3761177063f/M_PI), Q30(1.5429240465f/M_PI),
Q30(1.0079245567f/M_PI), Q30(1.0208238363f/M_PI), Q30(1.0433073044f/M_PI), Q30(1.1208510399f/M_PI), Q30(1.2424604893f/M_PI), Q30(1.5185726881f/M_PI),
Q30(0.8995233774f/M_PI), Q30(0.9069069624f/M_PI), Q30(0.9201194048f/M_PI), Q30(0.9698365927f/M_PI), Q30(1.0671583414f/M_PI), Q30(1.4647934437f/M_PI),
Q30(0.7853981853f/M_PI), Q30(0.7853981853f/M_PI), Q30(0.7853981853f/M_PI), Q30(0.7853981853f/M_PI), Q30(0.7853981853f/M_PI), Q30(0.7853981853f/M_PI),
Q30(0.6712729335f/M_PI), Q30(0.6638893485f/M_PI), Q30(0.6506769061f/M_PI), Q30(0.6009597182f/M_PI), Q30(0.5036380291f/M_PI), Q30(0.1060028747f/M_PI),
Q30(0.5628717542f/M_PI), Q30(0.5499725342f/M_PI), Q30(0.5274890065f/M_PI), Q30(0.4499453008f/M_PI), Q30(0.3283358216f/M_PI), Q30(0.0522236861f/M_PI),
Q30(0.4200925827f/M_PI), Q30(0.4038758278f/M_PI), Q30(0.3769206405f/M_PI), Q30(0.2953795493f/M_PI), Q30(0.1946786791f/M_PI), Q30(0.0278722942f/M_PI),
Q30(0.3062773645f/M_PI), Q30(0.2911485136f/M_PI), Q30(0.2669326365f/M_PI), Q30(0.1997837722f/M_PI), Q30(0.1264114529f/M_PI), Q30(0.0175609849f/M_PI),
Q30(0.1969399750f/M_PI), Q30(0.1856741160f/M_PI), Q30(0.1681558639f/M_PI), Q30(0.1223674342f/M_PI), Q30(0.0758088827f/M_PI), Q30(0.0103884479f/M_PI),
Q30(0.1252337098f/M_PI), Q30(0.1176410317f/M_PI), Q30(0.1059871912f/M_PI), Q30(0.0762724727f/M_PI), Q30(0.0468905345f/M_PI), Q30(0.0063956482f/M_PI),
Q30(0.0561749674f/M_PI), Q30(0.0526629239f/M_PI), Q30(0.0473113805f/M_PI), Q30(0.0338476151f/M_PI), Q30(0.0207276177f/M_PI), Q30(0.0028205961f/M_PI),
Q30(1.5676341057f/M_PI), Q30(1.5678333044f/M_PI), Q30(1.5681363344f/M_PI), Q30(1.5688960552f/M_PI), Q30(1.5696337223f/M_PI), Q30(1.5706381798f/M_PI),
Q30(1.5651730299f/M_PI), Q30(1.5655272007f/M_PI), Q30(1.5660660267f/M_PI), Q30(1.5674170256f/M_PI), Q30(1.5687289238f/M_PI), Q30(1.5705151558f/M_PI),
Q30(1.5607966185f/M_PI), Q30(1.5614265203f/M_PI), Q30(1.5623844862f/M_PI), Q30(1.5647867918f/M_PI), Q30(1.5671195984f/M_PI), Q30(1.5702962875f/M_PI),
Q30(1.5530153513f/M_PI), Q30(1.5541347265f/M_PI), Q30(1.5558375120f/M_PI), Q30(1.5601085424f/M_PI), Q30(1.5642569065f/M_PI), Q30(1.5699069500f/M_PI),
Q30(1.5391840935f/M_PI), Q30(1.5411708355f/M_PI), Q30(1.5441943407f/M_PI), Q30(1.5517836809f/M_PI), Q30(1.5591609478f/M_PI), Q30(1.5692136288f/M_PI),
Q30(1.5146213770f/M_PI), Q30(1.5181334019f/M_PI), Q30(1.5234849453f/M_PI), Q30(1.5369486809f/M_PI), Q30(1.5500687361f/M_PI), Q30(1.5679757595f/M_PI),
Q30(1.4915299416f/M_PI), Q30(1.4964480400f/M_PI), Q30(1.5039558411f/M_PI), Q30(1.5229074955f/M_PI), Q30(1.5414420366f/M_PI), Q30(1.5667995214f/M_PI),
Q30(1.4590617418f/M_PI), Q30(1.4658898115f/M_PI), Q30(1.4763505459f/M_PI), Q30(1.5029321909f/M_PI), Q30(1.5291173458f/M_PI), Q30(1.5651149750f/M_PI),
Q30(1.4136143923f/M_PI), Q30(1.4229322672f/M_PI), Q30(1.4373078346f/M_PI), Q30(1.4743183851f/M_PI), Q30(1.5113102198f/M_PI), Q30(1.5626684427f/M_PI),
Q30(1.3505556583f/M_PI), Q30(1.3628427982f/M_PI), Q30(1.3820509911f/M_PI), Q30(1.4327841997f/M_PI), Q30(1.4850014448f/M_PI), Q30(1.5590143204f/M_PI),
Q30(1.2645189762f/M_PI), Q30(1.2796478271f/M_PI), Q30(1.3038636446f/M_PI), Q30(1.3710125685f/M_PI), Q30(1.4443849325f/M_PI), Q30(1.5532352924f/M_PI),
Q30(1.1919227839f/M_PI), Q30(1.2081253529f/M_PI), Q30(1.2346779108f/M_PI), Q30(1.3123005629f/M_PI), Q30(1.4034168720f/M_PI), Q30(1.5471596718f/M_PI),
Q30(1.1061993837f/M_PI), Q30(1.1219338179f/M_PI), Q30(1.1484941244f/M_PI), Q30(1.2320860624f/M_PI), Q30(1.3421301842f/M_PI), Q30(1.5373806953f/M_PI),
Q30(1.0079245567f/M_PI), Q30(1.0208238363f/M_PI), Q30(1.0433073044f/M_PI), Q30(1.1208510399f/M_PI), Q30(1.2424604893f/M_PI), Q30(1.5185726881f/M_PI),
Q30(0.8995233774f/M_PI), Q30(0.9069069624f/M_PI), Q30(0.9201194048f/M_PI), Q30(0.9698365927f/M_PI), Q30(1.0671583414f/M_PI), Q30(1.4647934437f/M_PI),
Q30(0.7853981853f/M_PI), Q30(0.7853981853f/M_PI), Q30(0.7853981853f/M_PI), Q30(0.7853981853f/M_PI), Q30(0.7853981853f/M_PI), Q30(0.7853981853f/M_PI),
Q30(0.6712729335f/M_PI), Q30(0.6638893485f/M_PI), Q30(0.6506769061f/M_PI), Q30(0.6009597182f/M_PI), Q30(0.5036380291f/M_PI), Q30(0.1060028747f/M_PI),
Q30(0.5628717542f/M_PI), Q30(0.5499725342f/M_PI), Q30(0.5274890065f/M_PI), Q30(0.4499453008f/M_PI), Q30(0.3283358216f/M_PI), Q30(0.0522236861f/M_PI),
Q30(0.4645969570f/M_PI), Q30(0.4488625824f/M_PI), Q30(0.4223022461f/M_PI), Q30(0.3387103081f/M_PI), Q30(0.2286661267f/M_PI), Q30(0.0334156826f/M_PI),
Q30(0.3788735867f/M_PI), Q30(0.3626709878f/M_PI), Q30(0.3361184299f/M_PI), Q30(0.2584958076f/M_PI), Q30(0.1673794836f/M_PI), Q30(0.0236366931f/M_PI),
Q30(0.3062773645f/M_PI), Q30(0.2911485136f/M_PI), Q30(0.2669326365f/M_PI), Q30(0.1997837722f/M_PI), Q30(0.1264114529f/M_PI), Q30(0.0175609849f/M_PI),
Q30(0.2202406377f/M_PI), Q30(0.2079535723f/M_PI), Q30(0.1887452900f/M_PI), Q30(0.1380121708f/M_PI), Q30(0.0857949182f/M_PI), Q30(0.0117820343f/M_PI),
Q30(0.1571819335f/M_PI), Q30(0.1478640437f/M_PI), Q30(0.1334884763f/M_PI), Q30(0.0964778885f/M_PI), Q30(0.0594860613f/M_PI), Q30(0.0081279324f/M_PI),
Q30(0.1117345318f/M_PI), Q30(0.1049065739f/M_PI), Q30(0.0944457650f/M_PI), Q30(0.0678641573f/M_PI), Q30(0.0416790098f/M_PI), Q30(0.0056813755f/M_PI),
Q30(0.0792663917f/M_PI), Q30(0.0743482932f/M_PI), Q30(0.0668405443f/M_PI), Q30(0.0478888862f/M_PI), Q30(0.0293543357f/M_PI), Q30(0.0039967746f/M_PI),
Q30(0.0561749674f/M_PI), Q30(0.0526629239f/M_PI), Q30(0.0473113805f/M_PI), Q30(0.0338476151f/M_PI), Q30(0.0207276177f/M_PI), Q30(0.0028205961f/M_PI),
Q30(0.0316122435f/M_PI), Q30(0.0296254847f/M_PI), Q30(0.0266019460f/M_PI), Q30(0.0190126132f/M_PI), Q30(0.0116353342f/M_PI), Q30(0.0015827164f/M_PI),
Q30(0.0177809205f/M_PI), Q30(0.0166615788f/M_PI), Q30(0.0149587989f/M_PI), Q30(0.0106877899f/M_PI), Q30(0.0065393616f/M_PI), Q30(0.0008894200f/M_PI),
Q30(0.0099996664f/M_PI), Q30(0.0093698399f/M_PI), Q30(0.0084118480f/M_PI), Q30(0.0060095116f/M_PI), Q30(0.0036767013f/M_PI), Q30(0.0005000498f/M_PI),
Q30(0.0056233541f/M_PI), Q30(0.0052691097f/M_PI), Q30(0.0047303112f/M_PI), Q30(0.0033792770f/M_PI), Q30(0.0020674451f/M_PI), Q30(0.0002811795f/M_PI),
Q30(0.0031622672f/M_PI), Q30(0.0029630491f/M_PI), Q30(0.0026600463f/M_PI), Q30(0.0019002859f/M_PI), Q30(0.0011625893f/M_PI), Q30(0.0001581155f/M_PI)
};
static const int gamma_tab[] =
{
Q30(0.0000000000f/M_PI), Q30(0.0195873566f/M_PI), Q30(0.0303316917f/M_PI), Q30(0.0448668823f/M_PI), Q30(0.0522258915f/M_PI), Q30(0.0561044961f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0433459543f/M_PI), Q30(0.0672172382f/M_PI), Q30(0.0997167900f/M_PI), Q30(0.1162951663f/M_PI), Q30(0.1250736862f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0672341362f/M_PI), Q30(0.1045235619f/M_PI), Q30(0.1558904350f/M_PI), Q30(0.1824723780f/M_PI), Q30(0.1966800541f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1011129096f/M_PI), Q30(0.1580764502f/M_PI), Q30(0.2387557179f/M_PI), Q30(0.2820728719f/M_PI), Q30(0.3058380187f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1315985769f/M_PI), Q30(0.2072522491f/M_PI), Q30(0.3188187480f/M_PI), Q30(0.3825501204f/M_PI), Q30(0.4193951190f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1603866369f/M_PI), Q30(0.2549437582f/M_PI), Q30(0.4029446840f/M_PI), Q30(0.4980689585f/M_PI), Q30(0.5615641475f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1736015975f/M_PI), Q30(0.2773745656f/M_PI), Q30(0.4461984038f/M_PI), Q30(0.5666890144f/M_PI), Q30(0.6686112881f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1784276664f/M_PI), Q30(0.2856673002f/M_PI), Q30(0.4630723596f/M_PI), Q30(0.5971632004f/M_PI), Q30(0.7603877187f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1736015975f/M_PI), Q30(0.2773745656f/M_PI), Q30(0.4461984038f/M_PI), Q30(0.5666890144f/M_PI), Q30(0.6686112881f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1603866369f/M_PI), Q30(0.2549437582f/M_PI), Q30(0.4029446840f/M_PI), Q30(0.4980689585f/M_PI), Q30(0.5615641475f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1315985769f/M_PI), Q30(0.2072522491f/M_PI), Q30(0.3188187480f/M_PI), Q30(0.3825501204f/M_PI), Q30(0.4193951190f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1011129096f/M_PI), Q30(0.1580764502f/M_PI), Q30(0.2387557179f/M_PI), Q30(0.2820728719f/M_PI), Q30(0.3058380187f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0672341362f/M_PI), Q30(0.1045235619f/M_PI), Q30(0.1558904350f/M_PI), Q30(0.1824723780f/M_PI), Q30(0.1966800541f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0433459543f/M_PI), Q30(0.0672172382f/M_PI), Q30(0.0997167900f/M_PI), Q30(0.1162951663f/M_PI), Q30(0.1250736862f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0195873566f/M_PI), Q30(0.0303316917f/M_PI), Q30(0.0448668823f/M_PI), Q30(0.0522258915f/M_PI), Q30(0.0561044961f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0011053939f/M_PI), Q30(0.0017089852f/M_PI), Q30(0.0025254129f/M_PI), Q30(0.0029398468f/M_PI), Q30(0.0031597170f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0019607407f/M_PI), Q30(0.0030395309f/M_PI), Q30(0.0044951206f/M_PI), Q30(0.0052305623f/M_PI), Q30(0.0056152637f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0034913034f/M_PI), Q30(0.0054070661f/M_PI), Q30(0.0079917293f/M_PI), Q30(0.0092999367f/M_PI), Q30(0.0099875759f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0062100487f/M_PI), Q30(0.0096135242f/M_PI), Q30(0.0142110568f/M_PI), Q30(0.0165348612f/M_PI), Q30(0.0177587029f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0110366223f/M_PI), Q30(0.0170863140f/M_PI), Q30(0.0252620988f/M_PI), Q30(0.0293955617f/M_PI), Q30(0.0315726399f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0195873566f/M_PI), Q30(0.0303316917f/M_PI), Q30(0.0448668823f/M_PI), Q30(0.0522258915f/M_PI), Q30(0.0561044961f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0275881495f/M_PI), Q30(0.0427365713f/M_PI), Q30(0.0632618815f/M_PI), Q30(0.0736731067f/M_PI), Q30(0.0791663304f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0387469754f/M_PI), Q30(0.0600636788f/M_PI), Q30(0.0890387669f/M_PI), Q30(0.1037906483f/M_PI), Q30(0.1115923747f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0541138873f/M_PI), Q30(0.0839984417f/M_PI), Q30(0.1248718798f/M_PI), Q30(0.1458375156f/M_PI), Q30(0.1569785923f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0747506917f/M_PI), Q30(0.1163287833f/M_PI), Q30(0.1738867164f/M_PI), Q30(0.2038587779f/M_PI), Q30(0.2199459076f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1011129096f/M_PI), Q30(0.1580764502f/M_PI), Q30(0.2387557179f/M_PI), Q30(0.2820728719f/M_PI), Q30(0.3058380187f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1212290376f/M_PI), Q30(0.1903949380f/M_PI), Q30(0.2907958031f/M_PI), Q30(0.3466993868f/M_PI), Q30(0.3782821596f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1418247074f/M_PI), Q30(0.2240308374f/M_PI), Q30(0.3474813402f/M_PI), Q30(0.4202919006f/M_PI), Q30(0.4637607038f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1603866369f/M_PI), Q30(0.2549437582f/M_PI), Q30(0.4029446840f/M_PI), Q30(0.4980689585f/M_PI), Q30(0.5615641475f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1736015975f/M_PI), Q30(0.2773745656f/M_PI), Q30(0.4461984038f/M_PI), Q30(0.5666890144f/M_PI), Q30(0.6686112881f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1784276664f/M_PI), Q30(0.2856673002f/M_PI), Q30(0.4630723596f/M_PI), Q30(0.5971632004f/M_PI), Q30(0.7603877187f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1736015975f/M_PI), Q30(0.2773745656f/M_PI), Q30(0.4461984038f/M_PI), Q30(0.5666890144f/M_PI), Q30(0.6686112881f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1603866369f/M_PI), Q30(0.2549437582f/M_PI), Q30(0.4029446840f/M_PI), Q30(0.4980689585f/M_PI), Q30(0.5615641475f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1418247074f/M_PI), Q30(0.2240308374f/M_PI), Q30(0.3474813402f/M_PI), Q30(0.4202919006f/M_PI), Q30(0.4637607038f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1212290376f/M_PI), Q30(0.1903949380f/M_PI), Q30(0.2907958031f/M_PI), Q30(0.3466993868f/M_PI), Q30(0.3782821596f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.1011129096f/M_PI), Q30(0.1580764502f/M_PI), Q30(0.2387557179f/M_PI), Q30(0.2820728719f/M_PI), Q30(0.3058380187f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0747506917f/M_PI), Q30(0.1163287833f/M_PI), Q30(0.1738867164f/M_PI), Q30(0.2038587779f/M_PI), Q30(0.2199459076f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0541138873f/M_PI), Q30(0.0839984417f/M_PI), Q30(0.1248718798f/M_PI), Q30(0.1458375156f/M_PI), Q30(0.1569785923f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0387469754f/M_PI), Q30(0.0600636788f/M_PI), Q30(0.0890387669f/M_PI), Q30(0.1037906483f/M_PI), Q30(0.1115923747f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0275881495f/M_PI), Q30(0.0427365713f/M_PI), Q30(0.0632618815f/M_PI), Q30(0.0736731067f/M_PI), Q30(0.0791663304f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0195873566f/M_PI), Q30(0.0303316917f/M_PI), Q30(0.0448668823f/M_PI), Q30(0.0522258915f/M_PI), Q30(0.0561044961f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0110366223f/M_PI), Q30(0.0170863140f/M_PI), Q30(0.0252620988f/M_PI), Q30(0.0293955617f/M_PI), Q30(0.0315726399f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0062100487f/M_PI), Q30(0.0096135242f/M_PI), Q30(0.0142110568f/M_PI), Q30(0.0165348612f/M_PI), Q30(0.0177587029f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0034913034f/M_PI), Q30(0.0054070661f/M_PI), Q30(0.0079917293f/M_PI), Q30(0.0092999367f/M_PI), Q30(0.0099875759f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0019607407f/M_PI), Q30(0.0030395309f/M_PI), Q30(0.0044951206f/M_PI), Q30(0.0052305623f/M_PI), Q30(0.0056152637f/M_PI),
Q30(0.0000000000f/M_PI), Q30(0.0011053939f/M_PI), Q30(0.0017089852f/M_PI), Q30(0.0025254129f/M_PI), Q30(0.0029398468f/M_PI), Q30(0.0031597170f/M_PI)
};
static const int iid_par_dequant_c1[] = {
//iid_par_dequant_default
Q30(1.41198278375959f), Q30(1.40313815268360f), Q30(1.38687670404960f), Q30(1.34839972492648f),
Q30(1.29124937110028f), Q30(1.19603741667993f), Q30(1.10737240362323f), Q30(1),
Q30(0.87961716655242f), Q30(0.75464859232732f), Q30(0.57677990744575f), Q30(0.42640143271122f),
Q30(0.27671828230984f), Q30(0.17664462766713f), Q30(0.07940162697653f),
//iid_par_dequant_fine
Q30(1.41420649135832f), Q30(1.41419120222364f), Q30(1.41414285699784f), Q30(1.41399000859438f),
Q30(1.41350698548044f), Q30(1.41198278375959f), Q30(1.40977302262355f), Q30(1.40539479488545f),
Q30(1.39677960498402f), Q30(1.38005309967827f), Q30(1.34839972492648f), Q30(1.31392017367631f),
Q30(1.26431008149654f), Q30(1.19603741667993f), Q30(1.10737240362323f), Q30(1),
Q30(0.87961716655242f), Q30(0.75464859232732f), Q30(0.63365607219232f), Q30(0.52308104267543f),
Q30(0.42640143271122f), Q30(0.30895540465965f), Q30(0.22137464873077f), Q30(0.15768788954414f),
Q30(0.11198225164225f), Q30(0.07940162697653f), Q30(0.04469901562677f), Q30(0.02514469318284f),
Q30(0.01414142856998f), Q30(0.00795258154731f), Q30(0.00447211359449f),
};
static const int acos_icc_invq[] = {
Q31(0), Q31(0.178427635f/M_PI), Q31(0.28566733f/M_PI), Q31(0.46307236f/M_PI), Q31(0.59716315f/M_PI), Q31(0.78539816f/M_PI), Q31(1.10030855f/M_PI), Q31(1.57079633f/M_PI)
};
int iid, icc;
int k, m;
static const int8_t f_center_20[] = {
-3, -1, 1, 3, 5, 7, 10, 14, 18, 22,
};
static const int32_t f_center_34[] = {
Q31( 2/768.0),Q31( 6/768.0),Q31(10/768.0),Q31(14/768.0),Q31( 18/768.0),Q31( 22/768.0),Q31( 26/768.0),Q31(30/768.0),
Q31( 34/768.0),Q31(-10/768.0),Q31(-6/768.0),Q31(-2/768.0),Q31( 51/768.0),Q31( 57/768.0),Q31( 15/768.0),Q31(21/768.0),
Q31( 27/768.0),Q31( 33/768.0),Q31(39/768.0),Q31(45/768.0),Q31( 54/768.0),Q31( 66/768.0),Q31( 78/768.0),Q31(42/768.0),
Q31(102/768.0),Q31( 66/768.0),Q31(78/768.0),Q31(90/768.0),Q31(102/768.0),Q31(114/768.0),Q31(126/768.0),Q31(90/768.0)
};
static const int fractional_delay_links[] = { Q31(0.43f), Q31(0.75f), Q31(0.347f) };
const int fractional_delay_gain = Q31(0.39f);
for (pd0 = 0; pd0 < 8; pd0++) {
int pd0_re = (ipdopd_cos[pd0]+2)>>2;
int pd0_im = (ipdopd_sin[pd0]+2)>>2;
for (pd1 = 0; pd1 < 8; pd1++) {
int pd1_re = ipdopd_cos[pd1] >> 1;
int pd1_im = ipdopd_sin[pd1] >> 1;
for (pd2 = 0; pd2 < 8; pd2++) {
int shift, round;
int pd2_re = ipdopd_cos[pd2];
int pd2_im = ipdopd_sin[pd2];
int re_smooth = pd0_re + pd1_re + pd2_re;
int im_smooth = pd0_im + pd1_im + pd2_im;
SoftFloat pd_mag = av_int2sf(((ipdopd_cos[(pd0-pd1)&7]+8)>>4) + ((ipdopd_cos[(pd0-pd2)&7]+4)>>3) +
((ipdopd_cos[(pd1-pd2)&7]+2)>>2) + 0x15000000, 28);
pd_mag = av_div_sf(FLOAT_1, av_sqrt_sf(pd_mag));
shift = 30 - pd_mag.exp;
round = 1 << (shift-1);
pd_re_smooth[pd0*64+pd1*8+pd2] = (int)(((int64_t)re_smooth * pd_mag.mant + round) >> shift);
pd_im_smooth[pd0*64+pd1*8+pd2] = (int)(((int64_t)im_smooth * pd_mag.mant + round) >> shift);
}
}
}
idx = 0;
for (iid = 0; iid < 46; iid++) {
int c1, c2;
c1 = iid_par_dequant_c1[iid];
if (iid < 15)
c2 = iid_par_dequant_c1[14-iid];
else
c2 = iid_par_dequant_c1[60-iid];
for (icc = 0; icc < 8; icc++) {
/*if (PS_BASELINE || ps->icc_mode < 3)*/{
int alpha, beta;
int ca, sa, cb, sb;
alpha = acos_icc_invq[icc];
beta = (int)(((int64_t)alpha * 1518500250 + 0x40000000) >> 31);
alpha >>= 1;
beta = (int)(((int64_t)beta * (c1 - c2) + 0x40000000) >> 31);
av_sincos_sf(beta + alpha, &sa, &ca);
av_sincos_sf(beta - alpha, &sb, &cb);
HA[iid][icc][0] = (int)(((int64_t)c2 * ca + 0x20000000) >> 30);
HA[iid][icc][1] = (int)(((int64_t)c1 * cb + 0x20000000) >> 30);
HA[iid][icc][2] = (int)(((int64_t)c2 * sa + 0x20000000) >> 30);
HA[iid][icc][3] = (int)(((int64_t)c1 * sb + 0x20000000) >> 30);
} /* else */ {
int alpha_int, gamma_int;
int alpha_c_int, alpha_s_int, gamma_c_int, gamma_s_int;
alpha_int = alpha_tab[idx];
gamma_int = gamma_tab[idx];
av_sincos_sf(alpha_int, &alpha_s_int, &alpha_c_int);
av_sincos_sf(gamma_int, &gamma_s_int, &gamma_c_int);
alpha_c_int = (int)(((int64_t)alpha_c_int * 1518500250 + 0x20000000) >> 30);
alpha_s_int = (int)(((int64_t)alpha_s_int * 1518500250 + 0x20000000) >> 30);
HB[iid][icc][0] = (int)(((int64_t)alpha_c_int * gamma_c_int + 0x20000000) >> 30);
HB[iid][icc][1] = (int)(((int64_t)alpha_s_int * gamma_c_int + 0x20000000) >> 30);
HB[iid][icc][2] = -(int)(((int64_t)alpha_s_int * gamma_s_int + 0x20000000) >> 30);
HB[iid][icc][3] = (int)(((int64_t)alpha_c_int * gamma_s_int + 0x20000000) >> 30);
}
if (icc < 5 || icc > 6)
idx++;
}
}
for (k = 0; k < NR_ALLPASS_BANDS20; k++) {
int theta;
int64_t f_center;
int c, s;
if (k < FF_ARRAY_ELEMS(f_center_20))
f_center = f_center_20[k];
else
f_center = (k << 3) - 52;
for (m = 0; m < PS_AP_LINKS; m++) {
theta = (int)(((int64_t)fractional_delay_links[m] * f_center + 8) >> 4);
av_sincos_sf(-theta, &s, &c);
Q_fract_allpass[0][k][m][0] = c;
Q_fract_allpass[0][k][m][1] = s;
}
theta = (int)(((int64_t)fractional_delay_gain * f_center + 8) >> 4);
av_sincos_sf(-theta, &s, &c);
phi_fract[0][k][0] = c;
phi_fract[0][k][1] = s;
}
for (k = 0; k < NR_ALLPASS_BANDS34; k++) {
int theta, f_center;
int c, s;
if (k < FF_ARRAY_ELEMS(f_center_34))
f_center = f_center_34[k];
else
f_center = ((int64_t)k << 26) - (53 << 25);
for (m = 0; m < PS_AP_LINKS; m++) {
theta = (int)(((int64_t)fractional_delay_links[m] * f_center + 0x10000000) >> 27);
av_sincos_sf(-theta, &s, &c);
Q_fract_allpass[1][k][m][0] = c;
Q_fract_allpass[1][k][m][1] = s;
}
theta = (int)(((int64_t)fractional_delay_gain * f_center + 0x10000000) >> 27);
av_sincos_sf(-theta, &s, &c);
phi_fract[1][k][0] = c;
phi_fract[1][k][1] = s;
}
make_filters_from_proto(f20_0_8, g0_Q8, 8);
make_filters_from_proto(f34_0_12, g0_Q12, 12);
make_filters_from_proto(f34_1_8, g1_Q8, 8);
make_filters_from_proto(f34_2_4, g2_Q4, 4);
}
#endif /* CONFIG_HARDCODED_TABLES */
#endif /* AVCODEC_AACPS_FIXED_TABLEGEN_H */

View File

@ -0,0 +1,217 @@
/*
* Header file for hardcoded Parametric Stereo tables
*
* Copyright (c) 2010 Alex Converse <alex.converse@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AACPS_TABLEGEN_H
#define AVCODEC_AACPS_TABLEGEN_H
#include <math.h>
#include <stdint.h>
#if CONFIG_HARDCODED_TABLES
#define ps_tableinit()
#define TABLE_CONST const
#include "libavcodec/aacps_tables.h"
#else
#include "libavutil/common.h"
#include "libavutil/libm.h"
#include "libavutil/mathematics.h"
#include "libavutil/mem.h"
#define NR_ALLPASS_BANDS20 30
#define NR_ALLPASS_BANDS34 50
#define PS_AP_LINKS 3
#define TABLE_CONST
static float pd_re_smooth[8*8*8];
static float pd_im_smooth[8*8*8];
static float HA[46][8][4];
static float HB[46][8][4];
static DECLARE_ALIGNED(16, float, f20_0_8) [ 8][8][2];
static DECLARE_ALIGNED(16, float, f34_0_12)[12][8][2];
static DECLARE_ALIGNED(16, float, f34_1_8) [ 8][8][2];
static DECLARE_ALIGNED(16, float, f34_2_4) [ 4][8][2];
static TABLE_CONST DECLARE_ALIGNED(16, float, Q_fract_allpass)[2][50][3][2];
static DECLARE_ALIGNED(16, float, phi_fract)[2][50][2];
static const float g0_Q8[] = {
0.00746082949812f, 0.02270420949825f, 0.04546865930473f, 0.07266113929591f,
0.09885108575264f, 0.11793710567217f, 0.125f
};
static const float g0_Q12[] = {
0.04081179924692f, 0.03812810994926f, 0.05144908135699f, 0.06399831151592f,
0.07428313801106f, 0.08100347892914f, 0.08333333333333f
};
static const float g1_Q8[] = {
0.01565675600122f, 0.03752716391991f, 0.05417891378782f, 0.08417044116767f,
0.10307344158036f, 0.12222452249753f, 0.125f
};
static const float g2_Q4[] = {
-0.05908211155639f, -0.04871498374946f, 0.0f, 0.07778723915851f,
0.16486303567403f, 0.23279856662996f, 0.25f
};
static av_cold void make_filters_from_proto(float (*filter)[8][2], const float *proto, int bands)
{
int q, n;
for (q = 0; q < bands; q++) {
for (n = 0; n < 7; n++) {
double theta = 2 * M_PI * (q + 0.5) * (n - 6) / bands;
filter[q][n][0] = proto[n] * cos(theta);
filter[q][n][1] = proto[n] * -sin(theta);
}
}
}
static av_cold void ps_tableinit(void)
{
static const float ipdopd_sin[] = { 0, M_SQRT1_2, 1, M_SQRT1_2, 0, -M_SQRT1_2, -1, -M_SQRT1_2 };
static const float ipdopd_cos[] = { 1, M_SQRT1_2, 0, -M_SQRT1_2, -1, -M_SQRT1_2, 0, M_SQRT1_2 };
int pd0, pd1, pd2;
static const float iid_par_dequant[] = {
//iid_par_dequant_default
0.05623413251903, 0.12589254117942, 0.19952623149689, 0.31622776601684,
0.44668359215096, 0.63095734448019, 0.79432823472428, 1,
1.25892541179417, 1.58489319246111, 2.23872113856834, 3.16227766016838,
5.01187233627272, 7.94328234724282, 17.7827941003892,
//iid_par_dequant_fine
0.00316227766017, 0.00562341325190, 0.01, 0.01778279410039,
0.03162277660168, 0.05623413251903, 0.07943282347243, 0.11220184543020,
0.15848931924611, 0.22387211385683, 0.31622776601684, 0.39810717055350,
0.50118723362727, 0.63095734448019, 0.79432823472428, 1,
1.25892541179417, 1.58489319246111, 1.99526231496888, 2.51188643150958,
3.16227766016838, 4.46683592150963, 6.30957344480193, 8.91250938133745,
12.5892541179417, 17.7827941003892, 31.6227766016838, 56.2341325190349,
100, 177.827941003892, 316.227766016837,
};
static const float icc_invq[] = {
1, 0.937, 0.84118, 0.60092, 0.36764, 0, -0.589, -1
};
static const float acos_icc_invq[] = {
0, 0.35685527, 0.57133466, 0.92614472, 1.1943263, M_PI/2, 2.2006171, M_PI
};
int iid, icc;
int k, m;
static const int8_t f_center_20[] = {
-3, -1, 1, 3, 5, 7, 10, 14, 18, 22,
};
static const int8_t f_center_34[] = {
2, 6, 10, 14, 18, 22, 26, 30,
34,-10, -6, -2, 51, 57, 15, 21,
27, 33, 39, 45, 54, 66, 78, 42,
102, 66, 78, 90,102,114,126, 90,
};
static const float fractional_delay_links[] = { 0.43f, 0.75f, 0.347f };
const float fractional_delay_gain = 0.39f;
for (pd0 = 0; pd0 < 8; pd0++) {
float pd0_re = ipdopd_cos[pd0];
float pd0_im = ipdopd_sin[pd0];
for (pd1 = 0; pd1 < 8; pd1++) {
float pd1_re = ipdopd_cos[pd1];
float pd1_im = ipdopd_sin[pd1];
for (pd2 = 0; pd2 < 8; pd2++) {
float pd2_re = ipdopd_cos[pd2];
float pd2_im = ipdopd_sin[pd2];
float re_smooth = 0.25f * pd0_re + 0.5f * pd1_re + pd2_re;
float im_smooth = 0.25f * pd0_im + 0.5f * pd1_im + pd2_im;
float pd_mag = 1 / hypot(im_smooth, re_smooth);
pd_re_smooth[pd0*64+pd1*8+pd2] = re_smooth * pd_mag;
pd_im_smooth[pd0*64+pd1*8+pd2] = im_smooth * pd_mag;
}
}
}
for (iid = 0; iid < 46; iid++) {
float c = iid_par_dequant[iid]; ///< Linear Inter-channel Intensity Difference
float c1 = (float)M_SQRT2 / sqrtf(1.0f + c*c);
float c2 = c * c1;
for (icc = 0; icc < 8; icc++) {
/*if (PS_BASELINE || ps->icc_mode < 3)*/ {
float alpha = 0.5f * acos_icc_invq[icc];
float beta = alpha * (c1 - c2) * (float)M_SQRT1_2;
HA[iid][icc][0] = c2 * cosf(beta + alpha);
HA[iid][icc][1] = c1 * cosf(beta - alpha);
HA[iid][icc][2] = c2 * sinf(beta + alpha);
HA[iid][icc][3] = c1 * sinf(beta - alpha);
} /* else */ {
float alpha, gamma, mu, rho;
float alpha_c, alpha_s, gamma_c, gamma_s;
rho = FFMAX(icc_invq[icc], 0.05f);
alpha = 0.5f * atan2f(2.0f * c * rho, c*c - 1.0f);
mu = c + 1.0f / c;
mu = sqrtf(1 + (4 * rho * rho - 4)/(mu * mu));
gamma = atanf(sqrtf((1.0f - mu)/(1.0f + mu)));
if (alpha < 0) alpha += M_PI/2;
alpha_c = cosf(alpha);
alpha_s = sinf(alpha);
gamma_c = cosf(gamma);
gamma_s = sinf(gamma);
HB[iid][icc][0] = M_SQRT2 * alpha_c * gamma_c;
HB[iid][icc][1] = M_SQRT2 * alpha_s * gamma_c;
HB[iid][icc][2] = -M_SQRT2 * alpha_s * gamma_s;
HB[iid][icc][3] = M_SQRT2 * alpha_c * gamma_s;
}
}
}
for (k = 0; k < NR_ALLPASS_BANDS20; k++) {
double f_center, theta;
if (k < FF_ARRAY_ELEMS(f_center_20))
f_center = f_center_20[k] * 0.125;
else
f_center = k - 6.5f;
for (m = 0; m < PS_AP_LINKS; m++) {
theta = -M_PI * fractional_delay_links[m] * f_center;
Q_fract_allpass[0][k][m][0] = cos(theta);
Q_fract_allpass[0][k][m][1] = sin(theta);
}
theta = -M_PI*fractional_delay_gain*f_center;
phi_fract[0][k][0] = cos(theta);
phi_fract[0][k][1] = sin(theta);
}
for (k = 0; k < NR_ALLPASS_BANDS34; k++) {
double f_center, theta;
if (k < FF_ARRAY_ELEMS(f_center_34))
f_center = f_center_34[k] / 24.0;
else
f_center = k - 26.5f;
for (m = 0; m < PS_AP_LINKS; m++) {
theta = -M_PI * fractional_delay_links[m] * f_center;
Q_fract_allpass[1][k][m][0] = cos(theta);
Q_fract_allpass[1][k][m][1] = sin(theta);
}
theta = -M_PI*fractional_delay_gain*f_center;
phi_fract[1][k][0] = cos(theta);
phi_fract[1][k][1] = sin(theta);
}
make_filters_from_proto(f20_0_8, g0_Q8, 8);
make_filters_from_proto(f34_0_12, g0_Q12, 12);
make_filters_from_proto(f34_1_8, g1_Q8, 8);
make_filters_from_proto(f34_2_4, g2_Q4, 4);
}
#endif /* CONFIG_HARDCODED_TABLES */
#endif /* AVCODEC_AACPS_TABLEGEN_H */

View File

@ -0,0 +1,60 @@
/*
* Copyright (c) 2012 Mans Rullgard
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AACPSDSP_H
#define AVCODEC_AACPSDSP_H
#include <stddef.h>
#include "aac_defines.h"
#define PS_QMF_TIME_SLOTS 32
#define PS_AP_LINKS 3
#define PS_MAX_AP_DELAY 5
typedef struct PSDSPContext {
void (*add_squares)(INTFLOAT *dst, const INTFLOAT (*src)[2], int n);
void (*mul_pair_single)(INTFLOAT (*dst)[2], INTFLOAT (*src0)[2], INTFLOAT *src1,
int n);
void (*hybrid_analysis)(INTFLOAT (*out)[2], INTFLOAT (*in)[2],
const INTFLOAT (*filter)[8][2],
ptrdiff_t stride, int n);
void (*hybrid_analysis_ileave)(INTFLOAT (*out)[32][2], INTFLOAT L[2][38][64],
int i, int len);
void (*hybrid_synthesis_deint)(INTFLOAT out[2][38][64], INTFLOAT (*in)[32][2],
int i, int len);
void (*decorrelate)(INTFLOAT (*out)[2], INTFLOAT (*delay)[2],
INTFLOAT (*ap_delay)[PS_QMF_TIME_SLOTS+PS_MAX_AP_DELAY][2],
const INTFLOAT phi_fract[2], const INTFLOAT (*Q_fract)[2],
const INTFLOAT *transient_gain,
INTFLOAT g_decay_slope,
int len);
void (*stereo_interpolate[2])(INTFLOAT (*l)[2], INTFLOAT (*r)[2],
INTFLOAT h[2][4], INTFLOAT h_step[2][4],
int len);
} PSDSPContext;
void AAC_RENAME(ff_psdsp_init)(PSDSPContext *s);
void ff_psdsp_init_arm(PSDSPContext *s);
void ff_psdsp_init_aarch64(PSDSPContext *s);
void ff_psdsp_init_mips(PSDSPContext *s);
void ff_psdsp_init_x86(PSDSPContext *s);
#endif /* AVCODEC_AACPSDSP_H */

View File

@ -0,0 +1,96 @@
/*
* AAC Spectral Band Replication function declarations
* Copyright (c) 2008-2009 Robert Swain ( rob opendot cl )
* Copyright (c) 2010 Alex Converse <alex.converse@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC Spectral Band Replication function declarations
* @author Robert Swain ( rob opendot cl )
*/
#ifndef AVCODEC_AACSBR_H
#define AVCODEC_AACSBR_H
#include "get_bits.h"
#include "aac.h"
#include "sbr.h"
#define ENVELOPE_ADJUSTMENT_OFFSET 2
#define NOISE_FLOOR_OFFSET 6
/**
* SBR VLC tables
*/
enum {
T_HUFFMAN_ENV_1_5DB,
F_HUFFMAN_ENV_1_5DB,
T_HUFFMAN_ENV_BAL_1_5DB,
F_HUFFMAN_ENV_BAL_1_5DB,
T_HUFFMAN_ENV_3_0DB,
F_HUFFMAN_ENV_3_0DB,
T_HUFFMAN_ENV_BAL_3_0DB,
F_HUFFMAN_ENV_BAL_3_0DB,
T_HUFFMAN_NOISE_3_0DB,
T_HUFFMAN_NOISE_BAL_3_0DB,
};
/**
* bs_frame_class - frame class of current SBR frame (14496-3 sp04 p98)
*/
enum {
FIXFIX,
FIXVAR,
VARFIX,
VARVAR,
};
enum {
EXTENSION_ID_PS = 2,
};
static const int8_t vlc_sbr_lav[10] =
{ 60, 60, 24, 24, 31, 31, 12, 12, 31, 12 };
#define SBR_INIT_VLC_STATIC(num, size) \
INIT_VLC_STATIC(&vlc_sbr[num], 9, sbr_tmp[num].table_size / sbr_tmp[num].elem_size, \
sbr_tmp[num].sbr_bits , 1, 1, \
sbr_tmp[num].sbr_codes, sbr_tmp[num].elem_size, sbr_tmp[num].elem_size, \
size)
#define SBR_VLC_ROW(name) \
{ name ## _codes, name ## _bits, sizeof(name ## _codes), sizeof(name ## _codes[0]) }
/** Initialize SBR. */
void AAC_RENAME(ff_aac_sbr_init)(void);
/** Initialize one SBR context. */
void AAC_RENAME(ff_aac_sbr_ctx_init)(AACContext *ac, SpectralBandReplication *sbr, int id_aac);
/** Close one SBR context. */
void AAC_RENAME(ff_aac_sbr_ctx_close)(SpectralBandReplication *sbr);
/** Decode one SBR element. */
int AAC_RENAME(ff_decode_sbr_extension)(AACContext *ac, SpectralBandReplication *sbr,
GetBitContext *gb, int crc, int cnt, int id_aac);
/** Apply one SBR element to one AAC element. */
void AAC_RENAME(ff_sbr_apply)(AACContext *ac, SpectralBandReplication *sbr, int id_aac,
INTFLOAT* L, INTFLOAT *R);
void ff_aacsbr_func_ptr_init_mips(AACSBRContext *c);
#endif /* AVCODEC_AACSBR_H */

View File

@ -0,0 +1,28 @@
/*
* Header file for hardcoded AAC SBR windows
*
* Copyright (c) 2014 Reimar Döffinger <Reimar.Doeffinger@gmx.de>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AACSBR_FIXED_TABLEGEN_H
#define AVCODEC_AACSBR_FIXED_TABLEGEN_H
#include "aacsbr_tablegen_common.h"
#endif /* AVCODEC_AACSBR_FIXED_TABLEGEN_H */

View File

@ -0,0 +1,28 @@
/*
* Header file for hardcoded AAC SBR windows
*
* Copyright (c) 2014 Reimar Döffinger <Reimar.Doeffinger@gmx.de>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AACSBR_TABLEGEN_H
#define AVCODEC_AACSBR_TABLEGEN_H
#include "aacsbr_tablegen_common.h"
#endif /* AVCODEC_AACSBR_TABLEGEN_H */

View File

@ -0,0 +1,126 @@
/*
* Header file for hardcoded AAC SBR windows
*
* Copyright (c) 2014 Reimar Döffinger <Reimar.Doeffinger@gmx.de>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AACSBR_TABLEGEN_COMMON_H
#define AVCODEC_AACSBR_TABLEGEN_COMMON_H
#include "aac_defines.h"
#include "libavutil/mem.h"
///< window coefficients for analysis/synthesis QMF banks
static DECLARE_ALIGNED(32, INTFLOAT, sbr_qmf_window_ds)[320];
static DECLARE_ALIGNED(32, INTFLOAT, sbr_qmf_window_us)[640] = {
Q31( 0.0000000000f), Q31(-0.0005525286f), Q31(-0.0005617692f), Q31(-0.0004947518f),
Q31(-0.0004875227f), Q31(-0.0004893791f), Q31(-0.0005040714f), Q31(-0.0005226564f),
Q31(-0.0005466565f), Q31(-0.0005677802f), Q31(-0.0005870930f), Q31(-0.0006132747f),
Q31(-0.0006312493f), Q31(-0.0006540333f), Q31(-0.0006777690f), Q31(-0.0006941614f),
Q31(-0.0007157736f), Q31(-0.0007255043f), Q31(-0.0007440941f), Q31(-0.0007490598f),
Q31(-0.0007681371f), Q31(-0.0007724848f), Q31(-0.0007834332f), Q31(-0.0007779869f),
Q31(-0.0007803664f), Q31(-0.0007801449f), Q31(-0.0007757977f), Q31(-0.0007630793f),
Q31(-0.0007530001f), Q31(-0.0007319357f), Q31(-0.0007215391f), Q31(-0.0006917937f),
Q31(-0.0006650415f), Q31(-0.0006341594f), Q31(-0.0005946118f), Q31(-0.0005564576f),
Q31(-0.0005145572f), Q31(-0.0004606325f), Q31(-0.0004095121f), Q31(-0.0003501175f),
Q31(-0.0002896981f), Q31(-0.0002098337f), Q31(-0.0001446380f), Q31(-0.0000617334f),
Q31( 0.0000134949f), Q31( 0.0001094383f), Q31( 0.0002043017f), Q31( 0.0002949531f),
Q31( 0.0004026540f), Q31( 0.0005107388f), Q31( 0.0006239376f), Q31( 0.0007458025f),
Q31( 0.0008608443f), Q31( 0.0009885988f), Q31( 0.0011250155f), Q31( 0.0012577884f),
Q31( 0.0013902494f), Q31( 0.0015443219f), Q31( 0.0016868083f), Q31( 0.0018348265f),
Q31( 0.0019841140f), Q31( 0.0021461583f), Q31( 0.0023017254f), Q31( 0.0024625616f),
Q31( 0.0026201758f), Q31( 0.0027870464f), Q31( 0.0029469447f), Q31( 0.0031125420f),
Q31( 0.0032739613f), Q31( 0.0034418874f), Q31( 0.0036008268f), Q31( 0.0037603922f),
Q31( 0.0039207432f), Q31( 0.0040819753f), Q31( 0.0042264269f), Q31( 0.0043730719f),
Q31( 0.0045209852f), Q31( 0.0046606460f), Q31( 0.0047932560f), Q31( 0.0049137603f),
Q31( 0.0050393022f), Q31( 0.0051407353f), Q31( 0.0052461166f), Q31( 0.0053471681f),
Q31( 0.0054196775f), Q31( 0.0054876040f), Q31( 0.0055475714f), Q31( 0.0055938023f),
Q31( 0.0056220643f), Q31( 0.0056455196f), Q31( 0.0056389199f), Q31( 0.0056266114f),
Q31( 0.0055917128f), Q31( 0.0055404363f), Q31( 0.0054753783f), Q31( 0.0053838975f),
Q31( 0.0052715758f), Q31( 0.0051382275f), Q31( 0.0049839687f), Q31( 0.0048109469f),
Q31( 0.0046039530f), Q31( 0.0043801861f), Q31( 0.0041251642f), Q31( 0.0038456408f),
Q31( 0.0035401246f), Q31( 0.0032091885f), Q31( 0.0028446757f), Q31( 0.0024508540f),
Q31( 0.0020274176f), Q31( 0.0015784682f), Q31( 0.0010902329f), Q31( 0.0005832264f),
Q31( 0.0000276045f), Q31(-0.0005464280f), Q31(-0.0011568135f), Q31(-0.0018039472f),
Q31(-0.0024826723f), Q31(-0.0031933778f), Q31(-0.0039401124f), Q31(-0.0047222596f),
Q31(-0.0055337211f), Q31(-0.0063792293f), Q31(-0.0072615816f), Q31(-0.0081798233f),
Q31(-0.0091325329f), Q31(-0.0101150215f), Q31(-0.0111315548f), Q31(-0.0121849995f),
Q31( 0.0132718220f), Q31( 0.0143904666f), Q31( 0.0155405553f), Q31( 0.0167324712f),
Q31( 0.0179433381f), Q31( 0.0191872431f), Q31( 0.0204531793f), Q31( 0.0217467550f),
Q31( 0.0230680169f), Q31( 0.0244160992f), Q31( 0.0257875847f), Q31( 0.0271859429f),
Q31( 0.0286072173f), Q31( 0.0300502657f), Q31( 0.0315017608f), Q31( 0.0329754081f),
Q31( 0.0344620948f), Q31( 0.0359697560f), Q31( 0.0374812850f), Q31( 0.0390053679f),
Q31( 0.0405349170f), Q31( 0.0420649094f), Q31( 0.0436097542f), Q31( 0.0451488405f),
Q31( 0.0466843027f), Q31( 0.0482165720f), Q31( 0.0497385755f), Q31( 0.0512556155f),
Q31( 0.0527630746f), Q31( 0.0542452768f), Q31( 0.0557173648f), Q31( 0.0571616450f),
Q31( 0.0585915683f), Q31( 0.0599837480f), Q31( 0.0613455171f), Q31( 0.0626857808f),
Q31( 0.0639715898f), Q31( 0.0652247106f), Q31( 0.0664367512f), Q31( 0.0676075985f),
Q31( 0.0687043828f), Q31( 0.0697630244f), Q31( 0.0707628710f), Q31( 0.0717002673f),
Q31( 0.0725682583f), Q31( 0.0733620255f), Q31( 0.0741003642f), Q31( 0.0747452558f),
Q31( 0.0753137336f), Q31( 0.0758008358f), Q31( 0.0761992479f), Q31( 0.0764992170f),
Q31( 0.0767093490f), Q31( 0.0768173975f), Q31( 0.0768230011f), Q31( 0.0767204924f),
Q31( 0.0765050718f), Q31( 0.0761748321f), Q31( 0.0757305756f), Q31( 0.0751576255f),
Q31( 0.0744664394f), Q31( 0.0736406005f), Q31( 0.0726774642f), Q31( 0.0715826364f),
Q31( 0.0703533073f), Q31( 0.0689664013f), Q31( 0.0674525021f), Q31( 0.0657690668f),
Q31( 0.0639444805f), Q31( 0.0619602779f), Q31( 0.0598166570f), Q31( 0.0575152691f),
Q31( 0.0550460034f), Q31( 0.0524093821f), Q31( 0.0495978676f), Q31( 0.0466303305f),
Q31( 0.0434768782f), Q31( 0.0401458278f), Q31( 0.0366418116f), Q31( 0.0329583930f),
Q31( 0.0290824006f), Q31( 0.0250307561f), Q31( 0.0207997072f), Q31( 0.0163701258f),
Q31( 0.0117623832f), Q31( 0.0069636862f), Q31( 0.0019765601f), Q31(-0.0032086896f),
Q31(-0.0085711749f), Q31(-0.0141288827f), Q31(-0.0198834129f), Q31(-0.0258227288f),
Q31(-0.0319531274f), Q31(-0.0382776572f), Q31(-0.0447806821f), Q31(-0.0514804176f),
Q31(-0.0583705326f), Q31(-0.0654409853f), Q31(-0.0726943300f), Q31(-0.0801372934f),
Q31(-0.0877547536f), Q31(-0.0955533352f), Q31(-0.1035329531f), Q31(-0.1116826931f),
Q31(-0.1200077984f), Q31(-0.1285002850f), Q31(-0.1371551761f), Q31(-0.1459766491f),
Q31(-0.1549607071f), Q31(-0.1640958855f), Q31(-0.1733808172f), Q31(-0.1828172548f),
Q31(-0.1923966745f), Q31(-0.2021250176f), Q31(-0.2119735853f), Q31(-0.2219652696f),
Q31(-0.2320690870f), Q31(-0.2423016884f), Q31(-0.2526480309f), Q31(-0.2631053299f),
Q31(-0.2736634040f), Q31(-0.2843214189f), Q31(-0.2950716717f), Q31(-0.3059098575f),
Q31(-0.3168278913f), Q31(-0.3278113727f), Q31(-0.3388722693f), Q31(-0.3499914122f),
Q31( 0.3611589903f), Q31( 0.3723795546f), Q31( 0.3836350013f), Q31( 0.3949211761f),
Q31( 0.4062317676f), Q31( 0.4175696896f), Q31( 0.4289119920f), Q31( 0.4402553754f),
Q31( 0.4515996535f), Q31( 0.4629308085f), Q31( 0.4742453214f), Q31( 0.4855253091f),
Q31( 0.4967708254f), Q31( 0.5079817500f), Q31( 0.5191234970f), Q31( 0.5302240895f),
Q31( 0.5412553448f), Q31( 0.5522051258f), Q31( 0.5630789140f), Q31( 0.5738524131f),
Q31( 0.5845403235f), Q31( 0.5951123086f), Q31( 0.6055783538f), Q31( 0.6159109932f),
Q31( 0.6261242695f), Q31( 0.6361980107f), Q31( 0.6461269695f), Q31( 0.6559016302f),
Q31( 0.6655139880f), Q31( 0.6749663190f), Q31( 0.6842353293f), Q31( 0.6933282376f),
Q31( 0.7022388719f), Q31( 0.7109410426f), Q31( 0.7194462634f), Q31( 0.7277448900f),
Q31( 0.7358211758f), Q31( 0.7436827863f), Q31( 0.7513137456f), Q31( 0.7587080760f),
Q31( 0.7658674865f), Q31( 0.7727780881f), Q31( 0.7794287519f), Q31( 0.7858353120f),
Q31( 0.7919735841f), Q31( 0.7978466413f), Q31( 0.8034485751f), Q31( 0.8087695004f),
Q31( 0.8138191270f), Q31( 0.8185776004f), Q31( 0.8230419890f), Q31( 0.8272275347f),
Q31( 0.8311038457f), Q31( 0.8346937361f), Q31( 0.8379717337f), Q31( 0.8409541392f),
Q31( 0.8436238281f), Q31( 0.8459818469f), Q31( 0.8480315777f), Q31( 0.8497805198f),
Q31( 0.8511971524f), Q31( 0.8523047035f), Q31( 0.8531020949f), Q31( 0.8535720573f),
Q31( 0.8537385600f),
};
static av_cold void aacsbr_tableinit(void)
{
int n;
for (n = 1; n < 320; n++)
sbr_qmf_window_us[320 + n] = sbr_qmf_window_us[320 - n];
sbr_qmf_window_us[384] = -sbr_qmf_window_us[384];
sbr_qmf_window_us[512] = -sbr_qmf_window_us[512];
for (n = 0; n < 320; n++)
sbr_qmf_window_ds[n] = sbr_qmf_window_us[2*n];
}
#endif /* AVCODEC_AACSBR_TABLEGEN_COMMON_H */

View File

@ -0,0 +1,535 @@
/*
* AAC Spectral Band Replication decoding data
* Copyright (c) 2008-2009 Robert Swain ( rob opendot cl )
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC Spectral Band Replication decoding data
* @author Robert Swain ( rob opendot cl )
*/
#ifndef AVCODEC_AACSBRDATA_H
#define AVCODEC_AACSBRDATA_H
#include <stdint.h>
#include "libavutil/mem.h"
#include "aac_defines.h"
///< Huffman tables for SBR
static const uint8_t t_huffman_env_1_5dB_bits[121] = {
18, 18, 18, 18, 18, 18, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 17, 18, 16, 17, 18, 17,
16, 16, 16, 16, 15, 14, 14, 13,
13, 12, 11, 10, 9, 8, 7, 6,
5, 4, 3, 2, 2, 3, 4, 5,
6, 7, 8, 9, 10, 12, 13, 14,
14, 15, 16, 17, 16, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19,
19,
};
static const uint32_t t_huffman_env_1_5dB_codes[121] = {
0x3ffd6, 0x3ffd7, 0x3ffd8, 0x3ffd9, 0x3ffda, 0x3ffdb, 0x7ffb8, 0x7ffb9,
0x7ffba, 0x7ffbb, 0x7ffbc, 0x7ffbd, 0x7ffbe, 0x7ffbf, 0x7ffc0, 0x7ffc1,
0x7ffc2, 0x7ffc3, 0x7ffc4, 0x7ffc5, 0x7ffc6, 0x7ffc7, 0x7ffc8, 0x7ffc9,
0x7ffca, 0x7ffcb, 0x7ffcc, 0x7ffcd, 0x7ffce, 0x7ffcf, 0x7ffd0, 0x7ffd1,
0x7ffd2, 0x7ffd3, 0x1ffe6, 0x3ffd4, 0x0fff0, 0x1ffe9, 0x3ffd5, 0x1ffe7,
0x0fff1, 0x0ffec, 0x0ffed, 0x0ffee, 0x07ff4, 0x03ff9, 0x03ff7, 0x01ffa,
0x01ff9, 0x00ffb, 0x007fc, 0x003fc, 0x001fd, 0x000fd, 0x0007d, 0x0003d,
0x0001d, 0x0000d, 0x00005, 0x00001, 0x00000, 0x00004, 0x0000c, 0x0001c,
0x0003c, 0x0007c, 0x000fc, 0x001fc, 0x003fd, 0x00ffa, 0x01ff8, 0x03ff6,
0x03ff8, 0x07ff5, 0x0ffef, 0x1ffe8, 0x0fff2, 0x7ffd4, 0x7ffd5, 0x7ffd6,
0x7ffd7, 0x7ffd8, 0x7ffd9, 0x7ffda, 0x7ffdb, 0x7ffdc, 0x7ffdd, 0x7ffde,
0x7ffdf, 0x7ffe0, 0x7ffe1, 0x7ffe2, 0x7ffe3, 0x7ffe4, 0x7ffe5, 0x7ffe6,
0x7ffe7, 0x7ffe8, 0x7ffe9, 0x7ffea, 0x7ffeb, 0x7ffec, 0x7ffed, 0x7ffee,
0x7ffef, 0x7fff0, 0x7fff1, 0x7fff2, 0x7fff3, 0x7fff4, 0x7fff5, 0x7fff6,
0x7fff7, 0x7fff8, 0x7fff9, 0x7fffa, 0x7fffb, 0x7fffc, 0x7fffd, 0x7fffe,
0x7ffff,
};
static const uint8_t f_huffman_env_1_5dB_bits[121] = {
19, 19, 20, 20, 20, 20, 20, 20,
20, 19, 20, 20, 20, 20, 19, 20,
19, 19, 20, 18, 20, 20, 20, 19,
20, 20, 20, 19, 20, 19, 18, 19,
18, 18, 17, 18, 17, 17, 17, 16,
16, 16, 15, 15, 14, 13, 13, 12,
12, 11, 10, 9, 9, 8, 7, 6,
5, 4, 3, 2, 2, 3, 4, 5,
6, 8, 8, 9, 10, 11, 11, 11,
12, 12, 13, 13, 14, 14, 16, 16,
17, 17, 18, 18, 18, 18, 18, 18,
18, 20, 19, 20, 20, 20, 20, 20,
20, 19, 20, 20, 20, 20, 19, 20,
18, 20, 20, 19, 19, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20,
20,
};
static const uint32_t f_huffman_env_1_5dB_codes[121] = {
0x7ffe7, 0x7ffe8, 0xfffd2, 0xfffd3, 0xfffd4, 0xfffd5, 0xfffd6, 0xfffd7,
0xfffd8, 0x7ffda, 0xfffd9, 0xfffda, 0xfffdb, 0xfffdc, 0x7ffdb, 0xfffdd,
0x7ffdc, 0x7ffdd, 0xfffde, 0x3ffe4, 0xfffdf, 0xfffe0, 0xfffe1, 0x7ffde,
0xfffe2, 0xfffe3, 0xfffe4, 0x7ffdf, 0xfffe5, 0x7ffe0, 0x3ffe8, 0x7ffe1,
0x3ffe0, 0x3ffe9, 0x1ffef, 0x3ffe5, 0x1ffec, 0x1ffed, 0x1ffee, 0x0fff4,
0x0fff3, 0x0fff0, 0x07ff7, 0x07ff6, 0x03ffa, 0x01ffa, 0x01ff9, 0x00ffa,
0x00ff8, 0x007f9, 0x003fb, 0x001fc, 0x001fa, 0x000fb, 0x0007c, 0x0003c,
0x0001c, 0x0000c, 0x00005, 0x00001, 0x00000, 0x00004, 0x0000d, 0x0001d,
0x0003d, 0x000fa, 0x000fc, 0x001fb, 0x003fa, 0x007f8, 0x007fa, 0x007fb,
0x00ff9, 0x00ffb, 0x01ff8, 0x01ffb, 0x03ff8, 0x03ff9, 0x0fff1, 0x0fff2,
0x1ffea, 0x1ffeb, 0x3ffe1, 0x3ffe2, 0x3ffea, 0x3ffe3, 0x3ffe6, 0x3ffe7,
0x3ffeb, 0xfffe6, 0x7ffe2, 0xfffe7, 0xfffe8, 0xfffe9, 0xfffea, 0xfffeb,
0xfffec, 0x7ffe3, 0xfffed, 0xfffee, 0xfffef, 0xffff0, 0x7ffe4, 0xffff1,
0x3ffec, 0xffff2, 0xffff3, 0x7ffe5, 0x7ffe6, 0xffff4, 0xffff5, 0xffff6,
0xffff7, 0xffff8, 0xffff9, 0xffffa, 0xffffb, 0xffffc, 0xffffd, 0xffffe,
0xfffff,
};
static const uint8_t t_huffman_env_bal_1_5dB_bits[49] = {
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 12, 11, 9, 7, 5, 3,
1, 2, 4, 6, 8, 11, 12, 15,
16, 16, 16, 16, 16, 16, 16, 17,
17, 17, 17, 17, 17, 17, 17, 17,
17,
};
static const uint32_t t_huffman_env_bal_1_5dB_codes[49] = {
0x0ffe4, 0x0ffe5, 0x0ffe6, 0x0ffe7, 0x0ffe8, 0x0ffe9, 0x0ffea, 0x0ffeb,
0x0ffec, 0x0ffed, 0x0ffee, 0x0ffef, 0x0fff0, 0x0fff1, 0x0fff2, 0x0fff3,
0x0fff4, 0x0ffe2, 0x00ffc, 0x007fc, 0x001fe, 0x0007e, 0x0001e, 0x00006,
0x00000, 0x00002, 0x0000e, 0x0003e, 0x000fe, 0x007fd, 0x00ffd, 0x07ff0,
0x0ffe3, 0x0fff5, 0x0fff6, 0x0fff7, 0x0fff8, 0x0fff9, 0x0fffa, 0x1fff6,
0x1fff7, 0x1fff8, 0x1fff9, 0x1fffa, 0x1fffb, 0x1fffc, 0x1fffd, 0x1fffe,
0x1ffff,
};
static const uint8_t f_huffman_env_bal_1_5dB_bits[49] = {
18, 18, 18, 18, 18, 18, 18, 18,
18, 18, 18, 18, 18, 18, 18, 16,
17, 14, 11, 11, 8, 7, 4, 2,
1, 3, 5, 6, 9, 11, 12, 15,
16, 18, 18, 18, 18, 18, 18, 18,
18, 18, 18, 18, 18, 18, 18, 19,
19,
};
static const uint32_t f_huffman_env_bal_1_5dB_codes[49] = {
0x3ffe2, 0x3ffe3, 0x3ffe4, 0x3ffe5, 0x3ffe6, 0x3ffe7, 0x3ffe8, 0x3ffe9,
0x3ffea, 0x3ffeb, 0x3ffec, 0x3ffed, 0x3ffee, 0x3ffef, 0x3fff0, 0x0fff7,
0x1fff0, 0x03ffc, 0x007fe, 0x007fc, 0x000fe, 0x0007e, 0x0000e, 0x00002,
0x00000, 0x00006, 0x0001e, 0x0003e, 0x001fe, 0x007fd, 0x00ffe, 0x07ffa,
0x0fff6, 0x3fff1, 0x3fff2, 0x3fff3, 0x3fff4, 0x3fff5, 0x3fff6, 0x3fff7,
0x3fff8, 0x3fff9, 0x3fffa, 0x3fffb, 0x3fffc, 0x3fffd, 0x3fffe, 0x7fffe,
0x7ffff,
};
static const uint8_t t_huffman_env_3_0dB_bits[63] = {
18, 18, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19,
19, 17, 16, 16, 16, 14, 14, 14,
13, 12, 11, 8, 6, 4, 2, 1,
3, 5, 7, 9, 11, 13, 14, 14,
15, 16, 17, 18, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19,
};
static const uint32_t t_huffman_env_3_0dB_codes[63] = {
0x3ffed, 0x3ffee, 0x7ffde, 0x7ffdf, 0x7ffe0, 0x7ffe1, 0x7ffe2, 0x7ffe3,
0x7ffe4, 0x7ffe5, 0x7ffe6, 0x7ffe7, 0x7ffe8, 0x7ffe9, 0x7ffea, 0x7ffeb,
0x7ffec, 0x1fff4, 0x0fff7, 0x0fff9, 0x0fff8, 0x03ffb, 0x03ffa, 0x03ff8,
0x01ffa, 0x00ffc, 0x007fc, 0x000fe, 0x0003e, 0x0000e, 0x00002, 0x00000,
0x00006, 0x0001e, 0x0007e, 0x001fe, 0x007fd, 0x01ffb, 0x03ff9, 0x03ffc,
0x07ffa, 0x0fff6, 0x1fff5, 0x3ffec, 0x7ffed, 0x7ffee, 0x7ffef, 0x7fff0,
0x7fff1, 0x7fff2, 0x7fff3, 0x7fff4, 0x7fff5, 0x7fff6, 0x7fff7, 0x7fff8,
0x7fff9, 0x7fffa, 0x7fffb, 0x7fffc, 0x7fffd, 0x7fffe, 0x7ffff,
};
static const uint8_t f_huffman_env_3_0dB_bits[63] = {
20, 20, 20, 20, 20, 20, 20, 18,
19, 19, 19, 19, 18, 18, 20, 19,
17, 18, 17, 16, 16, 15, 14, 12,
11, 10, 9, 8, 6, 4, 2, 1,
3, 5, 8, 9, 10, 11, 12, 13,
14, 15, 15, 16, 16, 17, 17, 18,
18, 18, 20, 19, 19, 19, 20, 19,
19, 20, 20, 20, 20, 20, 20,
};
static const uint32_t f_huffman_env_3_0dB_codes[63] = {
0xffff0, 0xffff1, 0xffff2, 0xffff3, 0xffff4, 0xffff5, 0xffff6, 0x3fff3,
0x7fff5, 0x7ffee, 0x7ffef, 0x7fff6, 0x3fff4, 0x3fff2, 0xffff7, 0x7fff0,
0x1fff5, 0x3fff0, 0x1fff4, 0x0fff7, 0x0fff6, 0x07ff8, 0x03ffb, 0x00ffd,
0x007fd, 0x003fd, 0x001fd, 0x000fd, 0x0003e, 0x0000e, 0x00002, 0x00000,
0x00006, 0x0001e, 0x000fc, 0x001fc, 0x003fc, 0x007fc, 0x00ffc, 0x01ffc,
0x03ffa, 0x07ff9, 0x07ffa, 0x0fff8, 0x0fff9, 0x1fff6, 0x1fff7, 0x3fff5,
0x3fff6, 0x3fff1, 0xffff8, 0x7fff1, 0x7fff2, 0x7fff3, 0xffff9, 0x7fff7,
0x7fff4, 0xffffa, 0xffffb, 0xffffc, 0xffffd, 0xffffe, 0xfffff,
};
static const uint8_t t_huffman_env_bal_3_0dB_bits[25] = {
13, 13, 13, 13, 13, 13, 13, 12,
8, 7, 4, 3, 1, 2, 5, 6,
9, 13, 13, 13, 13, 13, 13, 14,
14,
};
static const uint16_t t_huffman_env_bal_3_0dB_codes[25] = {
0x1ff2, 0x1ff3, 0x1ff4, 0x1ff5, 0x1ff6, 0x1ff7, 0x1ff8, 0x0ff8,
0x00fe, 0x007e, 0x000e, 0x0006, 0x0000, 0x0002, 0x001e, 0x003e,
0x01fe, 0x1ff9, 0x1ffa, 0x1ffb, 0x1ffc, 0x1ffd, 0x1ffe, 0x3ffe,
0x3fff,
};
static const uint8_t f_huffman_env_bal_3_0dB_bits[25] = {
13, 13, 13, 13, 13, 14, 14, 11,
8, 7, 4, 2, 1, 3, 5, 6,
9, 12, 13, 14, 14, 14, 14, 14,
14,
};
static const uint16_t f_huffman_env_bal_3_0dB_codes[25] = {
0x1ff7, 0x1ff8, 0x1ff9, 0x1ffa, 0x1ffb, 0x3ff8, 0x3ff9, 0x07fc,
0x00fe, 0x007e, 0x000e, 0x0002, 0x0000, 0x0006, 0x001e, 0x003e,
0x01fe, 0x0ffa, 0x1ff6, 0x3ffa, 0x3ffb, 0x3ffc, 0x3ffd, 0x3ffe,
0x3fff,
};
static const uint8_t t_huffman_noise_3_0dB_bits[63] = {
13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 11, 8, 6, 4, 3, 1,
2, 5, 8, 10, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 14, 14,
};
static const uint16_t t_huffman_noise_3_0dB_codes[63] = {
0x1fce, 0x1fcf, 0x1fd0, 0x1fd1, 0x1fd2, 0x1fd3, 0x1fd4, 0x1fd5,
0x1fd6, 0x1fd7, 0x1fd8, 0x1fd9, 0x1fda, 0x1fdb, 0x1fdc, 0x1fdd,
0x1fde, 0x1fdf, 0x1fe0, 0x1fe1, 0x1fe2, 0x1fe3, 0x1fe4, 0x1fe5,
0x1fe6, 0x1fe7, 0x07f2, 0x00fd, 0x003e, 0x000e, 0x0006, 0x0000,
0x0002, 0x001e, 0x00fc, 0x03f8, 0x1fcc, 0x1fe8, 0x1fe9, 0x1fea,
0x1feb, 0x1fec, 0x1fcd, 0x1fed, 0x1fee, 0x1fef, 0x1ff0, 0x1ff1,
0x1ff2, 0x1ff3, 0x1ff4, 0x1ff5, 0x1ff6, 0x1ff7, 0x1ff8, 0x1ff9,
0x1ffa, 0x1ffb, 0x1ffc, 0x1ffd, 0x1ffe, 0x3ffe, 0x3fff,
};
static const uint8_t t_huffman_noise_bal_3_0dB_bits[25] = {
8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 5, 2, 1, 3, 6, 8,
8, 8, 8, 8, 8, 8, 8, 8,
8,
};
static const uint8_t t_huffman_noise_bal_3_0dB_codes[25] = {
0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3,
0xf4, 0xf5, 0x1c, 0x02, 0x00, 0x06, 0x3a, 0xf6,
0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe,
0xff,
};
static const int8_t sbr_offset[6][16] = {
{-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7}, // fs_sbr = 16000 Hz
{-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13}, // fs_sbr = 22050 Hz
{-5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16}, // fs_sbr = 24000 Hz
{-6, -4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16}, // fs_sbr = 32000 Hz
{-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20}, // 44100 Hz <= fs_sbr <= 64000 Hz
{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20, 24}, // 64000 Hz < fs_sbr
};
/* First eight entries repeated at end to simplify SIMD implementations. */
const DECLARE_ALIGNED(16, INTFLOAT, AAC_RENAME(ff_sbr_noise_table))[][2] = {
{Q31(-0.99948153278296f), Q31(-0.59483417516607f)}, {Q31( 0.97113454393991f), Q31(-0.67528515225647f)},
{Q31( 0.14130051758487f), Q31(-0.95090983575689f)}, {Q31(-0.47005496701697f), Q31(-0.37340549728647f)},
{Q31( 0.80705063769351f), Q31( 0.29653668284408f)}, {Q31(-0.38981478896926f), Q31( 0.89572605717087f)},
{Q31(-0.01053049862020f), Q31(-0.66959058036166f)}, {Q31(-0.91266367957293f), Q31(-0.11522938140034f)},
{Q31( 0.54840422910309f), Q31( 0.75221367176302f)}, {Q31( 0.40009252867955f), Q31(-0.98929400334421f)},
{Q31(-0.99867974711855f), Q31(-0.88147068645358f)}, {Q31(-0.95531076805040f), Q31( 0.90908757154593f)},
{Q31(-0.45725933317144f), Q31(-0.56716323646760f)}, {Q31(-0.72929675029275f), Q31(-0.98008272727324f)},
{Q31( 0.75622801399036f), Q31( 0.20950329995549f)}, {Q31( 0.07069442601050f), Q31(-0.78247898470706f)},
{Q31( 0.74496252926055f), Q31(-0.91169004445807f)}, {Q31(-0.96440182703856f), Q31(-0.94739918296622f)},
{Q31( 0.30424629369539f), Q31(-0.49438267012479f)}, {Q31( 0.66565033746925f), Q31( 0.64652935542491f)},
{Q31( 0.91697008020594f), Q31( 0.17514097332009f)}, {Q31(-0.70774918760427f), Q31( 0.52548653416543f)},
{Q31(-0.70051415345560f), Q31(-0.45340028808763f)}, {Q31(-0.99496513054797f), Q31(-0.90071908066973f)},
{Q31( 0.98164490790123f), Q31(-0.77463155528697f)}, {Q31(-0.54671580548181f), Q31(-0.02570928536004f)},
{Q31(-0.01689629065389f), Q31( 0.00287506445732f)}, {Q31(-0.86110349531986f), Q31( 0.42548583726477f)},
{Q31(-0.98892980586032f), Q31(-0.87881132267556f)}, {Q31( 0.51756627678691f), Q31( 0.66926784710139f)},
{Q31(-0.99635026409640f), Q31(-0.58107730574765f)}, {Q31(-0.99969370862163f), Q31( 0.98369989360250f)},
{Q31( 0.55266258627194f), Q31( 0.59449057465591f)}, {Q31( 0.34581177741673f), Q31( 0.94879421061866f)},
{Q31( 0.62664209577999f), Q31(-0.74402970906471f)}, {Q31(-0.77149701404973f), Q31(-0.33883658042801f)},
{Q31(-0.91592244254432f), Q31( 0.03687901376713f)}, {Q31(-0.76285492357887f), Q31(-0.91371867919124f)},
{Q31( 0.79788337195331f), Q31(-0.93180971199849f)}, {Q31( 0.54473080610200f), Q31(-0.11919206037186f)},
{Q31(-0.85639281671058f), Q31( 0.42429854760451f)}, {Q31(-0.92882402971423f), Q31( 0.27871809078609f)},
{Q31(-0.11708371046774f), Q31(-0.99800843444966f)}, {Q31( 0.21356749817493f), Q31(-0.90716295627033f)},
{Q31(-0.76191692573909f), Q31( 0.99768118356265f)}, {Q31( 0.98111043100884f), Q31(-0.95854459734407f)},
{Q31(-0.85913269895572f), Q31( 0.95766566168880f)}, {Q31(-0.93307242253692f), Q31( 0.49431757696466f)},
{Q31( 0.30485754879632f), Q31(-0.70540034357529f)}, {Q31( 0.85289650925190f), Q31( 0.46766131791044f)},
{Q31( 0.91328082618125f), Q31(-0.99839597361769f)}, {Q31(-0.05890199924154f), Q31( 0.70741827819497f)},
{Q31( 0.28398686150148f), Q31( 0.34633555702188f)}, {Q31( 0.95258164539612f), Q31(-0.54893416026939f)},
{Q31(-0.78566324168507f), Q31(-0.75568541079691f)}, {Q31(-0.95789495447877f), Q31(-0.20423194696966f)},
{Q31( 0.82411158711197f), Q31( 0.96654618432562f)}, {Q31(-0.65185446735885f), Q31(-0.88734990773289f)},
{Q31(-0.93643603134666f), Q31( 0.99870790442385f)}, {Q31( 0.91427159529618f), Q31(-0.98290505544444f)},
{Q31(-0.70395684036886f), Q31( 0.58796798221039f)}, {Q31( 0.00563771969365f), Q31( 0.61768196727244f)},
{Q31( 0.89065051931895f), Q31( 0.52783352697585f)}, {Q31(-0.68683707712762f), Q31( 0.80806944710339f)},
{Q31( 0.72165342518718f), Q31(-0.69259857349564f)}, {Q31(-0.62928247730667f), Q31( 0.13627037407335f)},
{Q31( 0.29938434065514f), Q31(-0.46051329682246f)}, {Q31(-0.91781958879280f), Q31(-0.74012716684186f)},
{Q31( 0.99298717043688f), Q31( 0.40816610075661f)}, {Q31( 0.82368298622748f), Q31(-0.74036047190173f)},
{Q31(-0.98512833386833f), Q31(-0.99972330709594f)}, {Q31(-0.95915368242257f), Q31(-0.99237800466040f)},
{Q31(-0.21411126572790f), Q31(-0.93424819052545f)}, {Q31(-0.68821476106884f), Q31(-0.26892306315457f)},
{Q31( 0.91851997982317f), Q31( 0.09358228901785f)}, {Q31(-0.96062769559127f), Q31( 0.36099095133739f)},
{Q31( 0.51646184922287f), Q31(-0.71373332873917f)}, {Q31( 0.61130721139669f), Q31( 0.46950141175917f)},
{Q31( 0.47336129371299f), Q31(-0.27333178296162f)}, {Q31( 0.90998308703519f), Q31( 0.96715662938132f)},
{Q31( 0.44844799194357f), Q31( 0.99211574628306f)}, {Q31( 0.66614891079092f), Q31( 0.96590176169121f)},
{Q31( 0.74922239129237f), Q31(-0.89879858826087f)}, {Q31(-0.99571588506485f), Q31( 0.52785521494349f)},
{Q31( 0.97401082477563f), Q31(-0.16855870075190f)}, {Q31( 0.72683747733879f), Q31(-0.48060774432251f)},
{Q31( 0.95432193457128f), Q31( 0.68849603408441f)}, {Q31(-0.72962208425191f), Q31(-0.76608443420917f)},
{Q31(-0.85359479233537f), Q31( 0.88738125901579f)}, {Q31(-0.81412430338535f), Q31(-0.97480768049637f)},
{Q31(-0.87930772356786f), Q31( 0.74748307690436f)}, {Q31(-0.71573331064977f), Q31(-0.98570608178923f)},
{Q31( 0.83524300028228f), Q31( 0.83702537075163f)}, {Q31(-0.48086065601423f), Q31(-0.98848504923531f)},
{Q31( 0.97139128574778f), Q31( 0.80093621198236f)}, {Q31( 0.51992825347895f), Q31( 0.80247631400510f)},
{Q31(-0.00848591195325f), Q31(-0.76670128000486f)}, {Q31(-0.70294374303036f), Q31( 0.55359910445577f)},
{Q31(-0.95894428168140f), Q31(-0.43265504344783f)}, {Q31( 0.97079252950321f), Q31( 0.09325857238682f)},
{Q31(-0.92404293670797f), Q31( 0.85507704027855f)}, {Q31(-0.69506469500450f), Q31( 0.98633412625459f)},
{Q31( 0.26559203620024f), Q31( 0.73314307966524f)}, {Q31( 0.28038443336943f), Q31( 0.14537913654427f)},
{Q31(-0.74138124825523f), Q31( 0.99310339807762f)}, {Q31(-0.01752795995444f), Q31(-0.82616635284178f)},
{Q31(-0.55126773094930f), Q31(-0.98898543862153f)}, {Q31( 0.97960898850996f), Q31(-0.94021446752851f)},
{Q31(-0.99196309146936f), Q31( 0.67019017358456f)}, {Q31(-0.67684928085260f), Q31( 0.12631491649378f)},
{Q31( 0.09140039465500f), Q31(-0.20537731453108f)}, {Q31(-0.71658965751996f), Q31(-0.97788200391224f)},
{Q31( 0.81014640078925f), Q31( 0.53722648362443f)}, {Q31( 0.40616991671205f), Q31(-0.26469008598449f)},
{Q31(-0.67680188682972f), Q31( 0.94502052337695f)}, {Q31( 0.86849774348749f), Q31(-0.18333598647899f)},
{Q31(-0.99500381284851f), Q31(-0.02634122068550f)}, {Q31( 0.84329189340667f), Q31( 0.10406957462213f)},
{Q31(-0.09215968531446f), Q31( 0.69540012101253f)}, {Q31( 0.99956173327206f), Q31(-0.12358542001404f)},
{Q31(-0.79732779473535f), Q31(-0.91582524736159f)}, {Q31( 0.96349973642406f), Q31( 0.96640458041000f)},
{Q31(-0.79942778496547f), Q31( 0.64323902822857f)}, {Q31(-0.11566039853896f), Q31( 0.28587846253726f)},
{Q31(-0.39922954514662f), Q31( 0.94129601616966f)}, {Q31( 0.99089197565987f), Q31(-0.92062625581587f)},
{Q31( 0.28631285179909f), Q31(-0.91035047143603f)}, {Q31(-0.83302725605608f), Q31(-0.67330410892084f)},
{Q31( 0.95404443402072f), Q31( 0.49162765398743f)}, {Q31(-0.06449863579434f), Q31( 0.03250560813135f)},
{Q31(-0.99575054486311f), Q31( 0.42389784469507f)}, {Q31(-0.65501142790847f), Q31( 0.82546114655624f)},
{Q31(-0.81254441908887f), Q31(-0.51627234660629f)}, {Q31(-0.99646369485481f), Q31( 0.84490533520752f)},
{Q31( 0.00287840603348f), Q31( 0.64768261158166f)}, {Q31( 0.70176989408455f), Q31(-0.20453028573322f)},
{Q31( 0.96361882270190f), Q31( 0.40706967140989f)}, {Q31(-0.68883758192426f), Q31( 0.91338958840772f)},
{Q31(-0.34875585502238f), Q31( 0.71472290693300f)}, {Q31( 0.91980081243087f), Q31( 0.66507455644919f)},
{Q31(-0.99009048343881f), Q31( 0.85868021604848f)}, {Q31( 0.68865791458395f), Q31( 0.55660316809678f)},
{Q31(-0.99484402129368f), Q31(-0.20052559254934f)}, {Q31( 0.94214511408023f), Q31(-0.99696425367461f)},
{Q31(-0.67414626793544f), Q31( 0.49548221180078f)}, {Q31(-0.47339353684664f), Q31(-0.85904328834047f)},
{Q31( 0.14323651387360f), Q31(-0.94145598222488f)}, {Q31(-0.29268293575672f), Q31( 0.05759224927952f)},
{Q31( 0.43793861458754f), Q31(-0.78904969892724f)}, {Q31(-0.36345126374441f), Q31( 0.64874435357162f)},
{Q31(-0.08750604656825f), Q31( 0.97686944362527f)}, {Q31(-0.96495267812511f), Q31(-0.53960305946511f)},
{Q31( 0.55526940659947f), Q31( 0.78891523734774f)}, {Q31( 0.73538215752630f), Q31( 0.96452072373404f)},
{Q31(-0.30889773919437f), Q31(-0.80664389776860f)}, {Q31( 0.03574995626194f), Q31(-0.97325616900959f)},
{Q31( 0.98720684660488f), Q31( 0.48409133691962f)}, {Q31(-0.81689296271203f), Q31(-0.90827703628298f)},
{Q31( 0.67866860118215f), Q31( 0.81284503870856f)}, {Q31(-0.15808569732583f), Q31( 0.85279555024382f)},
{Q31( 0.80723395114371f), Q31(-0.24717418514605f)}, {Q31( 0.47788757329038f), Q31(-0.46333147839295f)},
{Q31( 0.96367554763201f), Q31( 0.38486749303242f)}, {Q31(-0.99143875716818f), Q31(-0.24945277239809f)},
{Q31( 0.83081876925833f), Q31(-0.94780851414763f)}, {Q31(-0.58753191905341f), Q31( 0.01290772389163f)},
{Q31( 0.95538108220960f), Q31(-0.85557052096538f)}, {Q31(-0.96490920476211f), Q31(-0.64020970923102f)},
{Q31(-0.97327101028521f), Q31( 0.12378128133110f)}, {Q31( 0.91400366022124f), Q31( 0.57972471346930f)},
{Q31(-0.99925837363824f), Q31( 0.71084847864067f)}, {Q31(-0.86875903507313f), Q31(-0.20291699203564f)},
{Q31(-0.26240034795124f), Q31(-0.68264554369108f)}, {Q31(-0.24664412953388f), Q31(-0.87642273115183f)},
{Q31( 0.02416275806869f), Q31( 0.27192914288905f)}, {Q31( 0.82068619590515f), Q31(-0.85087787994476f)},
{Q31( 0.88547373760759f), Q31(-0.89636802901469f)}, {Q31(-0.18173078152226f), Q31(-0.26152145156800f)},
{Q31( 0.09355476558534f), Q31( 0.54845123045604f)}, {Q31(-0.54668414224090f), Q31( 0.95980774020221f)},
{Q31( 0.37050990604091f), Q31(-0.59910140383171f)}, {Q31(-0.70373594262891f), Q31( 0.91227665827081f)},
{Q31(-0.34600785879594f), Q31(-0.99441426144200f)}, {Q31(-0.68774481731008f), Q31(-0.30238837956299f)},
{Q31(-0.26843291251234f), Q31( 0.83115668004362f)}, {Q31( 0.49072334613242f), Q31(-0.45359708737775f)},
{Q31( 0.38975993093975f), Q31( 0.95515358099121f)}, {Q31(-0.97757125224150f), Q31( 0.05305894580606f)},
{Q31(-0.17325552859616f), Q31(-0.92770672250494f)}, {Q31( 0.99948035025744f), Q31( 0.58285545563426f)},
{Q31(-0.64946246527458f), Q31( 0.68645507104960f)}, {Q31(-0.12016920576437f), Q31(-0.57147322153312f)},
{Q31(-0.58947456517751f), Q31(-0.34847132454388f)}, {Q31(-0.41815140454465f), Q31( 0.16276422358861f)},
{Q31( 0.99885650204884f), Q31( 0.11136095490444f)}, {Q31(-0.56649614128386f), Q31(-0.90494866361587f)},
{Q31( 0.94138021032330f), Q31( 0.35281916733018f)}, {Q31(-0.75725076534641f), Q31( 0.53650549640587f)},
{Q31( 0.20541973692630f), Q31(-0.94435144369918f)}, {Q31( 0.99980371023351f), Q31( 0.79835913565599f)},
{Q31( 0.29078277605775f), Q31( 0.35393777921520f)}, {Q31(-0.62858772103030f), Q31( 0.38765693387102f)},
{Q31( 0.43440904467688f), Q31(-0.98546330463232f)}, {Q31(-0.98298583762390f), Q31( 0.21021524625209f)},
{Q31( 0.19513029146934f), Q31(-0.94239832251867f)}, {Q31(-0.95476662400101f), Q31( 0.98364554179143f)},
{Q31( 0.93379635304810f), Q31(-0.70881994583682f)}, {Q31(-0.85235410573336f), Q31(-0.08342347966410f)},
{Q31(-0.86425093011245f), Q31(-0.45795025029466f)}, {Q31( 0.38879779059045f), Q31( 0.97274429344593f)},
{Q31( 0.92045124735495f), Q31(-0.62433652524220f)}, {Q31( 0.89162532251878f), Q31( 0.54950955570563f)},
{Q31(-0.36834336949252f), Q31( 0.96458298020975f)}, {Q31( 0.93891760988045f), Q31(-0.89968353740388f)},
{Q31( 0.99267657565094f), Q31(-0.03757034316958f)}, {Q31(-0.94063471614176f), Q31( 0.41332338538963f)},
{Q31( 0.99740224117019f), Q31(-0.16830494996370f)}, {Q31(-0.35899413170555f), Q31(-0.46633226649613f)},
{Q31( 0.05237237274947f), Q31(-0.25640361602661f)}, {Q31( 0.36703583957424f), Q31(-0.38653265641875f)},
{Q31( 0.91653180367913f), Q31(-0.30587628726597f)}, {Q31( 0.69000803499316f), Q31( 0.90952171386132f)},
{Q31(-0.38658751133527f), Q31( 0.99501571208985f)}, {Q31(-0.29250814029851f), Q31( 0.37444994344615f)},
{Q31(-0.60182204677608f), Q31( 0.86779651036123f)}, {Q31(-0.97418588163217f), Q31( 0.96468523666475f)},
{Q31( 0.88461574003963f), Q31( 0.57508405276414f)}, {Q31( 0.05198933055162f), Q31( 0.21269661669964f)},
{Q31(-0.53499621979720f), Q31( 0.97241553731237f)}, {Q31(-0.49429560226497f), Q31( 0.98183865291903f)},
{Q31(-0.98935142339139f), Q31(-0.40249159006933f)}, {Q31(-0.98081380091130f), Q31(-0.72856895534041f)},
{Q31(-0.27338148835532f), Q31( 0.99950922447209f)}, {Q31( 0.06310802338302f), Q31(-0.54539587529618f)},
{Q31(-0.20461677199539f), Q31(-0.14209977628489f)}, {Q31( 0.66223843141647f), Q31( 0.72528579940326f)},
{Q31(-0.84764345483665f), Q31( 0.02372316801261f)}, {Q31(-0.89039863483811f), Q31( 0.88866581484602f)},
{Q31( 0.95903308477986f), Q31( 0.76744927173873f)}, {Q31( 0.73504123909879f), Q31(-0.03747203173192f)},
{Q31(-0.31744434966056f), Q31(-0.36834111883652f)}, {Q31(-0.34110827591623f), Q31( 0.40211222807691f)},
{Q31( 0.47803883714199f), Q31(-0.39423219786288f)}, {Q31( 0.98299195879514f), Q31( 0.01989791390047f)},
{Q31(-0.30963073129751f), Q31(-0.18076720599336f)}, {Q31( 0.99992588229018f), Q31(-0.26281872094289f)},
{Q31(-0.93149731080767f), Q31(-0.98313162570490f)}, {Q31( 0.99923472302773f), Q31(-0.80142993767554f)},
{Q31(-0.26024169633417f), Q31(-0.75999759855752f)}, {Q31(-0.35712514743563f), Q31( 0.19298963768574f)},
{Q31(-0.99899084509530f), Q31( 0.74645156992493f)}, {Q31( 0.86557171579452f), Q31( 0.55593866696299f)},
{Q31( 0.33408042438752f), Q31( 0.86185953874709f)}, {Q31( 0.99010736374716f), Q31( 0.04602397576623f)},
{Q31(-0.66694269691195f), Q31(-0.91643611810148f)}, {Q31( 0.64016792079480f), Q31( 0.15649530836856f)},
{Q31( 0.99570534804836f), Q31( 0.45844586038111f)}, {Q31(-0.63431466947340f), Q31( 0.21079116459234f)},
{Q31(-0.07706847005931f), Q31(-0.89581437101329f)}, {Q31( 0.98590090577724f), Q31( 0.88241721133981f)},
{Q31( 0.80099335254678f), Q31(-0.36851896710853f)}, {Q31( 0.78368131392666f), Q31( 0.45506999802597f)},
{Q31( 0.08707806671691f), Q31( 0.80938994918745f)}, {Q31(-0.86811883080712f), Q31( 0.39347308654705f)},
{Q31(-0.39466529740375f), Q31(-0.66809432114456f)}, {Q31( 0.97875325649683f), Q31(-0.72467840967746f)},
{Q31(-0.95038560288864f), Q31( 0.89563219587625f)}, {Q31( 0.17005239424212f), Q31( 0.54683053962658f)},
{Q31(-0.76910792026848f), Q31(-0.96226617549298f)}, {Q31( 0.99743281016846f), Q31( 0.42697157037567f)},
{Q31( 0.95437383549973f), Q31( 0.97002324109952f)}, {Q31( 0.99578905365569f), Q31(-0.54106826257356f)},
{Q31( 0.28058259829990f), Q31(-0.85361420634036f)}, {Q31( 0.85256524470573f), Q31(-0.64567607735589f)},
{Q31(-0.50608540105128f), Q31(-0.65846015480300f)}, {Q31(-0.97210735183243f), Q31(-0.23095213067791f)},
{Q31( 0.95424048234441f), Q31(-0.99240147091219f)}, {Q31(-0.96926570524023f), Q31( 0.73775654896574f)},
{Q31( 0.30872163214726f), Q31( 0.41514960556126f)}, {Q31(-0.24523839572639f), Q31( 0.63206633394807f)},
{Q31(-0.33813265086024f), Q31(-0.38661779441897f)}, {Q31(-0.05826828420146f), Q31(-0.06940774188029f)},
{Q31(-0.22898461455054f), Q31( 0.97054853316316f)}, {Q31(-0.18509915019881f), Q31( 0.47565762892084f)},
{Q31(-0.10488238045009f), Q31(-0.87769947402394f)}, {Q31(-0.71886586182037f), Q31( 0.78030982480538f)},
{Q31( 0.99793873738654f), Q31( 0.90041310491497f)}, {Q31( 0.57563307626120f), Q31(-0.91034337352097f)},
{Q31( 0.28909646383717f), Q31( 0.96307783970534f)}, {Q31( 0.42188998312520f), Q31( 0.48148651230437f)},
{Q31( 0.93335049681047f), Q31(-0.43537023883588f)}, {Q31(-0.97087374418267f), Q31( 0.86636445711364f)},
{Q31( 0.36722871286923f), Q31( 0.65291654172961f)}, {Q31(-0.81093025665696f), Q31( 0.08778370229363f)},
{Q31(-0.26240603062237f), Q31(-0.92774095379098f)}, {Q31( 0.83996497984604f), Q31( 0.55839849139647f)},
{Q31(-0.99909615720225f), Q31(-0.96024605713970f)}, {Q31( 0.74649464155061f), Q31( 0.12144893606462f)},
{Q31(-0.74774595569805f), Q31(-0.26898062008959f)}, {Q31( 0.95781667469567f), Q31(-0.79047927052628f)},
{Q31( 0.95472308713099f), Q31(-0.08588776019550f)}, {Q31( 0.48708332746299f), Q31( 0.99999041579432f)},
{Q31( 0.46332038247497f), Q31( 0.10964126185063f)}, {Q31(-0.76497004940162f), Q31( 0.89210929242238f)},
{Q31( 0.57397389364339f), Q31( 0.35289703373760f)}, {Q31( 0.75374316974495f), Q31( 0.96705214651335f)},
{Q31(-0.59174397685714f), Q31(-0.89405370422752f)}, {Q31( 0.75087906691890f), Q31(-0.29612672982396f)},
{Q31(-0.98607857336230f), Q31( 0.25034911730023f)}, {Q31(-0.40761056640505f), Q31(-0.90045573444695f)},
{Q31( 0.66929266740477f), Q31( 0.98629493401748f)}, {Q31(-0.97463695257310f), Q31(-0.00190223301301f)},
{Q31( 0.90145509409859f), Q31( 0.99781390365446f)}, {Q31(-0.87259289048043f), Q31( 0.99233587353666f)},
{Q31(-0.91529461447692f), Q31(-0.15698707534206f)}, {Q31(-0.03305738840705f), Q31(-0.37205262859764f)},
{Q31( 0.07223051368337f), Q31(-0.88805001733626f)}, {Q31( 0.99498012188353f), Q31( 0.97094358113387f)},
{Q31(-0.74904939500519f), Q31( 0.99985483641521f)}, {Q31( 0.04585228574211f), Q31( 0.99812337444082f)},
{Q31(-0.89054954257993f), Q31(-0.31791913188064f)}, {Q31(-0.83782144651251f), Q31( 0.97637632547466f)},
{Q31( 0.33454804933804f), Q31(-0.86231516800408f)}, {Q31(-0.99707579362824f), Q31( 0.93237990079441f)},
{Q31(-0.22827527843994f), Q31( 0.18874759397997f)}, {Q31( 0.67248046289143f), Q31(-0.03646211390569f)},
{Q31(-0.05146538187944f), Q31(-0.92599700120679f)}, {Q31( 0.99947295749905f), Q31( 0.93625229707912f)},
{Q31( 0.66951124390363f), Q31( 0.98905825623893f)}, {Q31(-0.99602956559179f), Q31(-0.44654715757688f)},
{Q31( 0.82104905483590f), Q31( 0.99540741724928f)}, {Q31( 0.99186510988782f), Q31( 0.72023001312947f)},
{Q31(-0.65284592392918f), Q31( 0.52186723253637f)}, {Q31( 0.93885443798188f), Q31(-0.74895312615259f)},
{Q31( 0.96735248738388f), Q31( 0.90891816978629f)}, {Q31(-0.22225968841114f), Q31( 0.57124029781228f)},
{Q31(-0.44132783753414f), Q31(-0.92688840659280f)}, {Q31(-0.85694974219574f), Q31( 0.88844532719844f)},
{Q31( 0.91783042091762f), Q31(-0.46356892383970f)}, {Q31( 0.72556974415690f), Q31(-0.99899555770747f)},
{Q31(-0.99711581834508f), Q31( 0.58211560180426f)}, {Q31( 0.77638976371966f), Q31( 0.94321834873819f)},
{Q31( 0.07717324253925f), Q31( 0.58638399856595f)}, {Q31(-0.56049829194163f), Q31( 0.82522301569036f)},
{Q31( 0.98398893639988f), Q31( 0.39467440420569f)}, {Q31( 0.47546946844938f), Q31( 0.68613044836811f)},
{Q31( 0.65675089314631f), Q31( 0.18331637134880f)}, {Q31( 0.03273375457980f), Q31(-0.74933109564108f)},
{Q31(-0.38684144784738f), Q31( 0.51337349030406f)}, {Q31(-0.97346267944545f), Q31(-0.96549364384098f)},
{Q31(-0.53282156061942f), Q31(-0.91423265091354f)}, {Q31( 0.99817310731176f), Q31( 0.61133572482148f)},
{Q31(-0.50254500772635f), Q31(-0.88829338134294f)}, {Q31( 0.01995873238855f), Q31( 0.85223515096765f)},
{Q31( 0.99930381973804f), Q31( 0.94578896296649f)}, {Q31( 0.82907767600783f), Q31(-0.06323442598128f)},
{Q31(-0.58660709669728f), Q31( 0.96840773806582f)}, {Q31(-0.17573736667267f), Q31(-0.48166920859485f)},
{Q31( 0.83434292401346f), Q31(-0.13023450646997f)}, {Q31( 0.05946491307025f), Q31( 0.20511047074866f)},
{Q31( 0.81505484574602f), Q31(-0.94685947861369f)}, {Q31(-0.44976380954860f), Q31( 0.40894572671545f)},
{Q31(-0.89746474625671f), Q31( 0.99846578838537f)}, {Q31( 0.39677256130792f), Q31(-0.74854668609359f)},
{Q31(-0.07588948563079f), Q31( 0.74096214084170f)}, {Q31( 0.76343198951445f), Q31( 0.41746629422634f)},
{Q31(-0.74490104699626f), Q31( 0.94725911744610f)}, {Q31( 0.64880119792759f), Q31( 0.41336660830571f)},
{Q31( 0.62319537462542f), Q31(-0.93098313552599f)}, {Q31( 0.42215817594807f), Q31(-0.07712787385208f)},
{Q31( 0.02704554141885f), Q31(-0.05417518053666f)}, {Q31( 0.80001773566818f), Q31( 0.91542195141039f)},
{Q31(-0.79351832348816f), Q31(-0.36208897989136f)}, {Q31( 0.63872359151636f), Q31( 0.08128252493444f)},
{Q31( 0.52890520960295f), Q31( 0.60048872455592f)}, {Q31( 0.74238552914587f), Q31( 0.04491915291044f)},
{Q31( 0.99096131449250f), Q31(-0.19451182854402f)}, {Q31(-0.80412329643109f), Q31(-0.88513818199457f)},
{Q31(-0.64612616129736f), Q31( 0.72198674804544f)}, {Q31( 0.11657770663191f), Q31(-0.83662833815041f)},
{Q31(-0.95053182488101f), Q31(-0.96939905138082f)}, {Q31(-0.62228872928622f), Q31( 0.82767262846661f)},
{Q31( 0.03004475787316f), Q31(-0.99738896333384f)}, {Q31(-0.97987214341034f), Q31( 0.36526129686425f)},
{Q31(-0.99986980746200f), Q31(-0.36021610299715f)}, {Q31( 0.89110648599879f), Q31(-0.97894250343044f)},
{Q31( 0.10407960510582f), Q31( 0.77357793811619f)}, {Q31( 0.95964737821728f), Q31(-0.35435818285502f)},
{Q31( 0.50843233159162f), Q31( 0.96107691266205f)}, {Q31( 0.17006334670615f), Q31(-0.76854025314829f)},
{Q31( 0.25872675063360f), Q31( 0.99893303933816f)}, {Q31(-0.01115998681937f), Q31( 0.98496019742444f)},
{Q31(-0.79598702973261f), Q31( 0.97138411318894f)}, {Q31(-0.99264708948101f), Q31(-0.99542822402536f)},
{Q31(-0.99829663752818f), Q31( 0.01877138824311f)}, {Q31(-0.70801016548184f), Q31( 0.33680685948117f)},
{Q31(-0.70467057786826f), Q31( 0.93272777501857f)}, {Q31( 0.99846021905254f), Q31(-0.98725746254433f)},
{Q31(-0.63364968534650f), Q31(-0.16473594423746f)}, {Q31(-0.16258217500792f), Q31(-0.95939125400802f)},
{Q31(-0.43645594360633f), Q31(-0.94805030113284f)}, {Q31(-0.99848471702976f), Q31( 0.96245166923809f)},
{Q31(-0.16796458968998f), Q31(-0.98987511890470f)}, {Q31(-0.87979225745213f), Q31(-0.71725725041680f)},
{Q31( 0.44183099021786f), Q31(-0.93568974498761f)}, {Q31( 0.93310180125532f), Q31(-0.99913308068246f)},
{Q31(-0.93941931782002f), Q31(-0.56409379640356f)}, {Q31(-0.88590003188677f), Q31( 0.47624600491382f)},
{Q31( 0.99971463703691f), Q31(-0.83889954253462f)}, {Q31(-0.75376385639978f), Q31( 0.00814643438625f)},
{Q31( 0.93887685615875f), Q31(-0.11284528204636f)}, {Q31( 0.85126435782309f), Q31( 0.52349251543547f)},
{Q31( 0.39701421446381f), Q31( 0.81779634174316f)}, {Q31(-0.37024464187437f), Q31(-0.87071656222959f)},
{Q31(-0.36024828242896f), Q31( 0.34655735648287f)}, {Q31(-0.93388812549209f), Q31(-0.84476541096429f)},
{Q31(-0.65298804552119f), Q31(-0.18439575450921f)}, {Q31( 0.11960319006843f), Q31( 0.99899346780168f)},
{Q31( 0.94292565553160f), Q31( 0.83163906518293f)}, {Q31( 0.75081145286948f), Q31(-0.35533223142265f)},
{Q31( 0.56721979748394f), Q31(-0.24076836414499f)}, {Q31( 0.46857766746029f), Q31(-0.30140233457198f)},
{Q31( 0.97312313923635f), Q31(-0.99548191630031f)}, {Q31(-0.38299976567017f), Q31( 0.98516909715427f)},
{Q31( 0.41025800019463f), Q31( 0.02116736935734f)}, {Q31( 0.09638062008048f), Q31( 0.04411984381457f)},
{Q31(-0.85283249275397f), Q31( 0.91475563922421f)}, {Q31( 0.88866808958124f), Q31(-0.99735267083226f)},
{Q31(-0.48202429536989f), Q31(-0.96805608884164f)}, {Q31( 0.27572582416567f), Q31( 0.58634753335832f)},
{Q31(-0.65889129659168f), Q31( 0.58835634138583f)}, {Q31( 0.98838086953732f), Q31( 0.99994349600236f)},
{Q31(-0.20651349620689f), Q31( 0.54593044066355f)}, {Q31(-0.62126416356920f), Q31(-0.59893681700392f)},
{Q31( 0.20320105410437f), Q31(-0.86879180355289f)}, {Q31(-0.97790548600584f), Q31( 0.96290806999242f)},
{Q31( 0.11112534735126f), Q31( 0.21484763313301f)}, {Q31(-0.41368337314182f), Q31( 0.28216837680365f)},
{Q31( 0.24133038992960f), Q31( 0.51294362630238f)}, {Q31(-0.66393410674885f), Q31(-0.08249679629081f)},
{Q31(-0.53697829178752f), Q31(-0.97649903936228f)}, {Q31(-0.97224737889348f), Q31( 0.22081333579837f)},
{Q31( 0.87392477144549f), Q31(-0.12796173740361f)}, {Q31( 0.19050361015753f), Q31( 0.01602615387195f)},
{Q31(-0.46353441212724f), Q31(-0.95249041539006f)}, {Q31(-0.07064096339021f), Q31(-0.94479803205886f)},
{Q31(-0.92444085484466f), Q31(-0.10457590187436f)}, {Q31(-0.83822593578728f), Q31(-0.01695043208885f)},
{Q31( 0.75214681811150f), Q31(-0.99955681042665f)}, {Q31(-0.42102998829339f), Q31( 0.99720941999394f)},
{Q31(-0.72094786237696f), Q31(-0.35008961934255f)}, {Q31( 0.78843311019251f), Q31( 0.52851398958271f)},
{Q31( 0.97394027897442f), Q31(-0.26695944086561f)}, {Q31( 0.99206463477946f), Q31(-0.57010120849429f)},
{Q31( 0.76789609461795f), Q31(-0.76519356730966f)}, {Q31(-0.82002421836409f), Q31(-0.73530179553767f)},
{Q31( 0.81924990025724f), Q31( 0.99698425250579f)}, {Q31(-0.26719850873357f), Q31( 0.68903369776193f)},
{Q31(-0.43311260380975f), Q31( 0.85321815947490f)}, {Q31( 0.99194979673836f), Q31( 0.91876249766422f)},
{Q31(-0.80692001248487f), Q31(-0.32627540663214f)}, {Q31( 0.43080003649976f), Q31(-0.21919095636638f)},
{Q31( 0.67709491937357f), Q31(-0.95478075822906f)}, {Q31( 0.56151770568316f), Q31(-0.70693811747778f)},
{Q31( 0.10831862810749f), Q31(-0.08628837174592f)}, {Q31( 0.91229417540436f), Q31(-0.65987351408410f)},
{Q31(-0.48972893932274f), Q31( 0.56289246362686f)}, {Q31(-0.89033658689697f), Q31(-0.71656563987082f)},
{Q31( 0.65269447475094f), Q31( 0.65916004833932f)}, {Q31( 0.67439478141121f), Q31(-0.81684380846796f)},
{Q31(-0.47770832416973f), Q31(-0.16789556203025f)}, {Q31(-0.99715979260878f), Q31(-0.93565784007648f)},
{Q31(-0.90889593602546f), Q31( 0.62034397054380f)}, {Q31(-0.06618622548177f), Q31(-0.23812217221359f)},
{Q31( 0.99430266919728f), Q31( 0.18812555317553f)}, {Q31( 0.97686402381843f), Q31(-0.28664534366620f)},
{Q31( 0.94813650221268f), Q31(-0.97506640027128f)}, {Q31(-0.95434497492853f), Q31(-0.79607978501983f)},
{Q31(-0.49104783137150f), Q31( 0.32895214359663f)}, {Q31( 0.99881175120751f), Q31( 0.88993983831354f)},
{Q31( 0.50449166760303f), Q31(-0.85995072408434f)}, {Q31( 0.47162891065108f), Q31(-0.18680204049569f)},
{Q31(-0.62081581361840f), Q31( 0.75000676218956f)}, {Q31(-0.43867015250812f), Q31( 0.99998069244322f)},
{Q31( 0.98630563232075f), Q31(-0.53578899600662f)}, {Q31(-0.61510362277374f), Q31(-0.89515019899997f)},
{Q31(-0.03841517601843f), Q31(-0.69888815681179f)}, {Q31(-0.30102157304644f), Q31(-0.07667808922205f)},
{Q31( 0.41881284182683f), Q31( 0.02188098922282f)}, {Q31(-0.86135454941237f), Q31( 0.98947480909359f)},
{Q31( 0.67226861393788f), Q31(-0.13494389011014f)}, {Q31(-0.70737398842068f), Q31(-0.76547349325992f)},
{Q31( 0.94044946687963f), Q31( 0.09026201157416f)}, {Q31(-0.82386352534327f), Q31( 0.08924768823676f)},
{Q31(-0.32070666698656f), Q31( 0.50143421908753f)}, {Q31( 0.57593163224487f), Q31(-0.98966422921509f)},
{Q31(-0.36326018419965f), Q31( 0.07440243123228f)}, {Q31( 0.99979044674350f), Q31(-0.14130287347405f)},
{Q31(-0.92366023326932f), Q31(-0.97979298068180f)}, {Q31(-0.44607178518598f), Q31(-0.54233252016394f)},
{Q31( 0.44226800932956f), Q31( 0.71326756742752f)}, {Q31( 0.03671907158312f), Q31( 0.63606389366675f)},
{Q31( 0.52175424682195f), Q31(-0.85396826735705f)}, {Q31(-0.94701139690956f), Q31(-0.01826348194255f)},
{Q31(-0.98759606946049f), Q31( 0.82288714303073f)}, {Q31( 0.87434794743625f), Q31( 0.89399495655433f)},
{Q31(-0.93412041758744f), Q31( 0.41374052024363f)}, {Q31( 0.96063943315511f), Q31( 0.93116709541280f)},
{Q31( 0.97534253457837f), Q31( 0.86150930812689f)}, {Q31( 0.99642466504163f), Q31( 0.70190043427512f)},
{Q31(-0.94705089665984f), Q31(-0.29580042814306f)}, {Q31( 0.91599807087376f), Q31(-0.98147830385781f)},
// Start of duplicated table
{Q31(-0.99948153278296f), Q31(-0.59483417516607f)}, {Q31( 0.97113454393991f), Q31(-0.67528515225647f)},
{Q31( 0.14130051758487f), Q31(-0.95090983575689f)}, {Q31(-0.47005496701697f), Q31(-0.37340549728647f)},
{Q31( 0.80705063769351f), Q31( 0.29653668284408f)}, {Q31(-0.38981478896926f), Q31( 0.89572605717087f)},
{Q31(-0.01053049862020f), Q31(-0.66959058036166f)}, {Q31(-0.91266367957293f), Q31(-0.11522938140034f)},
};
#endif /* AVCODEC_AACSBRDATA_H */

View File

@ -0,0 +1,186 @@
/*
* AAC data declarations
* Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org )
* Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com )
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAC data declarations
* @author Oded Shimon ( ods15 ods15 dyndns org )
* @author Maxim Gavrilov ( maxim.gavrilov gmail com )
*/
#ifndef AVCODEC_AACTAB_H
#define AVCODEC_AACTAB_H
#include "libavutil/mem.h"
#include "aac.h"
#include <stdint.h>
/* NOTE:
* Tables in this file are shared by the AAC decoders and encoder
*/
extern float ff_aac_pow2sf_tab[428];
extern float ff_aac_pow34sf_tab[428];
static inline void ff_aac_tableinit(void)
{
int i;
/* 2^(i/16) for 0 <= i <= 15 */
static const float exp2_lut[] = {
1.00000000000000000000,
1.04427378242741384032,
1.09050773266525765921,
1.13878863475669165370,
1.18920711500272106672,
1.24185781207348404859,
1.29683955465100966593,
1.35425554693689272830,
1.41421356237309504880,
1.47682614593949931139,
1.54221082540794082361,
1.61049033194925430818,
1.68179283050742908606,
1.75625216037329948311,
1.83400808640934246349,
1.91520656139714729387,
};
float t1 = 8.8817841970012523233890533447265625e-16; // 2^(-50)
float t2 = 3.63797880709171295166015625e-12; // 2^(-38)
int t1_inc_cur, t2_inc_cur;
int t1_inc_prev = 0;
int t2_inc_prev = 8;
for (i = 0; i < 428; i++) {
t1_inc_cur = 4 * (i % 4);
t2_inc_cur = (8 + 3*i) % 16;
if (t1_inc_cur < t1_inc_prev)
t1 *= 2;
if (t2_inc_cur < t2_inc_prev)
t2 *= 2;
// A much more efficient and accurate way of doing:
// ff_aac_pow2sf_tab[i] = pow(2, (i - POW_SF2_ZERO) / 4.0);
// ff_aac_pow34sf_tab[i] = pow(ff_aac_pow2sf_tab[i], 3.0/4.0);
ff_aac_pow2sf_tab[i] = t1 * exp2_lut[t1_inc_cur];
ff_aac_pow34sf_tab[i] = t2 * exp2_lut[t2_inc_cur];
t1_inc_prev = t1_inc_cur;
t2_inc_prev = t2_inc_cur;
}
}
/* @name ltp_coef
* Table of the LTP coefficients
*/
static const INTFLOAT ltp_coef[8] = {
Q30(0.570829), Q30(0.696616), Q30(0.813004), Q30(0.911304),
Q30(0.984900), Q30(1.067894), Q30(1.194601), Q30(1.369533),
};
/* @name tns_tmp2_map
* Tables of the tmp2[] arrays of LPC coefficients used for TNS.
* The suffix _M_N[] indicate the values of coef_compress and coef_res
* respectively.
* @{
*/
static const INTFLOAT tns_tmp2_map_1_3[4] = {
Q31(0.00000000), Q31(-0.43388373), Q31(0.64278758), Q31(0.34202015),
};
static const INTFLOAT tns_tmp2_map_0_3[8] = {
Q31(0.00000000), Q31(-0.43388373), Q31(-0.78183150), Q31(-0.97492790),
Q31(0.98480773), Q31( 0.86602539), Q31( 0.64278758), Q31( 0.34202015),
};
static const INTFLOAT tns_tmp2_map_1_4[8] = {
Q31(0.00000000), Q31(-0.20791170), Q31(-0.40673664), Q31(-0.58778524),
Q31(0.67369562), Q31( 0.52643216), Q31( 0.36124167), Q31( 0.18374951),
};
static const INTFLOAT tns_tmp2_map_0_4[16] = {
Q31( 0.00000000), Q31(-0.20791170), Q31(-0.40673664), Q31(-0.58778524),
Q31(-0.74314481), Q31(-0.86602539), Q31(-0.95105654), Q31(-0.99452192),
Q31( 0.99573416), Q31( 0.96182561), Q31( 0.89516330), Q31( 0.79801720),
Q31( 0.67369562), Q31( 0.52643216), Q31( 0.36124167), Q31( 0.18374951),
};
static const INTFLOAT * const tns_tmp2_map[4] = {
tns_tmp2_map_0_3,
tns_tmp2_map_0_4,
tns_tmp2_map_1_3,
tns_tmp2_map_1_4
};
// @}
/* @name window coefficients
* @{
*/
DECLARE_ALIGNED(32, extern float, ff_aac_kbd_long_1024)[1024];
DECLARE_ALIGNED(32, extern float, ff_aac_kbd_short_128)[128];
DECLARE_ALIGNED(32, extern float, ff_aac_kbd_long_960)[960];
DECLARE_ALIGNED(32, extern float, ff_aac_kbd_short_120)[120];
DECLARE_ALIGNED(32, extern int, ff_aac_kbd_long_1024_fixed)[1024];
DECLARE_ALIGNED(32, extern int, ff_aac_kbd_long_512_fixed)[512];
DECLARE_ALIGNED(32, extern int, ff_aac_kbd_short_128_fixed)[128];
DECLARE_ALIGNED(32, extern const float, ff_aac_eld_window_512)[1920];
DECLARE_ALIGNED(32, extern const int, ff_aac_eld_window_512_fixed)[1920];
DECLARE_ALIGNED(32, extern const float, ff_aac_eld_window_480)[1800];
DECLARE_ALIGNED(32, extern const int, ff_aac_eld_window_480_fixed)[1800];
// @}
/* @name number of scalefactor window bands for long and short transform windows respectively
* @{
*/
extern const uint8_t ff_aac_num_swb_1024[];
extern const uint8_t ff_aac_num_swb_960 [];
extern const uint8_t ff_aac_num_swb_512 [];
extern const uint8_t ff_aac_num_swb_480 [];
extern const uint8_t ff_aac_num_swb_128 [];
extern const uint8_t ff_aac_num_swb_120 [];
// @}
extern const uint8_t ff_aac_pred_sfb_max [];
extern const uint32_t ff_aac_scalefactor_code[121];
extern const uint8_t ff_aac_scalefactor_bits[121];
extern const uint16_t * const ff_aac_spectral_codes[11];
extern const uint8_t * const ff_aac_spectral_bits [11];
extern const uint16_t ff_aac_spectral_sizes[11];
extern const float *ff_aac_codebook_vectors[];
extern const float *ff_aac_codebook_vector_vals[];
extern const uint16_t *ff_aac_codebook_vector_idx[];
extern const uint16_t * const ff_swb_offset_1024[13];
extern const uint16_t * const ff_swb_offset_960 [13];
extern const uint16_t * const ff_swb_offset_512 [13];
extern const uint16_t * const ff_swb_offset_480 [13];
extern const uint16_t * const ff_swb_offset_128 [13];
extern const uint16_t * const ff_swb_offset_120 [13];
extern const uint8_t ff_tns_max_bands_1024[13];
extern const uint8_t ff_tns_max_bands_512 [13];
extern const uint8_t ff_tns_max_bands_480 [13];
extern const uint8_t ff_tns_max_bands_128 [13];
#endif /* AVCODEC_AACTAB_H */

View File

@ -0,0 +1,32 @@
/*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AAN (Arai, Agui and Nakajima) (I)DCT tables
*/
#ifndef AVCODEC_AANDCTTAB_H
#define AVCODEC_AANDCTTAB_H
#include <stdint.h>
extern const uint16_t ff_aanscales[64];
extern const uint16_t ff_inv_aanscales[64];
#endif /* AVCODEC_AANDCTTAB_H */

View File

@ -0,0 +1,33 @@
/*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AARCH64_ASM_OFFSETS_H
#define AVCODEC_AARCH64_ASM_OFFSETS_H
/* CeltIMDCTContext */
#define CELT_EXPTAB 0x20
#define CELT_FFT_N 0x00
#define CELT_LEN2 0x04
#define CELT_LEN4 (CELT_LEN2 + 0x4) // loaded as pair
#define CELT_TMP 0x10
#define CELT_TWIDDLE (CELT_TMP + 0x8) // loaded as pair
/* FFTContext */
#define IMDCT_HALF 0x48
#endif /* AVCODEC_AARCH64_ASM_OFFSETS_H */

View File

@ -0,0 +1,104 @@
/*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AARCH64_CABAC_H
#define AVCODEC_AARCH64_CABAC_H
#include "config.h"
#if HAVE_INLINE_ASM
#include "libavutil/attributes.h"
#include "libavutil/internal.h"
#include "libavcodec/cabac.h"
#define get_cabac_inline get_cabac_inline_aarch64
static av_always_inline int get_cabac_inline_aarch64(CABACContext *c,
uint8_t *const state)
{
int bit;
void *reg_a, *reg_b, *reg_c, *tmp;
__asm__ volatile(
"ldrb %w[bit] , [%[state]] \n\t"
"add %[r_b] , %[tables] , %[lps_off] \n\t"
"mov %w[tmp] , %w[range] \n\t"
"and %w[range] , %w[range] , #0xC0 \n\t"
"lsl %w[r_c] , %w[range] , #1 \n\t"
"add %[r_b] , %[r_b] , %w[bit], UXTW \n\t"
"ldrb %w[range] , [%[r_b], %w[r_c], SXTW] \n\t"
"sub %w[r_c] , %w[tmp] , %w[range] \n\t"
"lsl %w[tmp] , %w[r_c] , #17 \n\t"
"cmp %w[tmp] , %w[low] \n\t"
"csel %w[tmp] , %w[tmp] , wzr , cc \n\t"
"csel %w[range] , %w[r_c] , %w[range], gt \n\t"
"cinv %w[bit] , %w[bit] , cc \n\t"
"sub %w[low] , %w[low] , %w[tmp] \n\t"
"add %[r_b] , %[tables] , %[norm_off] \n\t"
"add %[r_a] , %[tables] , %[mlps_off] \n\t"
"ldrb %w[tmp] , [%[r_b], %w[range], SXTW] \n\t"
"ldrb %w[r_a] , [%[r_a], %w[bit], SXTW] \n\t"
"lsl %w[low] , %w[low] , %w[tmp] \n\t"
"lsl %w[range] , %w[range] , %w[tmp] \n\t"
"uxth %w[r_c] , %w[low] \n\t"
"strb %w[r_a] , [%[state]] \n\t"
"cbnz %w[r_c] , 2f \n\t"
"ldr %[r_c] , [%[c], %[byte]] \n\t"
"ldr %[r_a] , [%[c], %[end]] \n\t"
"ldrh %w[tmp] , [%[r_c]] \n\t"
"cmp %[r_c] , %[r_a] \n\t"
"b.ge 1f \n\t"
"add %[r_a] , %[r_c] , #2 \n\t"
"str %[r_a] , [%[c], %[byte]] \n\t"
"1: \n\t"
"sub %w[r_c] , %w[low] , #1 \n\t"
"eor %w[r_c] , %w[r_c] , %w[low] \n\t"
"rev %w[tmp] , %w[tmp] \n\t"
"lsr %w[r_c] , %w[r_c] , #15 \n\t"
"lsr %w[tmp] , %w[tmp] , #15 \n\t"
"ldrb %w[r_c] , [%[r_b], %w[r_c], SXTW] \n\t"
"mov %w[r_b] , #0xFFFF \n\t"
"mov %w[r_a] , #7 \n\t"
"sub %w[tmp] , %w[tmp] , %w[r_b] \n\t"
"sub %w[r_c] , %w[r_a] , %w[r_c] \n\t"
"lsl %w[tmp] , %w[tmp] , %w[r_c] \n\t"
"add %w[low] , %w[low] , %w[tmp] \n\t"
"2: \n\t"
: [bit]"=&r"(bit),
[low]"+&r"(c->low),
[range]"+&r"(c->range),
[r_a]"=&r"(reg_a),
[r_b]"=&r"(reg_b),
[r_c]"=&r"(reg_c),
[tmp]"=&r"(tmp)
: [c]"r"(c),
[state]"r"(state),
[tables]"r"(ff_h264_cabac_tables),
[byte]"i"(offsetof(CABACContext, bytestream)),
[end]"i"(offsetof(CABACContext, bytestream_end)),
[norm_off]"I"(H264_NORM_SHIFT_OFFSET),
[lps_off]"I"(H264_LPS_RANGE_OFFSET),
[mlps_off]"I"(H264_MLPS_STATE_OFFSET + 128)
: "memory", "cc"
);
return bit & 1;
}
#endif /* HAVE_INLINE_ASM */
#endif /* AVCODEC_AARCH64_CABAC_H */

View File

@ -0,0 +1,28 @@
/*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AARCH64_IDCT_H
#define AVCODEC_AARCH64_IDCT_H
#include <stdint.h>
void ff_simple_idct_neon(int16_t *data);
void ff_simple_idct_put_neon(uint8_t *dest, ptrdiff_t line_size, int16_t *data);
void ff_simple_idct_add_neon(uint8_t *dest, ptrdiff_t line_size, int16_t *data);
#endif /* AVCODEC_AARCH64_IDCT_H */

View File

@ -0,0 +1,29 @@
/*
* Copyright (c) 2017 Google Inc.
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AARCH64_VP9DSP_INIT_H
#define AVCODEC_AARCH64_VP9DSP_INIT_H
#include "libavcodec/vp9dsp.h"
void ff_vp9dsp_init_10bpp_aarch64(VP9DSPContext *dsp);
void ff_vp9dsp_init_12bpp_aarch64(VP9DSPContext *dsp);
#endif /* AVCODEC_AARCH64_VP9DSP_INIT_H */

View File

@ -0,0 +1,263 @@
/*
* Common code between the AC-3 encoder and decoder
* Copyright (c) 2000, 2001, 2002 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Common code between the AC-3 encoder and decoder.
*/
#ifndef AVCODEC_AC3_H
#define AVCODEC_AC3_H
#define AC3_MAX_CODED_FRAME_SIZE 3840 /* in bytes */
#define EAC3_MAX_CHANNELS 16 /**< maximum number of channels in EAC3 */
#define AC3_MAX_CHANNELS 7 /**< maximum number of channels, including coupling channel */
#define CPL_CH 0 /**< coupling channel index */
#define AC3_MAX_COEFS 256
#define AC3_BLOCK_SIZE 256
#define AC3_MAX_BLOCKS 6
#define AC3_FRAME_SIZE (AC3_MAX_BLOCKS * 256)
#define AC3_WINDOW_SIZE (AC3_BLOCK_SIZE * 2)
#define AC3_CRITICAL_BANDS 50
#define AC3_MAX_CPL_BANDS 18
#include "libavutil/opt.h"
#include "avcodec.h"
#include "ac3tab.h"
/* exponent encoding strategy */
#define EXP_REUSE 0
#define EXP_NEW 1
#define EXP_D15 1
#define EXP_D25 2
#define EXP_D45 3
#ifndef USE_FIXED
#define USE_FIXED 0
#endif
#if USE_FIXED
#define FFT_FLOAT 0
#define FIXR(a) ((int)((a) * 0 + 0.5))
#define FIXR12(a) ((int)((a) * 4096 + 0.5))
#define FIXR15(a) ((int)((a) * 32768 + 0.5))
#define ROUND15(x) ((x) + 16384) >> 15
#define AC3_RENAME(x) x ## _fixed
#define AC3_NORM(norm) (1<<24)/(norm)
#define AC3_MUL(a,b) ((((int64_t) (a)) * (b))>>12)
#define AC3_RANGE(x) ((x)|(((x)&128)<<1))
#define AC3_HEAVY_RANGE(x) ((x)<<1)
#define AC3_DYNAMIC_RANGE(x) (x)
#define AC3_SPX_BLEND(x) (x)
#define AC3_DYNAMIC_RANGE1 0
typedef int INTFLOAT;
typedef int16_t SHORTFLOAT;
#else /* USE_FIXED */
#define FIXR(x) ((float)(x))
#define FIXR12(x) ((float)(x))
#define FIXR15(x) ((float)(x))
#define ROUND15(x) (x)
#define AC3_RENAME(x) x
#define AC3_NORM(norm) (1.0f/(norm))
#define AC3_MUL(a,b) ((a) * (b))
#define AC3_RANGE(x) (dynamic_range_tab[(x)])
#define AC3_HEAVY_RANGE(x) (ff_ac3_heavy_dynamic_range_tab[(x)])
#define AC3_DYNAMIC_RANGE(x) (powf(x, s->drc_scale))
#define AC3_SPX_BLEND(x) (x)* (1.0f/32)
#define AC3_DYNAMIC_RANGE1 1.0f
typedef float INTFLOAT;
typedef float SHORTFLOAT;
#endif /* USE_FIXED */
#define AC3_LEVEL(x) ROUND15((x) * FIXR15(M_SQRT1_2))
/* pre-defined gain values */
#define LEVEL_PLUS_3DB M_SQRT2
#define LEVEL_PLUS_1POINT5DB 1.1892071150027209
#define LEVEL_MINUS_1POINT5DB 0.8408964152537145
#define LEVEL_MINUS_3DB M_SQRT1_2
#define LEVEL_MINUS_4POINT5DB 0.5946035575013605
#define LEVEL_MINUS_6DB 0.5000000000000000
#define LEVEL_MINUS_9DB 0.3535533905932738
#define LEVEL_ZERO 0.0000000000000000
#define LEVEL_ONE 1.0000000000000000
/** Delta bit allocation strategy */
typedef enum {
DBA_REUSE = 0,
DBA_NEW,
DBA_NONE,
DBA_RESERVED
} AC3DeltaStrategy;
/** Channel mode (audio coding mode) */
typedef enum {
AC3_CHMODE_DUALMONO = 0,
AC3_CHMODE_MONO,
AC3_CHMODE_STEREO,
AC3_CHMODE_3F,
AC3_CHMODE_2F1R,
AC3_CHMODE_3F1R,
AC3_CHMODE_2F2R,
AC3_CHMODE_3F2R
} AC3ChannelMode;
/** Dolby Surround mode */
typedef enum AC3DolbySurroundMode {
AC3_DSURMOD_NOTINDICATED = 0,
AC3_DSURMOD_OFF,
AC3_DSURMOD_ON,
AC3_DSURMOD_RESERVED
} AC3DolbySurroundMode;
/** Dolby Surround EX mode */
typedef enum AC3DolbySurroundEXMode {
AC3_DSUREXMOD_NOTINDICATED = 0,
AC3_DSUREXMOD_OFF,
AC3_DSUREXMOD_ON,
AC3_DSUREXMOD_PLIIZ
} AC3DolbySurroundEXMode;
/** Dolby Headphone mode */
typedef enum AC3DolbyHeadphoneMode {
AC3_DHEADPHONMOD_NOTINDICATED = 0,
AC3_DHEADPHONMOD_OFF,
AC3_DHEADPHONMOD_ON,
AC3_DHEADPHONMOD_RESERVED
} AC3DolbyHeadphoneMode;
/** Preferred Stereo Downmix mode */
typedef enum AC3PreferredStereoDownmixMode {
AC3_DMIXMOD_NOTINDICATED = 0,
AC3_DMIXMOD_LTRT,
AC3_DMIXMOD_LORO,
AC3_DMIXMOD_DPLII // reserved value in A/52, but used by encoders to indicate DPL2
} AC3PreferredStereoDownmixMode;
typedef struct AC3BitAllocParameters {
int sr_code;
int sr_shift;
int slow_gain, slow_decay, fast_decay, db_per_bit, floor;
int cpl_fast_leak, cpl_slow_leak;
} AC3BitAllocParameters;
/**
* @struct AC3HeaderInfo
* Coded AC-3 header values up to the lfeon element, plus derived values.
*/
typedef struct AC3HeaderInfo {
/** @name Coded elements
* @{
*/
uint16_t sync_word;
uint16_t crc1;
uint8_t sr_code;
uint8_t bitstream_id;
uint8_t bitstream_mode;
uint8_t channel_mode;
uint8_t lfe_on;
uint8_t frame_type;
int substreamid; ///< substream identification
int center_mix_level; ///< Center mix level index
int surround_mix_level; ///< Surround mix level index
uint16_t channel_map;
int num_blocks; ///< number of audio blocks
int dolby_surround_mode;
/** @} */
/** @name Derived values
* @{
*/
uint8_t sr_shift;
uint16_t sample_rate;
uint32_t bit_rate;
uint8_t channels;
uint16_t frame_size;
uint64_t channel_layout;
/** @} */
} AC3HeaderInfo;
typedef enum {
EAC3_FRAME_TYPE_INDEPENDENT = 0,
EAC3_FRAME_TYPE_DEPENDENT,
EAC3_FRAME_TYPE_AC3_CONVERT,
EAC3_FRAME_TYPE_RESERVED
} EAC3FrameType;
void ff_ac3_common_init(void);
/**
* Calculate the log power-spectral density of the input signal.
* This gives a rough estimate of signal power in the frequency domain by using
* the spectral envelope (exponents). The psd is also separately grouped
* into critical bands for use in the calculating the masking curve.
* 128 units in psd = -6 dB. The dbknee parameter in AC3BitAllocParameters
* determines the reference level.
*
* @param[in] exp frequency coefficient exponents
* @param[in] start starting bin location
* @param[in] end ending bin location
* @param[out] psd signal power for each frequency bin
* @param[out] band_psd signal power for each critical band
*/
void ff_ac3_bit_alloc_calc_psd(int8_t *exp, int start, int end, int16_t *psd,
int16_t *band_psd);
/**
* Calculate the masking curve.
* First, the excitation is calculated using parameters in s and the signal
* power in each critical band. The excitation is compared with a predefined
* hearing threshold table to produce the masking curve. If delta bit
* allocation information is provided, it is used for adjusting the masking
* curve, usually to give a closer match to a better psychoacoustic model.
*
* @param[in] s adjustable bit allocation parameters
* @param[in] band_psd signal power for each critical band
* @param[in] start starting bin location
* @param[in] end ending bin location
* @param[in] fast_gain fast gain (estimated signal-to-mask ratio)
* @param[in] is_lfe whether or not the channel being processed is the LFE
* @param[in] dba_mode delta bit allocation mode (none, reuse, or new)
* @param[in] dba_nsegs number of delta segments
* @param[in] dba_offsets location offsets for each segment
* @param[in] dba_lengths length of each segment
* @param[in] dba_values delta bit allocation for each segment
* @param[out] mask calculated masking curve
* @return returns 0 for success, non-zero for error
*/
int ff_ac3_bit_alloc_calc_mask(AC3BitAllocParameters *s, int16_t *band_psd,
int start, int end, int fast_gain, int is_lfe,
int dba_mode, int dba_nsegs, uint8_t *dba_offsets,
uint8_t *dba_lengths, uint8_t *dba_values,
int16_t *mask);
#endif /* AVCODEC_AC3_H */

View File

@ -0,0 +1,36 @@
/*
* AC-3 parser prototypes
* Copyright (c) 2003 Fabrice Bellard
* Copyright (c) 2003 Michael Niedermayer
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AC3_PARSER_H
#define AVCODEC_AC3_PARSER_H
#include <stddef.h>
#include <stdint.h>
/**
* Extract the bitstream ID and the frame size from AC-3 data.
*/
int av_ac3_parse_header(const uint8_t *buf, size_t size,
uint8_t *bitstream_id, uint16_t *frame_size);
#endif /* AVCODEC_AC3_PARSER_H */

View File

@ -0,0 +1,42 @@
/*
* AC-3 parser internal code
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AC3_PARSER_INTERNAL_H
#define AVCODEC_AC3_PARSER_INTERNAL_H
#include "ac3.h"
#include "get_bits.h"
/**
* Parse AC-3 frame header.
* Parse the header up to the lfeon element, which is the first 52 or 54 bits
* depending on the audio coding mode.
* @param[in] gbc BitContext containing the first 54 bits of the frame.
* @param[out] hdr Pointer to struct where header info is written.
* @return Returns 0 on success, -1 if there is a sync word mismatch,
* -2 if the bsid (version) element is invalid, -3 if the fscod (sample rate)
* element is invalid, or -4 if the frmsizecod (bit rate) element is invalid.
*/
int ff_ac3_parse_header(GetBitContext *gbc, AC3HeaderInfo *hdr);
int avpriv_ac3_parse_header(AC3HeaderInfo **hdr, const uint8_t *buf,
size_t size);
#endif /* AVCODEC_AC3_PARSER_INTERNAL_H */

View File

@ -0,0 +1,277 @@
/*
* Common code between the AC-3 and E-AC-3 decoders
* Copyright (c) 2007 Bartlomiej Wolowiec <bartek.wolowiec@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Common code between the AC-3 and E-AC-3 decoders.
*
* Summary of MDCT Coefficient Grouping:
* The individual MDCT coefficient indices are often referred to in the
* (E-)AC-3 specification as frequency bins. These bins are grouped together
* into subbands of 12 coefficients each. The subbands are grouped together
* into bands as defined in the bitstream by the band structures, which
* determine the number of bands and the size of each band. The full spectrum
* of 256 frequency bins is divided into 1 DC bin + 21 subbands = 253 bins.
* This system of grouping coefficients is used for channel bandwidth, stereo
* rematrixing, channel coupling, enhanced coupling, and spectral extension.
*
* +-+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-+
* |1| |12| | [12|12|12|12] | | | | | | | | | | | | |3|
* +-+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-+
* ~~~ ~~~~ ~~~~~~~~~~~~~ ~~~
* | | | |
* | | | 3 unused frequency bins--+
* | | |
* | | +--1 band containing 4 subbands
* | |
* | +--1 subband of 12 frequency bins
* |
* +--DC frequency bin
*/
#ifndef AVCODEC_AC3DEC_H
#define AVCODEC_AC3DEC_H
#include "libavutil/float_dsp.h"
#include "libavutil/fixed_dsp.h"
#include "libavutil/lfg.h"
#include "ac3.h"
#include "ac3dsp.h"
#include "bswapdsp.h"
#include "get_bits.h"
#include "fft.h"
#include "fmtconvert.h"
#define AC3_OUTPUT_LFEON 8
#define SPX_MAX_BANDS 17
/** Large enough for maximum possible frame size when the specification limit is ignored */
#define AC3_FRAME_BUFFER_SIZE 32768
typedef struct AC3DecodeContext {
AVClass *class; ///< class for AVOptions
AVCodecContext *avctx; ///< parent context
GetBitContext gbc; ///< bitstream reader
///@name Bit stream information
///@{
int frame_type; ///< frame type (strmtyp)
int substreamid; ///< substream identification
int superframe_size; ///< current superframe size, in bytes
int frame_size; ///< current frame size, in bytes
int bit_rate; ///< stream bit rate, in bits-per-second
int sample_rate; ///< sample frequency, in Hz
int num_blocks; ///< number of audio blocks
int bitstream_id; ///< bitstream id (bsid)
int bitstream_mode; ///< bitstream mode (bsmod)
int channel_mode; ///< channel mode (acmod)
int lfe_on; ///< lfe channel in use
int dialog_normalization[2]; ///< dialog level in dBFS (dialnorm)
int compression_exists[2]; ///< compression field is valid for frame (compre)
int compression_gain[2]; ///< gain to apply for heavy compression (compr)
int channel_map; ///< custom channel map (chanmap)
int preferred_downmix; ///< Preferred 2-channel downmix mode (dmixmod)
int center_mix_level; ///< Center mix level index
int center_mix_level_ltrt; ///< Center mix level index for Lt/Rt (ltrtcmixlev)
int surround_mix_level; ///< Surround mix level index
int surround_mix_level_ltrt; ///< Surround mix level index for Lt/Rt (ltrtsurmixlev)
int lfe_mix_level_exists; ///< indicates if lfemixlevcod is specified (lfemixlevcode)
int lfe_mix_level; ///< LFE mix level index (lfemixlevcod)
int eac3; ///< indicates if current frame is E-AC-3
int eac3_frame_dependent_found; ///< bitstream has E-AC-3 dependent frame(s)
int eac3_subsbtreamid_found; ///< bitstream has E-AC-3 additional substream(s)
int dolby_surround_mode; ///< dolby surround mode (dsurmod)
int dolby_surround_ex_mode; ///< dolby surround ex mode (dsurexmod)
int dolby_headphone_mode; ///< dolby headphone mode (dheadphonmod)
///@}
int preferred_stereo_downmix;
float ltrt_center_mix_level;
float ltrt_surround_mix_level;
float loro_center_mix_level;
float loro_surround_mix_level;
int target_level; ///< target level in dBFS
float level_gain[2];
///@name Frame syntax parameters
int snr_offset_strategy; ///< SNR offset strategy (snroffststr)
int block_switch_syntax; ///< block switch syntax enabled (blkswe)
int dither_flag_syntax; ///< dither flag syntax enabled (dithflage)
int bit_allocation_syntax; ///< bit allocation model syntax enabled (bamode)
int fast_gain_syntax; ///< fast gain codes enabled (frmfgaincode)
int dba_syntax; ///< delta bit allocation syntax enabled (dbaflde)
int skip_syntax; ///< skip field syntax enabled (skipflde)
///@}
///@name Standard coupling
int cpl_in_use[AC3_MAX_BLOCKS]; ///< coupling in use (cplinu)
int cpl_strategy_exists[AC3_MAX_BLOCKS];///< coupling strategy exists (cplstre)
int channel_in_cpl[AC3_MAX_CHANNELS]; ///< channel in coupling (chincpl)
int phase_flags_in_use; ///< phase flags in use (phsflginu)
int phase_flags[AC3_MAX_CPL_BANDS]; ///< phase flags (phsflg)
int num_cpl_bands; ///< number of coupling bands (ncplbnd)
uint8_t cpl_band_struct[AC3_MAX_CPL_BANDS];
uint8_t cpl_band_sizes[AC3_MAX_CPL_BANDS]; ///< number of coeffs in each coupling band
int firstchincpl; ///< first channel in coupling
int first_cpl_coords[AC3_MAX_CHANNELS]; ///< first coupling coordinates states (firstcplcos)
int cpl_coords[AC3_MAX_CHANNELS][AC3_MAX_CPL_BANDS]; ///< coupling coordinates (cplco)
///@}
///@name Spectral extension
///@{
int spx_in_use; ///< spectral extension in use (spxinu)
uint8_t channel_uses_spx[AC3_MAX_CHANNELS]; ///< channel uses spectral extension (chinspx)
int8_t spx_atten_code[AC3_MAX_CHANNELS]; ///< spx attenuation code (spxattencod)
int spx_src_start_freq; ///< spx start frequency bin
int spx_dst_end_freq; ///< spx end frequency bin
int spx_dst_start_freq; ///< spx starting frequency bin for copying (copystartmant)
///< the copy region ends at the start of the spx region.
int num_spx_bands; ///< number of spx bands (nspxbnds)
uint8_t spx_band_struct[SPX_MAX_BANDS];
uint8_t spx_band_sizes[SPX_MAX_BANDS]; ///< number of bins in each spx band
uint8_t first_spx_coords[AC3_MAX_CHANNELS]; ///< first spx coordinates states (firstspxcos)
INTFLOAT spx_noise_blend[AC3_MAX_CHANNELS][SPX_MAX_BANDS]; ///< spx noise blending factor (nblendfact)
INTFLOAT spx_signal_blend[AC3_MAX_CHANNELS][SPX_MAX_BANDS];///< spx signal blending factor (sblendfact)
///@}
///@name Adaptive hybrid transform
int channel_uses_aht[AC3_MAX_CHANNELS]; ///< channel AHT in use (chahtinu)
int pre_mantissa[AC3_MAX_CHANNELS][AC3_MAX_COEFS][AC3_MAX_BLOCKS]; ///< pre-IDCT mantissas
///@}
///@name Channel
int fbw_channels; ///< number of full-bandwidth channels
int channels; ///< number of total channels
int lfe_ch; ///< index of LFE channel
SHORTFLOAT *downmix_coeffs[2]; ///< stereo downmix coefficients
int downmixed; ///< indicates if coeffs are currently downmixed
int output_mode; ///< output channel configuration
int prev_output_mode; ///< output channel configuration for previous frame
int out_channels; ///< number of output channels
int prev_bit_rate; ///< stream bit rate, in bits-per-second for previous frame
///@}
///@name Dynamic range
INTFLOAT dynamic_range[2]; ///< dynamic range
INTFLOAT drc_scale; ///< percentage of dynamic range compression to be applied
int heavy_compression; ///< apply heavy compression
INTFLOAT heavy_dynamic_range[2]; ///< heavy dynamic range compression
///@}
///@name Bandwidth
int start_freq[AC3_MAX_CHANNELS]; ///< start frequency bin (strtmant)
int end_freq[AC3_MAX_CHANNELS]; ///< end frequency bin (endmant)
///@}
///@name Consistent noise generation
int consistent_noise_generation; ///< seed noise generation with AC-3 frame on decode
///@}
///@name Rematrixing
int num_rematrixing_bands; ///< number of rematrixing bands (nrematbnd)
int rematrixing_flags[4]; ///< rematrixing flags (rematflg)
///@}
///@name Exponents
int num_exp_groups[AC3_MAX_CHANNELS]; ///< Number of exponent groups (nexpgrp)
int8_t dexps[AC3_MAX_CHANNELS][AC3_MAX_COEFS]; ///< decoded exponents
int exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS]; ///< exponent strategies (expstr)
///@}
///@name Bit allocation
AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
int first_cpl_leak; ///< first coupling leak state (firstcplleak)
int snr_offset[AC3_MAX_CHANNELS]; ///< signal-to-noise ratio offsets (snroffst)
int fast_gain[AC3_MAX_CHANNELS]; ///< fast gain values/SMR's (fgain)
uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS]; ///< bit allocation pointers
int16_t psd[AC3_MAX_CHANNELS][AC3_MAX_COEFS]; ///< scaled exponents
int16_t band_psd[AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS]; ///< interpolated exponents
int16_t mask[AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS]; ///< masking curve values
int dba_mode[AC3_MAX_CHANNELS]; ///< delta bit allocation mode
int dba_nsegs[AC3_MAX_CHANNELS]; ///< number of delta segments
uint8_t dba_offsets[AC3_MAX_CHANNELS][8]; ///< delta segment offsets
uint8_t dba_lengths[AC3_MAX_CHANNELS][8]; ///< delta segment lengths
uint8_t dba_values[AC3_MAX_CHANNELS][8]; ///< delta values for each segment
///@}
///@name Zero-mantissa dithering
int dither_flag[AC3_MAX_CHANNELS]; ///< dither flags (dithflg)
AVLFG dith_state; ///< for dither generation
///@}
///@name IMDCT
int block_switch[AC3_MAX_CHANNELS]; ///< block switch flags (blksw)
FFTContext imdct_512; ///< for 512 sample IMDCT
FFTContext imdct_256; ///< for 256 sample IMDCT
///@}
///@name Optimization
BswapDSPContext bdsp;
#if USE_FIXED
AVFixedDSPContext *fdsp;
#else
AVFloatDSPContext *fdsp;
#endif
AC3DSPContext ac3dsp;
FmtConvertContext fmt_conv; ///< optimized conversion functions
///@}
SHORTFLOAT *outptr[AC3_MAX_CHANNELS];
INTFLOAT *xcfptr[AC3_MAX_CHANNELS];
INTFLOAT *dlyptr[AC3_MAX_CHANNELS];
///@name Aligned arrays
DECLARE_ALIGNED(16, int, fixed_coeffs)[AC3_MAX_CHANNELS][AC3_MAX_COEFS]; ///< fixed-point transform coefficients
DECLARE_ALIGNED(32, INTFLOAT, transform_coeffs)[AC3_MAX_CHANNELS][AC3_MAX_COEFS]; ///< transform coefficients
DECLARE_ALIGNED(32, INTFLOAT, delay)[EAC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< delay - added to the next block
DECLARE_ALIGNED(32, INTFLOAT, window)[AC3_BLOCK_SIZE]; ///< window coefficients
DECLARE_ALIGNED(32, INTFLOAT, tmp_output)[AC3_BLOCK_SIZE]; ///< temporary storage for output before windowing
DECLARE_ALIGNED(32, SHORTFLOAT, output)[EAC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< output after imdct transform and windowing
DECLARE_ALIGNED(32, uint8_t, input_buffer)[AC3_FRAME_BUFFER_SIZE + AV_INPUT_BUFFER_PADDING_SIZE]; ///< temp buffer to prevent overread
DECLARE_ALIGNED(32, SHORTFLOAT, output_buffer)[EAC3_MAX_CHANNELS][AC3_BLOCK_SIZE * 6]; ///< final output buffer
///@}
} AC3DecodeContext;
/**
* Parse the E-AC-3 frame header.
* This parses both the bit stream info and audio frame header.
*/
static int ff_eac3_parse_header(AC3DecodeContext *s);
/**
* Decode mantissas in a single channel for the entire frame.
* This is used when AHT mode is enabled.
*/
static void ff_eac3_decode_transform_coeffs_aht_ch(AC3DecodeContext *s, int ch);
/**
* Apply spectral extension to each channel by copying lower frequency
* coefficients to higher frequency bins and applying side information to
* approximate the original high frequency signal.
*/
static void ff_eac3_apply_spectral_extension(AC3DecodeContext *s);
#if (!USE_FIXED)
extern float ff_ac3_heavy_dynamic_range_tab[256];
#endif
#endif /* AVCODEC_AC3DEC_H */

View File

@ -0,0 +1,32 @@
/*
* AC-3 and E-AC-3 decoder tables
* Copyright (c) 2007 Bartlomiej Wolowiec <bartek.wolowiec@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AC3DEC_DATA_H
#define AVCODEC_AC3DEC_DATA_H
#include <stdint.h>
extern const uint8_t ff_ac3_ungroup_3_in_5_bits_tab[32][3];
extern const uint8_t ff_eac3_hebap_tab[64];
extern const uint8_t ff_eac3_default_spx_band_struct[17];
#endif /* AVCODEC_AC3DEC_DATA_H */

View File

@ -0,0 +1,167 @@
/*
* AC-3 DSP functions
* Copyright (c) 2011 Justin Ruggles
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AC3DSP_H
#define AVCODEC_AC3DSP_H
#include <stdint.h>
/**
* Number of mantissa bits written for each bap value.
* bap values with fractional bits are set to 0 and are calculated separately.
*/
extern const uint16_t ff_ac3_bap_bits[16];
typedef struct AC3DSPContext {
/**
* Set each encoded exponent in a block to the minimum of itself and the
* exponents in the same frequency bin of up to 5 following blocks.
* @param exp pointer to the start of the current block of exponents.
* constraints: align 16
* @param num_reuse_blocks number of blocks that will reuse exponents from the current block.
* constraints: range 0 to 5
* @param nb_coefs number of frequency coefficients.
*/
void (*ac3_exponent_min)(uint8_t *exp, int num_reuse_blocks, int nb_coefs);
/**
* Calculate the maximum MSB of the absolute value of each element in an
* array of int16_t.
* @param src input array
* constraints: align 16. values must be in range [-32767,32767]
* @param len number of values in the array
* constraints: multiple of 16 greater than 0
* @return a value with the same MSB as max(abs(src[]))
*/
int (*ac3_max_msb_abs_int16)(const int16_t *src, int len);
/**
* Left-shift each value in an array of int16_t by a specified amount.
* @param src input array
* constraints: align 16
* @param len number of values in the array
* constraints: multiple of 32 greater than 0
* @param shift left shift amount
* constraints: range [0,15]
*/
void (*ac3_lshift_int16)(int16_t *src, unsigned int len, unsigned int shift);
/**
* Right-shift each value in an array of int32_t by a specified amount.
* @param src input array
* constraints: align 16
* @param len number of values in the array
* constraints: multiple of 16 greater than 0
* @param shift right shift amount
* constraints: range [0,31]
*/
void (*ac3_rshift_int32)(int32_t *src, unsigned int len, unsigned int shift);
/**
* Convert an array of float in range [-1.0,1.0] to int32_t with range
* [-(1<<24),(1<<24)]
*
* @param dst destination array of int32_t.
* constraints: 16-byte aligned
* @param src source array of float.
* constraints: 16-byte aligned
* @param len number of elements to convert.
* constraints: multiple of 32 greater than zero
*/
void (*float_to_fixed24)(int32_t *dst, const float *src, unsigned int len);
/**
* Calculate bit allocation pointers.
* The SNR is the difference between the masking curve and the signal. AC-3
* uses this value for each frequency bin to allocate bits. The snroffset
* parameter is a global adjustment to the SNR for all bins.
*
* @param[in] mask masking curve
* @param[in] psd signal power for each frequency bin
* @param[in] start starting bin location
* @param[in] end ending bin location
* @param[in] snr_offset SNR adjustment
* @param[in] floor noise floor
* @param[in] bap_tab look-up table for bit allocation pointers
* @param[out] bap bit allocation pointers
*/
void (*bit_alloc_calc_bap)(int16_t *mask, int16_t *psd, int start, int end,
int snr_offset, int floor,
const uint8_t *bap_tab, uint8_t *bap);
/**
* Update bap counts using the supplied array of bap.
*
* @param[out] mant_cnt bap counts for 1 block
* @param[in] bap array of bap, pointing to start coef bin
* @param[in] len number of elements to process
*/
void (*update_bap_counts)(uint16_t mant_cnt[16], uint8_t *bap, int len);
/**
* Calculate the number of bits needed to encode a set of mantissas.
*
* @param[in] mant_cnt bap counts for all blocks
* @return mantissa bit count
*/
int (*compute_mantissa_size)(uint16_t mant_cnt[6][16]);
void (*extract_exponents)(uint8_t *exp, int32_t *coef, int nb_coefs);
void (*sum_square_butterfly_int32)(int64_t sum[4], const int32_t *coef0,
const int32_t *coef1, int len);
void (*sum_square_butterfly_float)(float sum[4], const float *coef0,
const float *coef1, int len);
int out_channels;
int in_channels;
void (*downmix)(float **samples, float **matrix, int len);
void (*downmix_fixed)(int32_t **samples, int16_t **matrix, int len);
/**
* Apply symmetric window in 16-bit fixed-point.
* @param output destination array
* constraints: 16-byte aligned
* @param input source array
* constraints: 16-byte aligned
* @param window window array
* constraints: 16-byte aligned, at least len/2 elements
* @param len full window length
* constraints: multiple of ? greater than zero
*/
void (*apply_window_int16)(int16_t *output, const int16_t *input,
const int16_t *window, unsigned int len);
} AC3DSPContext;
void ff_ac3dsp_init (AC3DSPContext *c, int bit_exact);
void ff_ac3dsp_init_arm(AC3DSPContext *c, int bit_exact);
void ff_ac3dsp_init_x86(AC3DSPContext *c, int bit_exact);
void ff_ac3dsp_init_mips(AC3DSPContext *c, int bit_exact);
void ff_ac3dsp_downmix(AC3DSPContext *c, float **samples, float **matrix,
int out_ch, int in_ch, int len);
void ff_ac3dsp_downmix_fixed(AC3DSPContext *c, int32_t **samples, int16_t **matrix,
int out_ch, int in_ch, int len);
void ff_ac3dsp_set_downmix_x86(AC3DSPContext *c);
#endif /* AVCODEC_AC3DSP_H */

View File

@ -0,0 +1,315 @@
/*
* AC-3 encoder & E-AC-3 encoder common header
* Copyright (c) 2000 Fabrice Bellard
* Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* AC-3 encoder & E-AC-3 encoder common header
*/
#ifndef AVCODEC_AC3ENC_H
#define AVCODEC_AC3ENC_H
#include <stdint.h>
#include "libavutil/float_dsp.h"
#include "ac3.h"
#include "ac3dsp.h"
#include "avcodec.h"
#include "fft.h"
#include "mathops.h"
#include "me_cmp.h"
#include "put_bits.h"
#include "audiodsp.h"
#ifndef CONFIG_AC3ENC_FLOAT
#define CONFIG_AC3ENC_FLOAT 0
#endif
#define OFFSET(param) offsetof(AC3EncodeContext, options.param)
#define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
#define AC3ENC_TYPE_AC3_FIXED 0
#define AC3ENC_TYPE_AC3 1
#define AC3ENC_TYPE_EAC3 2
#if CONFIG_AC3ENC_FLOAT
#define AC3_NAME(x) ff_ac3_float_ ## x
#define MAC_COEF(d,a,b) ((d)+=(a)*(b))
#define COEF_MIN (-16777215.0/16777216.0)
#define COEF_MAX ( 16777215.0/16777216.0)
#define NEW_CPL_COORD_THRESHOLD 0.03
typedef float SampleType;
typedef float CoefType;
typedef float CoefSumType;
#else
#define AC3_NAME(x) ff_ac3_fixed_ ## x
#define MAC_COEF(d,a,b) MAC64(d,a,b)
#define COEF_MIN -16777215
#define COEF_MAX 16777215
#define NEW_CPL_COORD_THRESHOLD 503317
typedef int16_t SampleType;
typedef int32_t CoefType;
typedef int64_t CoefSumType;
#endif
/* common option values */
#define AC3ENC_OPT_NONE -1
#define AC3ENC_OPT_AUTO -1
#define AC3ENC_OPT_OFF 0
#define AC3ENC_OPT_ON 1
#define AC3ENC_OPT_NOT_INDICATED 0
#define AC3ENC_OPT_MODE_ON 2
#define AC3ENC_OPT_MODE_OFF 1
#define AC3ENC_OPT_DSUREX_DPLIIZ 3
/* specific option values */
#define AC3ENC_OPT_LARGE_ROOM 1
#define AC3ENC_OPT_SMALL_ROOM 2
#define AC3ENC_OPT_DOWNMIX_LTRT 1
#define AC3ENC_OPT_DOWNMIX_LORO 2
#define AC3ENC_OPT_DOWNMIX_DPLII 3 // reserved value in A/52, but used by encoders to indicate DPL2
#define AC3ENC_OPT_ADCONV_STANDARD 0
#define AC3ENC_OPT_ADCONV_HDCD 1
/**
* Encoding Options used by AVOption.
*/
typedef struct AC3EncOptions {
/* AC-3 metadata options*/
int dialogue_level;
int bitstream_mode;
float center_mix_level;
float surround_mix_level;
int dolby_surround_mode;
int audio_production_info;
int mixing_level;
int room_type;
int copyright;
int original;
int extended_bsi_1;
int preferred_stereo_downmix;
float ltrt_center_mix_level;
float ltrt_surround_mix_level;
float loro_center_mix_level;
float loro_surround_mix_level;
int extended_bsi_2;
int dolby_surround_ex_mode;
int dolby_headphone_mode;
int ad_converter_type;
int eac3_mixing_metadata;
int eac3_info_metadata;
/* other encoding options */
int allow_per_frame_metadata;
int stereo_rematrixing;
int channel_coupling;
int cpl_start;
} AC3EncOptions;
/**
* Data for a single audio block.
*/
typedef struct AC3Block {
CoefType **mdct_coef; ///< MDCT coefficients
int32_t **fixed_coef; ///< fixed-point MDCT coefficients
uint8_t **exp; ///< original exponents
uint8_t **grouped_exp; ///< grouped exponents
int16_t **psd; ///< psd per frequency bin
int16_t **band_psd; ///< psd per critical band
int16_t **mask; ///< masking curve
uint16_t **qmant; ///< quantized mantissas
uint8_t **cpl_coord_exp; ///< coupling coord exponents (cplcoexp)
uint8_t **cpl_coord_mant; ///< coupling coord mantissas (cplcomant)
uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
int num_rematrixing_bands; ///< number of rematrixing bands
uint8_t rematrixing_flags[4]; ///< rematrixing flags
int new_cpl_strategy; ///< send new coupling strategy
int cpl_in_use; ///< coupling in use for this block (cplinu)
uint8_t channel_in_cpl[AC3_MAX_CHANNELS]; ///< channel in coupling (chincpl)
int num_cpl_channels; ///< number of channels in coupling
uint8_t new_cpl_coords[AC3_MAX_CHANNELS]; ///< send new coupling coordinates (cplcoe)
uint8_t cpl_master_exp[AC3_MAX_CHANNELS]; ///< coupling coord master exponents (mstrcplco)
int new_snr_offsets; ///< send new SNR offsets
int new_cpl_leak; ///< send new coupling leak info
int end_freq[AC3_MAX_CHANNELS]; ///< end frequency bin (endmant)
} AC3Block;
/**
* AC-3 encoder private context.
*/
typedef struct AC3EncodeContext {
AVClass *av_class; ///< AVClass used for AVOption
AC3EncOptions options; ///< encoding options
AVCodecContext *avctx; ///< parent AVCodecContext
PutBitContext pb; ///< bitstream writer context
AudioDSPContext adsp;
AVFloatDSPContext *fdsp;
MECmpContext mecc;
AC3DSPContext ac3dsp; ///< AC-3 optimized functions
FFTContext mdct; ///< FFT context for MDCT calculation
const SampleType *mdct_window; ///< MDCT window function array
AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
int fixed_point; ///< indicates if fixed-point encoder is being used
int eac3; ///< indicates if this is E-AC-3 vs. AC-3
int bitstream_id; ///< bitstream id (bsid)
int bitstream_mode; ///< bitstream mode (bsmod)
int bit_rate; ///< target bit rate, in bits-per-second
int sample_rate; ///< sampling frequency, in Hz
int num_blks_code; ///< number of blocks code (numblkscod)
int num_blocks; ///< number of blocks per frame
int frame_size_min; ///< minimum frame size in case rounding is necessary
int frame_size; ///< current frame size in bytes
int frame_size_code; ///< frame size code (frmsizecod)
uint16_t crc_inv[2];
int64_t bits_written; ///< bit count (used to avg. bitrate)
int64_t samples_written; ///< sample count (used to avg. bitrate)
int fbw_channels; ///< number of full-bandwidth channels (nfchans)
int channels; ///< total number of channels (nchans)
int lfe_on; ///< indicates if there is an LFE channel (lfeon)
int lfe_channel; ///< channel index of the LFE channel
int has_center; ///< indicates if there is a center channel
int has_surround; ///< indicates if there are one or more surround channels
int channel_mode; ///< channel mode (acmod)
const uint8_t *channel_map; ///< channel map used to reorder channels
int center_mix_level; ///< center mix level code
int surround_mix_level; ///< surround mix level code
int ltrt_center_mix_level; ///< Lt/Rt center mix level code
int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
int loro_center_mix_level; ///< Lo/Ro center mix level code
int loro_surround_mix_level; ///< Lo/Ro surround mix level code
int cutoff; ///< user-specified cutoff frequency, in Hz
int bandwidth_code; ///< bandwidth code (0 to 60) (chbwcod)
int start_freq[AC3_MAX_CHANNELS]; ///< start frequency bin (strtmant)
int cpl_end_freq; ///< coupling channel end frequency bin
int cpl_on; ///< coupling turned on for this frame
int cpl_enabled; ///< coupling enabled for all frames
int num_cpl_subbands; ///< number of coupling subbands (ncplsubnd)
int num_cpl_bands; ///< number of coupling bands (ncplbnd)
uint8_t cpl_band_sizes[AC3_MAX_CPL_BANDS]; ///< number of coeffs in each coupling band
int rematrixing_enabled; ///< stereo rematrixing enabled
/* bitrate allocation control */
int slow_gain_code; ///< slow gain code (sgaincod)
int slow_decay_code; ///< slow decay code (sdcycod)
int fast_decay_code; ///< fast decay code (fdcycod)
int db_per_bit_code; ///< dB/bit code (dbpbcod)
int floor_code; ///< floor code (floorcod)
AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
int frame_bits; ///< all frame bits except exponents and mantissas
int exponent_bits; ///< number of bits used for exponents
SampleType *windowed_samples;
SampleType **planar_samples;
uint8_t *bap_buffer;
uint8_t *bap1_buffer;
CoefType *mdct_coef_buffer;
int32_t *fixed_coef_buffer;
uint8_t *exp_buffer;
uint8_t *grouped_exp_buffer;
int16_t *psd_buffer;
int16_t *band_psd_buffer;
int16_t *mask_buffer;
int16_t *qmant_buffer;
uint8_t *cpl_coord_exp_buffer;
uint8_t *cpl_coord_mant_buffer;
uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
uint8_t frame_exp_strategy[AC3_MAX_CHANNELS]; ///< frame exp strategy index
int use_frame_exp_strategy; ///< indicates use of frame exp strategy
uint8_t exp_ref_block[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< reference blocks for EXP_REUSE
uint8_t *ref_bap [AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< bit allocation pointers (bap)
int ref_bap_set; ///< indicates if ref_bap pointers have been set
/* fixed vs. float function pointers */
void (*mdct_end)(struct AC3EncodeContext *s);
int (*mdct_init)(struct AC3EncodeContext *s);
/* fixed vs. float templated function pointers */
int (*allocate_sample_buffers)(struct AC3EncodeContext *s);
/* AC-3 vs. E-AC-3 function pointers */
void (*output_frame_header)(struct AC3EncodeContext *s);
} AC3EncodeContext;
extern const uint64_t ff_ac3_channel_layouts[19];
int ff_ac3_encode_init(AVCodecContext *avctx);
int ff_ac3_float_encode_init(AVCodecContext *avctx);
int ff_ac3_encode_close(AVCodecContext *avctx);
int ff_ac3_validate_metadata(AC3EncodeContext *s);
void ff_ac3_adjust_frame_size(AC3EncodeContext *s);
void ff_ac3_compute_coupling_strategy(AC3EncodeContext *s);
void ff_ac3_apply_rematrixing(AC3EncodeContext *s);
void ff_ac3_process_exponents(AC3EncodeContext *s);
int ff_ac3_compute_bit_allocation(AC3EncodeContext *s);
void ff_ac3_group_exponents(AC3EncodeContext *s);
void ff_ac3_quantize_mantissas(AC3EncodeContext *s);
void ff_ac3_output_frame(AC3EncodeContext *s, unsigned char *frame);
/* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
void ff_ac3_fixed_mdct_end(AC3EncodeContext *s);
void ff_ac3_float_mdct_end(AC3EncodeContext *s);
int ff_ac3_fixed_mdct_init(AC3EncodeContext *s);
int ff_ac3_float_mdct_init(AC3EncodeContext *s);
/* prototypes for functions in ac3enc_template.c */
int ff_ac3_fixed_allocate_sample_buffers(AC3EncodeContext *s);
int ff_ac3_float_allocate_sample_buffers(AC3EncodeContext *s);
int ff_ac3_fixed_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
const AVFrame *frame, int *got_packet_ptr);
int ff_ac3_float_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
const AVFrame *frame, int *got_packet_ptr);
#endif /* AVCODEC_AC3ENC_H */

View File

@ -0,0 +1,69 @@
/*
* AC-3 tables
* Copyright (c) 2000, 2001, 2002 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_AC3TAB_H
#define AVCODEC_AC3TAB_H
#include <stdint.h>
#include "libavutil/internal.h"
#include "ac3.h"
#include "internal.h"
extern const uint16_t ff_ac3_frame_size_tab[38][3];
extern const uint8_t ff_ac3_channels_tab[8];
extern av_export_avcodec const uint16_t avpriv_ac3_channel_layout_tab[8];
extern const uint8_t ff_ac3_enc_channel_map[8][2][6];
extern const uint8_t ff_ac3_dec_channel_map[8][2][6];
extern const uint16_t ff_ac3_sample_rate_tab[3];
extern const uint16_t ff_ac3_bitrate_tab[19];
extern const uint8_t ff_ac3_rematrix_band_tab[5];
extern const uint8_t ff_eac3_default_cpl_band_struct[18];
extern const int16_t ff_ac3_window[AC3_WINDOW_SIZE/2];
extern const uint8_t ff_ac3_log_add_tab[260];
extern const uint16_t ff_ac3_hearing_threshold_tab[AC3_CRITICAL_BANDS][3];
extern const uint8_t ff_ac3_bap_tab[64];
extern const uint8_t ff_ac3_slow_decay_tab[4];
extern const uint8_t ff_ac3_fast_decay_tab[4];
extern const uint16_t ff_ac3_slow_gain_tab[4];
extern const uint16_t ff_ac3_db_per_bit_tab[4];
extern const int16_t ff_ac3_floor_tab[8];
extern const uint16_t ff_ac3_fast_gain_tab[8];
extern const uint16_t ff_eac3_default_chmap[8];
extern const uint8_t ff_ac3_band_start_tab[AC3_CRITICAL_BANDS+1];
extern const uint8_t ff_ac3_bin_to_band_tab[253];
/** Custom channel map locations bitmask
* Other channels described in documentation:
* Lc/Rc pair, Lrs/Rrs pair, Ts, Lsd/Rsd pair,
* Lw/Rw pair, Lvh/Rvh pair, Cvh, Reserved, LFE2
*/
enum CustomChannelMapLocation{
AC3_CHMAP_L= 1<<(15-0),
AC3_CHMAP_C= 1<<(15-1),
AC3_CHMAP_R= 1<<(15-2),
AC3_CHMAP_L_SUR= 1<<(15-3),
AC3_CHMAP_R_SUR = 1<<(15-4),
AC3_CHMAP_C_SUR= 1<<(15-7),
AC3_CHMAP_LFE = 1<<(15-15)
};
#endif /* AVCODEC_AC3TAB_H */

View File

@ -0,0 +1,152 @@
/*
* various filters for ACELP-based codecs
*
* Copyright (c) 2008 Vladimir Voroshilov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_ACELP_FILTERS_H
#define AVCODEC_ACELP_FILTERS_H
#include <stdint.h>
typedef struct ACELPFContext {
/**
* Floating point version of ff_acelp_interpolate()
*/
void (*acelp_interpolatef)(float *out, const float *in,
const float *filter_coeffs, int precision,
int frac_pos, int filter_length, int length);
/**
* Apply an order 2 rational transfer function in-place.
*
* @param out output buffer for filtered speech samples
* @param in input buffer containing speech data (may be the same as out)
* @param zero_coeffs z^-1 and z^-2 coefficients of the numerator
* @param pole_coeffs z^-1 and z^-2 coefficients of the denominator
* @param gain scale factor for final output
* @param mem intermediate values used by filter (should be 0 initially)
* @param n number of samples (should be a multiple of eight)
*/
void (*acelp_apply_order_2_transfer_function)(float *out, const float *in,
const float zero_coeffs[2],
const float pole_coeffs[2],
float gain,
float mem[2], int n);
}ACELPFContext;
/**
* Initialize ACELPFContext.
*/
void ff_acelp_filter_init(ACELPFContext *c);
void ff_acelp_filter_init_mips(ACELPFContext *c);
/**
* low-pass Finite Impulse Response filter coefficients.
*
* Hamming windowed sinc filter with cutoff freq 3/40 of the sampling freq,
* the coefficients are scaled by 2^15.
* This array only contains the right half of the filter.
* This filter is likely identical to the one used in G.729, though this
* could not be determined from the original comments with certainty.
*/
extern const int16_t ff_acelp_interp_filter[61];
/**
* Generic FIR interpolation routine.
* @param[out] out buffer for interpolated data
* @param in input data
* @param filter_coeffs interpolation filter coefficients (0.15)
* @param precision sub sample factor, that is the precision of the position
* @param frac_pos fractional part of position [0..precision-1]
* @param filter_length filter length
* @param length length of output
*
* filter_coeffs contains coefficients of the right half of the symmetric
* interpolation filter. filter_coeffs[0] should the central (unpaired) coefficient.
* See ff_acelp_interp_filter for an example.
*/
void ff_acelp_interpolate(int16_t* out, const int16_t* in,
const int16_t* filter_coeffs, int precision,
int frac_pos, int filter_length, int length);
/**
* Floating point version of ff_acelp_interpolate()
*/
void ff_acelp_interpolatef(float *out, const float *in,
const float *filter_coeffs, int precision,
int frac_pos, int filter_length, int length);
/**
* high-pass filtering and upscaling (4.2.5 of G.729).
* @param[out] out output buffer for filtered speech data
* @param[in,out] hpf_f past filtered data from previous (2 items long)
* frames (-0x20000000 <= (14.13) < 0x20000000)
* @param in speech data to process
* @param length input data size
*
* out[i] = 0.93980581 * in[i] - 1.8795834 * in[i-1] + 0.93980581 * in[i-2] +
* 1.9330735 * out[i-1] - 0.93589199 * out[i-2]
*
* The filter has a cut-off frequency of 1/80 of the sampling freq
*
* @note Two items before the top of the in buffer must contain two items from the
* tail of the previous subframe.
*
* @remark It is safe to pass the same array in in and out parameters.
*
* @remark AMR uses mostly the same filter (cut-off frequency 60Hz, same formula,
* but constants differs in 5th sign after comma). Fortunately in
* fixed-point all coefficients are the same as in G.729. Thus this
* routine can be used for the fixed-point AMR decoder, too.
*/
void ff_acelp_high_pass_filter(int16_t* out, int hpf_f[2],
const int16_t* in, int length);
/**
* Apply an order 2 rational transfer function in-place.
*
* @param out output buffer for filtered speech samples
* @param in input buffer containing speech data (may be the same as out)
* @param zero_coeffs z^-1 and z^-2 coefficients of the numerator
* @param pole_coeffs z^-1 and z^-2 coefficients of the denominator
* @param gain scale factor for final output
* @param mem intermediate values used by filter (should be 0 initially)
* @param n number of samples
*/
void ff_acelp_apply_order_2_transfer_function(float *out, const float *in,
const float zero_coeffs[2],
const float pole_coeffs[2],
float gain,
float mem[2], int n);
/**
* Apply tilt compensation filter, 1 - tilt * z-1.
*
* @param mem pointer to the filter's state (one single float)
* @param tilt tilt factor
* @param samples array where the filter is applied
* @param size the size of the samples array
*/
void ff_tilt_compensation(float *mem, float tilt, float *samples, int size);
#endif /* AVCODEC_ACELP_FILTERS_H */

View File

@ -0,0 +1,253 @@
/*
* gain code, gain pitch and pitch delay decoding
*
* Copyright (c) 2008 Vladimir Voroshilov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_ACELP_PITCH_DELAY_H
#define AVCODEC_ACELP_PITCH_DELAY_H
#include <stdint.h>
#include "audiodsp.h"
#define PITCH_DELAY_MIN 20
#define PITCH_DELAY_MAX 143
/**
* @brief Decode pitch delay of the first subframe encoded by 8 bits with 1/3
* resolution.
* @param ac_index adaptive codebook index (8 bits)
*
* @return pitch delay in 1/3 units
*
* Pitch delay is coded:
* with 1/3 resolution, 19 < pitch_delay < 85
* integers only, 85 <= pitch_delay <= 143
*/
int ff_acelp_decode_8bit_to_1st_delay3(int ac_index);
/**
* @brief Decode pitch delay of the second subframe encoded by 5 or 6 bits
* with 1/3 precision.
* @param ac_index adaptive codebook index (5 or 6 bits)
* @param pitch_delay_min lower bound (integer) of pitch delay interval
* for second subframe
*
* @return pitch delay in 1/3 units
*
* Pitch delay is coded:
* with 1/3 resolution, -6 < pitch_delay - int(prev_pitch_delay) < 5
*
* @remark The routine is used in G.729 @@8k, AMR @@10.2k, AMR @@7.95k,
* AMR @@7.4k for the second subframe.
*/
int ff_acelp_decode_5_6_bit_to_2nd_delay3(
int ac_index,
int pitch_delay_min);
/**
* @brief Decode pitch delay with 1/3 precision.
* @param ac_index adaptive codebook index (4 bits)
* @param pitch_delay_min lower bound (integer) of pitch delay interval for
* second subframe
*
* @return pitch delay in 1/3 units
*
* Pitch delay is coded:
* integers only, -6 < pitch_delay - int(prev_pitch_delay) <= -2
* with 1/3 resolution, -2 < pitch_delay - int(prev_pitch_delay) < 1
* integers only, 1 <= pitch_delay - int(prev_pitch_delay) < 5
*
* @remark The routine is used in G.729 @@6.4k, AMR @@6.7k, AMR @@5.9k,
* AMR @@5.15k, AMR @@4.75k for the second subframe.
*/
int ff_acelp_decode_4bit_to_2nd_delay3(
int ac_index,
int pitch_delay_min);
/**
* @brief Decode pitch delay of the first subframe encoded by 9 bits
* with 1/6 precision.
* @param ac_index adaptive codebook index (9 bits)
*
* @return pitch delay in 1/6 units
*
* Pitch delay is coded:
* with 1/6 resolution, 17 < pitch_delay < 95
* integers only, 95 <= pitch_delay <= 143
*
* @remark The routine is used in AMR @@12.2k for the first and third subframes.
*/
int ff_acelp_decode_9bit_to_1st_delay6(int ac_index);
/**
* @brief Decode pitch delay of the second subframe encoded by 6 bits
* with 1/6 precision.
* @param ac_index adaptive codebook index (6 bits)
* @param pitch_delay_min lower bound (integer) of pitch delay interval for
* second subframe
*
* @return pitch delay in 1/6 units
*
* Pitch delay is coded:
* with 1/6 resolution, -6 < pitch_delay - int(prev_pitch_delay) < 5
*
* @remark The routine is used in AMR @@12.2k for the second and fourth subframes.
*/
int ff_acelp_decode_6bit_to_2nd_delay6(
int ac_index,
int pitch_delay_min);
/**
* @brief Update past quantized energies
* @param[in,out] quant_energy past quantized energies (5.10)
* @param gain_corr_factor gain correction factor
* @param log2_ma_pred_order log2() of MA prediction order
* @param erasure frame erasure flag
*
* If frame erasure flag is not equal to zero, memory is updated with
* averaged energy, attenuated by 4dB:
* max(avg(quant_energy[i])-4, -14), i=0,ma_pred_order
*
* In normal mode memory is updated with
* Er - Ep = 20 * log10(gain_corr_factor)
*
* @remark The routine is used in G.729 and AMR (all modes).
*/
void ff_acelp_update_past_gain(
int16_t* quant_energy,
int gain_corr_factor,
int log2_ma_pred_order,
int erasure);
/**
* @brief Decode the adaptive codebook gain and add
* correction (4.1.5 and 3.9.1 of G.729).
* @param adsp initialized audio DSP context
* @param gain_corr_factor gain correction factor (2.13)
* @param fc_v fixed-codebook vector (2.13)
* @param mr_energy mean innovation energy and fixed-point correction (7.13)
* @param[in,out] quant_energy past quantized energies (5.10)
* @param subframe_size length of subframe
*
* @return quantized fixed-codebook gain (14.1)
*
* The routine implements equations 69, 66 and 71 of the G.729 specification (3.9.1)
*
* Em - mean innovation energy (dB, constant, depends on decoding algorithm)
* Ep - mean-removed predicted energy (dB)
* Er - mean-removed innovation energy (dB)
* Ei - mean energy of the fixed-codebook contribution (dB)
* N - subframe_size
* M - MA (Moving Average) prediction order
* gc - fixed-codebook gain
* gc_p - predicted fixed-codebook gain
*
* Fixed codebook gain is computed using predicted gain gc_p and
* correction factor gain_corr_factor as shown below:
*
* gc = gc_p * gain_corr_factor
*
* The predicted fixed codebook gain gc_p is found by predicting
* the energy of the fixed-codebook contribution from the energy
* of previous fixed-codebook contributions.
*
* mean = 1/N * sum(i,0,N){ fc_v[i] * fc_v[i] }
*
* Ei = 10log(mean)
*
* Er = 10log(1/N * gc^2 * mean) - Em = 20log(gc) + Ei - Em
*
* Replacing Er with Ep and gc with gc_p we will receive:
*
* Ep = 10log(1/N * gc_p^2 * mean) - Em = 20log(gc_p) + Ei - Em
*
* and from above:
*
* gc_p = 10^((Ep - Ei + Em) / 20)
*
* Ep is predicted using past energies and prediction coefficients:
*
* Ep = sum(i,0,M){ ma_prediction_coeff[i] * quant_energy[i] }
*
* gc_p in fixed-point arithmetic is calculated as following:
*
* mean = 1/N * sum(i,0,N){ (fc_v[i] / 2^13) * (fc_v[i] / 2^13) } =
* = 1/N * sum(i,0,N) { fc_v[i] * fc_v[i] } / 2^26
*
* Ei = 10log(mean) = -10log(N) - 10log(2^26) +
* + 10log(sum(i,0,N) { fc_v[i] * fc_v[i] })
*
* Ep - Ei + Em = Ep + Em + 10log(N) + 10log(2^26) -
* - 10log(sum(i,0,N) { fc_v[i] * fc_v[i] }) =
* = Ep + mr_energy - 10log(sum(i,0,N) { fc_v[i] * fc_v[i] })
*
* gc_p = 10 ^ ((Ep - Ei + Em) / 20) =
* = 2 ^ (3.3219 * (Ep - Ei + Em) / 20) = 2 ^ (0.166 * (Ep - Ei + Em))
*
* where
*
* mr_energy = Em + 10log(N) + 10log(2^26)
*
* @remark The routine is used in G.729 and AMR (all modes).
*/
int16_t ff_acelp_decode_gain_code(
AudioDSPContext *adsp,
int gain_corr_factor,
const int16_t* fc_v,
int mr_energy,
const int16_t* quant_energy,
const int16_t* ma_prediction_coeff,
int subframe_size,
int max_pred_order);
/**
* Calculate fixed gain (part of section 6.1.3 of AMR spec)
*
* @param fixed_gain_factor gain correction factor
* @param fixed_mean_energy mean decoded algebraic codebook vector energy
* @param prediction_error vector of the quantified predictor errors of
* the four previous subframes. It is updated by this function.
* @param energy_mean desired mean innovation energy
* @param pred_table table of four moving average coefficients
*/
float ff_amr_set_fixed_gain(float fixed_gain_factor, float fixed_mean_energy,
float *prediction_error, float energy_mean,
const float *pred_table);
/**
* Decode the adaptive codebook index to the integer and fractional parts
* of the pitch lag for one subframe at 1/3 fractional precision.
*
* The choice of pitch lag is described in 3GPP TS 26.090 section 5.6.1.
*
* @param lag_int integer part of pitch lag of the current subframe
* @param lag_frac fractional part of pitch lag of the current subframe
* @param pitch_index parsed adaptive codebook (pitch) index
* @param prev_lag_int integer part of pitch lag for the previous subframe
* @param subframe current subframe number
* @param third_as_first treat the third frame the same way as the first
*/
void ff_decode_pitch_lag(int *lag_int, int *lag_frac, int pitch_index,
const int prev_lag_int, const int subframe,
int third_as_first, int resolution);
#endif /* AVCODEC_ACELP_PITCH_DELAY_H */

View File

@ -0,0 +1,288 @@
/*
* adaptive and fixed codebook vector operations for ACELP-based codecs
*
* Copyright (c) 2008 Vladimir Voroshilov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_ACELP_VECTORS_H
#define AVCODEC_ACELP_VECTORS_H
#include <stdint.h>
typedef struct ACELPVContext {
/**
* float implementation of weighted sum of two vectors.
* @param[out] out result of addition
* @param in_a first vector
* @param in_b second vector
* @param weight_coeff_a first vector weight coefficient
* @param weight_coeff_a second vector weight coefficient
* @param length vectors length (should be a multiple of two)
*
* @note It is safe to pass the same buffer for out and in_a or in_b.
*/
void (*weighted_vector_sumf)(float *out, const float *in_a, const float *in_b,
float weight_coeff_a, float weight_coeff_b,
int length);
}ACELPVContext;
/**
* Initialize ACELPVContext.
*/
void ff_acelp_vectors_init(ACELPVContext *c);
void ff_acelp_vectors_init_mips(ACELPVContext *c);
/** Sparse representation for the algebraic codebook (fixed) vector */
typedef struct AMRFixed {
int n;
int x[10];
float y[10];
int no_repeat_mask;
int pitch_lag;
float pitch_fac;
} AMRFixed;
/**
* Track|Pulse| Positions
* -------------------------------------------------------------------------
* 1 | 0 | 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75
* -------------------------------------------------------------------------
* 2 | 1 | 1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76
* -------------------------------------------------------------------------
* 3 | 2 | 2, 7, 12, 17, 22, 27, 32, 37, 42, 47, 52, 57, 62, 67, 72, 77
* -------------------------------------------------------------------------
*
* Table contains only first the pulse indexes.
*
* Used in G.729 @@8k, G.729 @@4.4k, AMR @@7.95k, AMR @@7.40k
*/
extern const uint8_t ff_fc_4pulses_8bits_tracks_13[16];
/**
* Track|Pulse| Positions
* -------------------------------------------------------------------------
* 4 | 3 | 3, 8, 13, 18, 23, 28, 33, 38, 43, 48, 53, 58, 63, 68, 73, 78
* | | 4, 9, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64, 69, 74, 79
* -------------------------------------------------------------------------
*
* @remark Track in the table should be read top-to-bottom, left-to-right.
*
* Used in G.729 @@8k, G.729 @@4.4k, AMR @@7.95k, AMR @@7.40k
*/
extern const uint8_t ff_fc_4pulses_8bits_track_4[32];
/**
* Track|Pulse| Positions
* -----------------------------------------
* 1 | 0 | 1, 6, 11, 16, 21, 26, 31, 36
* | | 3, 8, 13, 18, 23, 28, 33, 38
* -----------------------------------------
*
* @remark Track in the table should be read top-to-bottom, left-to-right.
*
* @note (EE) Reference G.729D code also uses gray decoding for each
* pulse index before looking up the value in the table.
*
* Used in G.729 @@6.4k (with gray coding), AMR @@5.9k (without gray coding)
*/
extern const uint8_t ff_fc_2pulses_9bits_track1[16];
extern const uint8_t ff_fc_2pulses_9bits_track1_gray[16];
/**
* Track|Pulse| Positions
* -----------------------------------------
* 2 | 1 | 0, 7, 14, 20, 27, 34, 1, 21
* | | 2, 9, 15, 22, 29, 35, 6, 26
* | | 4,10, 17, 24, 30, 37, 11, 31
* | | 5,12, 19, 25, 32, 39, 16, 36
* -----------------------------------------
*
* @remark Track in the table should be read top-to-bottom, left-to-right.
*
* @note (EE.1) This table (from the reference code) does not comply with
* the specification.
* The specification contains the following table:
*
* Track|Pulse| Positions
* -----------------------------------------
* 2 | 1 | 0, 5, 10, 15, 20, 25, 30, 35
* | | 1, 6, 11, 16, 21, 26, 31, 36
* | | 2, 7, 12, 17, 22, 27, 32, 37
* | | 4, 9, 14, 19, 24, 29, 34, 39
*
* -----------------------------------------
*
* @note (EE.2) Reference G.729D code also uses gray decoding for each
* pulse index before looking up the value in the table.
*
* Used in G.729 @@6.4k (with gray coding)
*/
extern const uint8_t ff_fc_2pulses_9bits_track2_gray[32];
/**
* b60 hamming windowed sinc function coefficients
*/
extern const float ff_b60_sinc[61];
/**
* Table of pow(0.7,n)
*/
extern const float ff_pow_0_7[10];
/**
* Table of pow(0.75,n)
*/
extern const float ff_pow_0_75[10];
/**
* Table of pow(0.55,n)
*/
extern const float ff_pow_0_55[10];
/**
* Decode fixed-codebook vector (3.8 and D.5.8 of G.729, 5.7.1 of AMR).
* @param[out] fc_v decoded fixed codebook vector (2.13)
* @param tab1 table used for first pulse_count pulses
* @param tab2 table used for last pulse
* @param pulse_indexes fixed codebook indexes
* @param pulse_signs signs of the excitation pulses (0 bit value
* means negative sign)
* @param bits number of bits per one pulse index
* @param pulse_count number of pulses decoded using first table
* @param bits length of one pulse index in bits
*
* Used in G.729 @@8k, G.729 @@4.4k, G.729 @@6.4k, AMR @@7.95k, AMR @@7.40k
*/
void ff_acelp_fc_pulse_per_track(int16_t* fc_v,
const uint8_t *tab1,
const uint8_t *tab2,
int pulse_indexes,
int pulse_signs,
int pulse_count,
int bits);
/**
* Decode the algebraic codebook index to pulse positions and signs and
* construct the algebraic codebook vector for MODE_12k2.
*
* @note: The positions and signs are explicitly coded in MODE_12k2.
*
* @param fixed_index positions of the ten pulses
* @param fixed_sparse pointer to the algebraic codebook vector
* @param gray_decode gray decoding table
* @param half_pulse_count number of couples of pulses
* @param bits length of one pulse index in bits
*/
void ff_decode_10_pulses_35bits(const int16_t *fixed_index,
AMRFixed *fixed_sparse,
const uint8_t *gray_decode,
int half_pulse_count, int bits);
/**
* weighted sum of two vectors with rounding.
* @param[out] out result of addition
* @param in_a first vector
* @param in_b second vector
* @param weight_coeff_a first vector weight coefficient
* @param weight_coeff_a second vector weight coefficient
* @param rounder this value will be added to the sum of the two vectors
* @param shift result will be shifted to right by this value
* @param length vectors length
*
* @note It is safe to pass the same buffer for out and in_a or in_b.
*
* out[i] = (in_a[i]*weight_a + in_b[i]*weight_b + rounder) >> shift
*/
void ff_acelp_weighted_vector_sum(int16_t* out,
const int16_t *in_a,
const int16_t *in_b,
int16_t weight_coeff_a,
int16_t weight_coeff_b,
int16_t rounder,
int shift,
int length);
/**
* float implementation of weighted sum of two vectors.
* @param[out] out result of addition
* @param in_a first vector
* @param in_b second vector
* @param weight_coeff_a first vector weight coefficient
* @param weight_coeff_a second vector weight coefficient
* @param length vectors length
*
* @note It is safe to pass the same buffer for out and in_a or in_b.
*/
void ff_weighted_vector_sumf(float *out, const float *in_a, const float *in_b,
float weight_coeff_a, float weight_coeff_b,
int length);
/**
* Adaptive gain control (as used in AMR postfiltering)
*
* @param out output buffer for filtered speech data
* @param in the input speech buffer (may be the same as out)
* @param speech_energ input energy
* @param size the input buffer size
* @param alpha exponential filter factor
* @param gain_mem a pointer to the filter memory (single float of size)
*/
void ff_adaptive_gain_control(float *out, const float *in, float speech_energ,
int size, float alpha, float *gain_mem);
/**
* Set the sum of squares of a signal by scaling
*
* @param out output samples
* @param in input samples
* @param sum_of_squares new sum of squares
* @param n number of samples
*
* @note If the input is zero (or its energy underflows), the output is zero.
* This is the behavior of AGC in the AMR reference decoder. The QCELP
* reference decoder seems to have undefined behavior.
*
* TIA/EIA/IS-733 2.4.8.3-2/3/4/5, 2.4.8.6
* 3GPP TS 26.090 6.1 (6)
*/
void ff_scale_vector_to_given_sum_of_squares(float *out, const float *in,
float sum_of_squares, const int n);
/**
* Add fixed vector to an array from a sparse representation
*
* @param out fixed vector with pitch sharpening
* @param in sparse fixed vector
* @param scale number to multiply the fixed vector by
* @param size the output vector size
*/
void ff_set_fixed_vector(float *out, const AMRFixed *in, float scale, int size);
/**
* Clear array values set by set_fixed_vector
*
* @param out fixed vector to be cleared
* @param in sparse fixed vector
* @param size the output vector size
*/
void ff_clear_fixed_vector(float *out, const AMRFixed *in, int size);
#endif /* AVCODEC_ACELP_VECTORS_H */

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2001-2003 The FFmpeg project
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* ADPCM encoder/decoder common header.
*/
#ifndef AVCODEC_ADPCM_H
#define AVCODEC_ADPCM_H
#include <stdint.h>
#define BLKSIZE 1024
typedef struct ADPCMChannelStatus {
int predictor;
int16_t step_index;
int step;
/* for encoding */
int prev_sample;
/* MS version */
int sample1;
int sample2;
int coeff1;
int coeff2;
int idelta;
} ADPCMChannelStatus;
#endif /* AVCODEC_ADPCM_H */

View File

@ -0,0 +1,46 @@
/*
* Copyright (c) 2001-2003 The FFmpeg project
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* ADPCM tables
*/
#ifndef AVCODEC_ADPCM_DATA_H
#define AVCODEC_ADPCM_DATA_H
#include <stdint.h>
static const uint8_t ff_adpcm_ima_block_sizes[4] = { 4, 12, 4, 20 };
static const uint8_t ff_adpcm_ima_block_samples[4] = { 16, 32, 8, 32 };
extern const int8_t * const ff_adpcm_index_tables[4];
extern const int8_t ff_adpcm_index_table[16];
extern const int16_t ff_adpcm_step_table[89];
extern const int16_t ff_adpcm_oki_step_table[49];
extern const int16_t ff_adpcm_AdaptationTable[];
extern const uint8_t ff_adpcm_AdaptCoeff1[];
extern const int8_t ff_adpcm_AdaptCoeff2[];
extern const int16_t ff_adpcm_yamaha_indexscale[];
extern const int8_t ff_adpcm_yamaha_difflookup[];
extern const int16_t ff_adpcm_afc_coeffs[2][16];
extern const int16_t ff_adpcm_mtaf_stepsize[32][16];
#endif /* AVCODEC_ADPCM_DATA_H */

Some files were not shown because too many files have changed in this diff Show More