diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml index ad4d0929..ac0af126 100644 --- a/.github/workflows/c-cpp.yml +++ b/.github/workflows/c-cpp.yml @@ -19,8 +19,16 @@ jobs: - name: Compile project run: make - + + - name: Prepare artifact folder + run: | + mkdir -p CMFileManagerPSP + cp audio_driver/audio_driver.prx CMFileManagerPSP/ + cp display_driver/display_driver.prx CMFileManagerPSP/ + cp fs_driver/fs_driver.prx CMFileManagerPSP/ + cp app/EBOOT.PBP CMFileManagerPSP/ + - uses: actions/upload-artifact@v4 with: - name: CMFileManager-PSP - path: app/EBOOT.PBP + name: CMFileManagerPSP + path: CMFileManagerPSP/ diff --git a/.gitignore b/.gitignore index de4d62cf..33fc0175 100644 --- a/.gitignore +++ b/.gitignore @@ -54,8 +54,9 @@ Mkfile.old dkms.conf # CMFileManager PSP Specific objects +app/drivers/audio_driver.S app/drivers/display_driver.S app/drivers/fs_driver.S -app/drivers/module_driver.S +app/drivers/input_driver.S app/*.json app/*.log diff --git a/Makefile b/Makefile index 3ac8ce3c..8f959f5e 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -SUBDIRS = display_driver fs_driver module_driver app launcher +SUBDIRS = audio_driver display_driver fs_driver app launcher all: @for dir in $(SUBDIRS); do $(MAKE) -C $$dir; done diff --git a/app/Makefile b/app/Makefile index 58fb5373..0aa04cfe 100644 --- a/app/Makefile +++ b/app/Makefile @@ -1,22 +1,21 @@ TARGET = CMFileManager SOURCES := data drivers source source/audio source/gui ../libs/libnsbmp ../libs/libnsgif -CFILES := $(foreach dir, $(SOURCES), $(wildcard $(dir)/*.c)) -SFILES := $(foreach dir, $(SOURCES), $(wildcard $(dir)/*.S)) -CPPFILES := $(foreach dir, $(SOURCES), $(wildcard $(dir)/*.cpp)) -FONTFILES := $(foreach dir, $(SOURCES), $(wildcard $(dir)/*.pgf)) -GFXFILES := $(foreach dir, $(SOURCES), $(wildcard $(dir)/*.png)) -PRXFILES := $(foreach dir, $(SOURCES), $(wildcard $(dir)/*.prx)) +CFILES := $(foreach dir,$(SOURCES), $(wildcard $(dir)/*.c)) +SFILES := $(foreach dir,$(SOURCES), $(wildcard $(dir)/*.S)) +CPPFILES := $(foreach dir,$(SOURCES), $(wildcard $(dir)/*.cpp)) +GFXFILES := $(foreach dir,$(SOURCES), $(wildcard $(dir)/*.png)) +FONTFILES := $(foreach dir,$(SOURCES), $(wildcard $(dir)/*.pgf)) -OBJS := $(addsuffix .o,$(BINFILES)) $(CFILES:.c=.o) $(SFILES:.S=.o) $(CPPFILES:.cpp=.o) \ - $(FONTFILES:.pgf=.o) $(GFXFILES:.png=.o) $(PRXFILES:.prx=.o) +OBJS := $(addsuffix .o,$(BINFILES)) \ + $(CFILES:.c=.o) $(SFILES:.S=.o) $(CPPFILES:.cpp=.o) $(GFXFILES:.png=.o) $(FONTFILES:.pgf=.o) VERSION_MAJOR := 4 VERSION_MINOR := 1 VERSION_MICRO := 0 INCDIR = ../libs/ ../libs/include ../libs/libnsbmp ../libs/libnsgif ../libs/include/opus include -CFLAGS = -Os -G0 -Wall -ffast-math -Wno-narrowing -Wno-unused-variable \ +CFLAGS = -Os -mno-gpopt -Wall -ffast-math -Wno-narrowing -Wno-unused-variable \ -DVERSION_MAJOR=$(VERSION_MAJOR) -DVERSION_MINOR=$(VERSION_MINOR) -DVERSION_MICRO=$(VERSION_MICRO) CXXFLAGS = $(CFLAGS) -fno-exceptions -fno-rtti -std=gnu++17 ASFLAGS := $(CFLAGS) @@ -26,22 +25,19 @@ BUILD_PRX = 1 LIBDIR = ../libs/lib LDFLAGS = LIBS = -lintrafont -lglib2d -lxmp -lmpg123 -lvorbisfile -lvorbis -lopusfile -lopus -lFLAC -logg \ - -larchive -llzma -ljpeg -lpng16 -lstdc++ -lz \ + -larchive -llzma -lturbojpeg -ljpeg -lpng16 -lstdc++ -lz \ -lpspkubridge -lpspsystemctrl_user -lpspusbdevice \ -lpspgu -lpspvram -lpspaudio -lpsppower -lpspreg -lpspusb -lpspusbstor -lpspumd -EXTRA_TARGETS = EBOOT.PBP -PSP_EBOOT_TITLE = CM File Manager PSP v$(VERSION_MAJOR).$(VERSION_MINOR)$(VERSION_MICRO) -PSP_EBOOT_ICON = ../ICON0.PNG +EXTRA_TARGETS = EBOOT.PBP +PSP_EBOOT_TITLE = CM File Manager PSP v$(VERSION_MAJOR).$(VERSION_MINOR)$(VERSION_MICRO) +PSP_EBOOT_ICON = ../ICON0.PNG PSPSDK=$(shell psp-config --pspsdk-path) include $(PSPSDK)/lib/build.mak -%.o: %.pgf - bin2o -i $< $@ $(addsuffix _pgf, $(basename $(notdir $<) )) - %.o: %.png bin2o -i $< $@ $(addsuffix _png, $(basename $(notdir $<) )) -%.o: %.prx - bin2o -i $< $@ $(addsuffix _prx, $(basename $(notdir $<) )) \ No newline at end of file +%.o: %.pgf + bin2o -i $< $@ $(addsuffix _pgf, $(basename $(notdir $<) )) diff --git a/app/include/fs.h b/app/include/fs.h index 7ac17eb1..e9ab565c 100644 --- a/app/include/fs.h +++ b/app/include/fs.h @@ -25,7 +25,7 @@ namespace FS { int MakeDir(const std::string &path); int RecursiveMakeDir(const std::string &path); int CreateFile(const std::string &path); - std::string GetFileExt(const std::string &filename); + const char* GetFileExt(const char *filename); FileType GetFileType(const std::string &filename); SceOff GetFileSize(const std::string &path); char *GetFileTimestamp(SceIoStat &stat, FileTimestamp time); diff --git a/app/include/kernel_functions.h b/app/include/kernel_functions.h index abb44990..d351e06f 100644 --- a/app/include/kernel_functions.h +++ b/app/include/kernel_functions.h @@ -6,12 +6,11 @@ extern "C" { #include #include -#include // Kernel function prototypes // audio_driver functions -int pspAudioSetFrequency(int frequency); +extern int pspAudioSetFrequency(int frequency); // display_driver functions extern int pspDisplayEnable(void); @@ -34,9 +33,6 @@ extern int pspIoRename(const char *oldname, const char *newname); extern int pspIoRemoveFile(const char *file); extern int pspIoDevctl(const char *dev, unsigned int cmd, void *indata, int inlen, void *outdata, int outlen); -// module_driver functions -extern int pspKernelLoadModuleBuffer(SceSize size, void *buf, s32 flag, const SceKernelLMOption *option); - #if defined (__cplusplus) } #endif diff --git a/app/include/textures.h b/app/include/textures.h index 8149b8c4..1c51c24d 100644 --- a/app/include/textures.h +++ b/app/include/textures.h @@ -19,7 +19,7 @@ extern g2dTexture *file_icons[NUM_FILE_ICONS], *icon_dir[NUM_THEMES], *icon_chec namespace Textures { g2dTexture *LoadImageBufferJPEG(unsigned char *data, int size); g2dTexture *LoadImageBufferPNG(unsigned char *data, int size); - g2dTexture *LoadImage(const std::string &path); + g2dTexture *LoadImage(const std::string &path, int size); void Load(void); void Free(void); } diff --git a/app/source/audio.cpp b/app/source/audio.cpp index d44a9f12..cb045ffa 100644 --- a/app/source/audio.cpp +++ b/app/source/audio.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include #include "fs.h" #include "kernel_functions.h" @@ -37,32 +37,37 @@ namespace Audio { static void Decode(void *buf, unsigned int length, void *userdata) { if ((!playing) || (paused)) { - s16 *buf_s16 = static_cast(buf); - for (unsigned int count = 0; count < length * 4; count++) - *(buf_s16 + count) = 0; + std::memset(buf, 0, length * 4); } - else - (* decoder.decode)(buf, length, userdata); + else { + (*decoder.decode)(buf, length, userdata); + } } void Init(const std::string &path) { playing = true; paused = false; + const char *ext = FS::GetFileExt(path.c_str()); - std::string ext = FS::GetFileExt(path); - - if (!ext.compare(".FLAC")) + if (strncasecmp(ext, "flac", 4) == 0) { file_type = FILE_TYPE_FLAC; - else if (!ext.compare(".MP3")) + } + else if (strncasecmp(ext, "mp3", 3) == 0) { file_type = FILE_TYPE_MP3; - else if (!ext.compare(".OGG")) + } + else if (strncasecmp(ext, "ogg", 3) == 0) { file_type = FILE_TYPE_OGG; - else if (!ext.compare(".OPUS")) + } + else if (strncasecmp(ext, "opus", 4) == 0) { file_type = FILE_TYPE_OPUS; - else if (!ext.compare(".WAV")) + } + else if (strncasecmp(ext, "wav", 3) == 0) { file_type = FILE_TYPE_WAV; - else if ((!ext.compare(".IT")) || (!ext.compare(".MOD")) || (!ext.compare(".S3M")) || (!ext.compare(".XM"))) + } + else if ((strncasecmp(ext, "it", 2) == 0) || (strncasecmp(ext, "mod", 3) == 0) || (strncasecmp(ext, "s3m", 3) == 0) + || (strncasecmp(ext, "xm", 2) == 0)) { file_type = FILE_TYPE_XM; + } switch(file_type) { case FILE_TYPE_FLAC: @@ -184,9 +189,8 @@ namespace Audio { (* decoder.term)(); // Clear metadata struct - if (metadata.has_meta) { - if (metadata.cover_image) - g2dTexFree(&metadata.cover_image); + if (metadata.has_meta && metadata.cover_image) { + g2dTexFree(&metadata.cover_image); } metadata = { 0 }; diff --git a/app/source/audio/ogg.cpp b/app/source/audio/ogg.cpp index 335a106f..2f64849f 100644 --- a/app/source/audio/ogg.cpp +++ b/app/source/audio/ogg.cpp @@ -1,9 +1,9 @@ #include +#include +#include #include "audio.h" #include "utils.h" -#include "vorbis/codec.h" -#include "vorbis/vorbisfile.h" namespace OGG { static OggVorbis_File ogg; diff --git a/app/source/audio/xm.cpp b/app/source/audio/xm.cpp index 16fa5e1e..01be638f 100644 --- a/app/source/audio/xm.cpp +++ b/app/source/audio/xm.cpp @@ -1,5 +1,6 @@ +#include + #include "audio.h" -#include "xmp.h" namespace XM { static xmp_context xmp; diff --git a/app/source/fs.cpp b/app/source/fs.cpp index caaec4a1..e41714a7 100644 --- a/app/source/fs.cpp +++ b/app/source/fs.cpp @@ -12,9 +12,9 @@ namespace FS { typedef struct { - std::string copy_path; - std::string copy_filename; - bool is_dir = false; + std::string path; + std::string filename; + bool isDir = false; } FSCopyEntry; static FSCopyEntry fs_copy_entry; @@ -46,31 +46,32 @@ namespace FS { int MakeDir(const std::string &path) { int ret = 0; #ifdef FS_DEBUG - if (R_FAILED(ret = sceIoMkdir(path.c_str(), 0777))) - return ret; + if (R_FAILED(ret = sceIoMkdir(path.c_str(), 0777))) { #else - if (R_FAILED(ret = pspIoMakeDir(path.c_str(), 0777))) - return ret; + if (R_FAILED(ret = pspIoMakeDir(path.c_str(), 0777))) { #endif + return ret; + } return 0; } // https://newbedev.com/mkdir-c-function int RecursiveMakeDir(const std::string &path) { - std::string current_level = ""; + std::string currentLevel = ""; std::string level; std::stringstream ss(path); // split path using slash as a separator while (std::getline(ss, level, '/')) { - current_level += level; // append folder to the current level + currentLevel += level; // append folder to the current level // create current level - if (!FS::DirExists(current_level) && FS::MakeDir(current_level.c_str()) != 0) + if (!FS::DirExists(currentLevel) && FS::MakeDir(currentLevel.c_str()) != 0) { return -1; + } - current_level += "/"; // don't forget to append a slash + currentLevel += "/"; // don't forget to append a slash } return 0; @@ -94,28 +95,42 @@ namespace FS { return file; } - std::string GetFileExt(const std::string &filename) { - std::string ext = std::filesystem::path(filename).extension(); - std::transform(ext.begin(), ext.end(), ext.begin(), ::toupper); - return ext; + const char* GetFileExt(const char *filename) { + const char *ext = strrchr(filename, '.'); + + if (ext == NULL) { + return ""; + } + + return ext + 1; } - + FileType GetFileType(const std::string &filename) { - std::string ext = FS::GetFileExt(filename); + const char *ext = FS::GetFileExt(filename.c_str()); - if ((!ext.compare(".CSO")) || (!ext.compare(".ISO")) || (!ext.compare(".PBP"))) + if ((strncasecmp(ext, "cso", 3) == 0) || (strncasecmp(ext, "iso", 3) == 0) || (strncasecmp(ext, "pbp", 3) == 0)) { return FileTypeApp; - else if ((!ext.compare(".7Z")) || (!ext.compare(".LZMA")) || (!ext.compare(".RAR")) || (!ext.compare(".ZIP"))) + } + else if ((strncasecmp(ext, "7z", 2) == 0) || (strncasecmp(ext, "lzma", 4) == 0) || (strncasecmp(ext, "rar", 3) == 0) + || (strncasecmp(ext, "zip", 3) == 0)) { return FileTypeArchive; - else if ((!ext.compare(".FLAC")) || (!ext.compare(".IT")) || (!ext.compare(".MOD")) || (!ext.compare(".MP3")) || (!ext.compare(".OGG")) - || (!ext.compare(".OPUS")) || (!ext.compare(".S3M")) || (!ext.compare(".WAV")) || (!ext.compare(".XM"))) - return FileTypeAudio; - else if ((!ext.compare(".BMP")) || (!ext.compare(".GIF")) || (!ext.compare(".JPG")) || (!ext.compare(".JPEG")) || (!ext.compare(".PGM")) - || (!ext.compare(".PPM")) || (!ext.compare(".PNG")) || (!ext.compare(".PSD")) || (!ext.compare(".TGA")) || (!ext.compare(".WEBP"))) - return FileTypeImage; - else if ((!ext.compare(".CFG")) || (!ext.compare(".CONF")) || (!ext.compare(".INI")) || (!ext.compare(".JSON")) || (!ext.compare(".LOG")) - || (!ext.compare(".MD")) || (!ext.compare(".TXT"))) + } + else if ((strncasecmp(ext, "flac", 4) == 0) || (strncasecmp(ext, "it", 2) == 0) || (strncasecmp(ext, "mod", 3) == 0) + || (strncasecmp(ext, "mp3", 3) == 0) || (strncasecmp(ext, "ogg", 3) == 0) || (strncasecmp(ext, "opus", 4) == 0) + || (strncasecmp(ext, "s3m", 3) == 0) || (strncasecmp(ext, "wav", 3) == 0) || (strncasecmp(ext, "xm", 2) == 0)) { + return FileTypeAudio; + } + else if ((strncasecmp(ext, "bmp", 3) == 0) || (strncasecmp(ext, "gif", 3) == 0) || (strncasecmp(ext, "jpg", 3) == 0) + || (strncasecmp(ext, "jpeg", 4) == 0) || (strncasecmp(ext, "pgm", 3) == 0) || (strncasecmp(ext, "ppm", 3) == 0) + || (strncasecmp(ext, "png", 3) == 0) || (strncasecmp(ext, "psd", 3) == 0) || (strncasecmp(ext, "tga", 3) == 0) + || (strncasecmp(ext, "webp", 4) == 0)) { + return FileTypeImage; + } + else if ((strncasecmp(ext, "cfg", 3) == 0) || (strncasecmp(ext, "conf", 4) == 0) || (strncasecmp(ext, "ini", 3) == 0) + || (strncasecmp(ext, "json", 4) == 0) || (strncasecmp(ext, "log", 3) == 0) || (strncasecmp(ext, "md", 2) == 0) + || (strncasecmp(ext, "txt", 3) == 0)) { return FileTypeText; + } return FileTypeNone; } @@ -127,12 +142,12 @@ namespace FS { std::memset(&stat, 0, sizeof(stat)); #ifdef FS_DEBUG - if (R_FAILED(ret = sceIoGetstat(path.c_str(), &stat))) - return ret; + if (R_FAILED(ret = sceIoGetstat(path.c_str(), &stat))) { #else - if (R_FAILED(ret = pspIoGetstat(path.c_str(), &stat))) - return ret; + if (R_FAILED(ret = pspIoGetstat(path.c_str(), &stat))) { #endif + return ret; + } return stat.st_size; } @@ -211,41 +226,33 @@ namespace FS { return file; } - static bool Sort(const SceIoDirent &entryA, const SceIoDirent &entryB) { - if ((FIO_S_ISDIR(entryA.d_stat.st_mode)) && !(FIO_S_ISDIR(entryB.d_stat.st_mode))) - return true; - else if (!(FIO_S_ISDIR(entryA.d_stat.st_mode)) && (FIO_S_ISDIR(entryB.d_stat.st_mode))) - return false; - else { - switch(cfg.sort) { - case 0: - if (strcasecmp(entryA.d_name, entryB.d_name) < 0) - return true; - break; - - case 1: - if (strcasecmp(entryB.d_name, entryA.d_name) < 0) - return true; - break; - - case 2: - if (entryB.d_stat.st_size < entryA.d_stat.st_size) - return true; - break; - - case 3: - if (entryA.d_stat.st_size < entryB.d_stat.st_size) - return true; - break; - - default: - break; - } + static bool Sort(const SceIoDirent &a, const SceIoDirent &b) { + bool aIsDir = FIO_S_ISDIR(a.d_stat.st_mode); + bool bIsDir = FIO_S_ISDIR(b.d_stat.st_mode); + + // Directories first + if (aIsDir != bIsDir) { + return aIsDir; + } + + switch (cfg.sort) { + case 0: // Name A-Z + return strcasecmp(a.d_name, b.d_name) < 0; + + case 1: // Name Z-A + return strcasecmp(a.d_name, b.d_name) > 0; + + case 2: // Size descending + return a.d_stat.st_size > b.d_stat.st_size; + + case 3: // Size ascending + return a.d_stat.st_size < b.d_stat.st_size; + + default: + return false; } - - return false; } - + int GetDirList(const std::string &path, std::vector &entries) { int ret = 0; SceUID dir = 0; @@ -253,89 +260,92 @@ namespace FS { #ifdef FS_DEBUG if (R_FAILED(ret = dir = sceIoDopen(path.c_str()))) { - Log::Error("sceIoDopen(%s) failed: 0x%08x\n", path.c_str(), ret); + Log::Error("%s(sceIoDopen) failed: %s (0x%08x)\n", __func__, path.c_str(), ret); return ret; } #else if (R_FAILED(ret = dir = pspIoOpenDir(path.c_str()))) { - Log::Error("pspIoOpenDir(%s) failed: 0x%08x\n", path.c_str(), ret); + Log::Error("%s(pspIoOpenDir) failed: %s (0x%08x)\n", __func__, path.c_str(), ret); return ret; } #endif - do { - SceIoDirent entry; + dir = ret; + SceIoDirent entry; + + while (true) { std::memset(&entry, 0, sizeof(entry)); - #ifdef FS_DEBUG ret = sceIoDread(dir, &entry); #else ret = pspIoReadDir(dir, &entry); #endif - if (ret > 0) { - if ((std::strcmp(entry.d_name, ".") == 0) || (std::strcmp(entry.d_name, "..") == 0)) - continue; - - entries.push_back(entry); + if (ret <= 0) { + break; } - } while (ret > 0); - - std::sort(entries.begin(), entries.end(), FS::Sort); - + + if (entry.d_name[0] == '.' && (entry.d_name[1] == '\0' || (entry.d_name[1] == '.' && entry.d_name[2] == '\0'))) { + continue; // skip "." and ".." + } + + entries.push_back(entry); + } + #ifdef FS_DEBUG sceIoDclose(dir); #else pspIoCloseDir(dir); #endif + + std::sort(entries.begin(), entries.end(), FS::Sort); return 0; } - //TODO: Clean up change directory impl. static int ChangeDir(const std::string &path, std::vector &entries) { int ret = 0; - std::vector new_entries; + std::vector newEntries; - if (R_FAILED(ret = FS::GetDirList(path, new_entries))) + if (R_FAILED(ret = FS::GetDirList(path, newEntries))) { return ret; - - // Free entries and change the current working directory. - entries.clear(); + } + + entries.swap(newEntries); cfg.cwd = path; - entries = new_entries; return 0; } int ChangeDirNext(const std::string &path, std::vector &entries) { - std::string new_path = FS::BuildPath(cfg.cwd, path); - return FS::ChangeDir(new_path, entries); + const std::string newPath = FS::BuildPath(cfg.cwd, path); + return FS::ChangeDir(newPath, entries); } int ChangeDirPrev(std::vector &entries) { - std::filesystem::path path = cfg.cwd; - std::string parent_path = path.parent_path(); + std::string parentPath = std::filesystem::path(cfg.cwd).parent_path().string(); - if (parent_path.back() == ':') - parent_path.append("/"); + if (!parentPath.empty() && parentPath.back() == ':') { + parentPath += '/'; + } - return FS::ChangeDir(parent_path.empty()? cfg.cwd : parent_path, entries); + return FS::ChangeDir(parentPath.empty()? cfg.cwd : parentPath, entries); } std::string GetFilename(const std::string &path) { - return std::filesystem::path(path).filename().u8string(); + std::size_t pos = path.find_last_of("/\\"); + return (pos == std::string::npos)? path : path.substr(pos + 1); } - static int CopyFile(const std::string &src_path, const std::string &dest_path) { + static int CopyFile(const std::string &src_path, const std::string &destPath) { int ret = 0; - SceUID src_handle = 0, dest_handle = 0; + SceUID srcHandle = 0, destHandle = 0; scePowerLock(0); #ifdef FS_DEBUG - if (R_FAILED(ret = src_handle = sceIoOpen(src_path.c_str(), PSP_O_RDONLY, 0))) { + if (R_FAILED(ret = srcHandle = sceIoOpen(src_path.c_str(), PSP_O_RDONLY, 0))) { Log::Error("sceIoOpen(%s) failed: 0x%x\n", src_path.c_str(), ret); scePowerUnlock(0); return ret; } #else - if (R_FAILED(ret = src_handle = pspIoOpenFile(src_path.c_str(), PSP_O_RDONLY, 0))) { + if (R_FAILED(ret = srcHandle = pspIoOpenFile(src_path.c_str(), PSP_O_RDONLY, 0))) { Log::Error("pspIoOpenFile(%s) failed: 0x%x\n", src_path.c_str(), ret); scePowerUnlock(0); return ret; @@ -343,113 +353,113 @@ namespace FS { #endif #ifdef FS_DEBUG - u64 size = sceIoLseek(src_handle, 0, PSP_SEEK_END); - sceIoLseek(src_handle, 0, PSP_SEEK_SET); + u64 size = sceIoLseek(srcHandle, 0, PSP_SEEK_END); + sceIoLseek(srcHandle, 0, PSP_SEEK_SET); #else - u64 size = pspIoLseek(src_handle, 0, PSP_SEEK_END); - pspIoLseek(src_handle, 0, PSP_SEEK_SET); + u64 size = pspIoLseek(srcHandle, 0, PSP_SEEK_END); + pspIoLseek(srcHandle, 0, PSP_SEEK_SET); #endif // Make sure we have enough storage to carry out this operation if (Utils::GetFreeStorage() < size) { Log::Error("Not enough storage is available to process this command 0x%x\n", src_path.c_str(), ret); #ifdef FS_DEBUG - sceIoClose(src_handle); + sceIoClose(srcHandle); #else - pspIoCloseFile(src_handle); + pspIoCloseFile(srcHandle); #endif scePowerUnlock(0); return -1; } - if (R_FAILED(ret = dest_handle = sceIoOpen(dest_path.c_str(), PSP_O_WRONLY | PSP_O_CREAT | PSP_O_APPEND, 0777))) { - Log::Error("sceIoOpen(%s) failed: 0x%x\n", dest_path.c_str(), ret); + if (R_FAILED(ret = destHandle = sceIoOpen(destPath.c_str(), PSP_O_WRONLY | PSP_O_CREAT | PSP_O_APPEND, 0777))) { + Log::Error("sceIoOpen(%s) failed: 0x%x\n", destPath.c_str(), ret); #ifdef FS_DEBUG - sceIoClose(src_handle); + sceIoClose(srcHandle); #else - pspIoCloseFile(src_handle); + pspIoCloseFile(srcHandle); #endif scePowerUnlock(0); return ret; } - u32 bytes_read = 0, bytes_written = 0; - const u64 buf_size = 0x10000; + u32 bytesRead = 0, bytesWritten = 0; + const u64 bufSize = 0x10000; u64 offset = 0; - u8 *buf = new u8[buf_size]; + u8 *buf = new u8[bufSize]; std::string filename = std::filesystem::path(src_path.data()).filename(); do { if (Utils::IsCancelButtonPressed()) { delete[] buf; #ifdef FS_DEBUG - sceIoClose(src_handle); - sceIoClose(dest_handle); + sceIoClose(srcHandle); + sceIoClose(destHandle); #else - pspIoCloseFile(src_handle); - pspIoCloseFile(dest_handle); + pspIoCloseFile(srcHandle); + pspIoCloseFile(destHandle); #endif scePowerUnlock(0); return 0; } - std::memset(buf, 0, buf_size); + std::memset(buf, 0, bufSize); #ifdef FS_DEBUG - if (R_FAILED(ret = bytes_read = sceIoRead(src_handle, buf, buf_size))) { + if (R_FAILED(ret = bytesRead = sceIoRead(srcHandle, buf, bufSize))) { Log::Error("sceIoRead(%s) failed: 0x%x\n", src_path.c_str(), ret); #else - if (R_FAILED(ret = bytes_read = pspIoReadFile(src_handle, buf, buf_size))) { + if (R_FAILED(ret = bytesRead = pspIoReadFile(srcHandle, buf, bufSize))) { Log::Error("pspIoReadFile(%s) failed: 0x%x\n", src_path.c_str(), ret); #endif delete[] buf; #ifdef FS_DEBUG - sceIoClose(src_handle); - sceIoClose(dest_handle); + sceIoClose(srcHandle); + sceIoClose(destHandle); #else - pspIoCloseFile(src_handle); - pspIoCloseFile(dest_handle); + pspIoCloseFile(srcHandle); + pspIoCloseFile(destHandle); #endif scePowerUnlock(0); return ret; } #ifdef FS_DEBUG - if (R_FAILED(ret = bytes_written = sceIoWrite(dest_handle, buf, bytes_read))) { - Log::Error("sceIoWrite(%s) failed: 0x%x\n", dest_path.c_str(), ret); + if (R_FAILED(ret = bytesWritten = sceIoWrite(destHandle, buf, bytesRead))) { + Log::Error("sceIoWrite(%s) failed: 0x%x\n", destPath.c_str(), ret); #else - if (R_FAILED(ret = bytes_written = pspIoWriteFile(dest_handle, buf, bytes_read))) { - Log::Error("pspIoWriteFile(%s) failed: 0x%x\n", dest_path.c_str(), ret); + if (R_FAILED(ret = bytesWritten = pspIoWriteFile(destHandle, buf, bytesRead))) { + Log::Error("pspIoWriteFile(%s) failed: 0x%x\n", destPath.c_str(), ret); #endif delete[] buf; #ifdef FS_DEBUG - sceIoClose(src_handle); - sceIoClose(dest_handle); + sceIoClose(srcHandle); + sceIoClose(destHandle); #else - pspIoCloseFile(src_handle); - pspIoCloseFile(dest_handle); + pspIoCloseFile(srcHandle); + pspIoCloseFile(destHandle); #endif scePowerUnlock(0); return ret; } - offset += bytes_read; + offset += bytesRead; GUI::ProgressBar("Copying", filename.c_str(), offset, size); } while(offset < size); delete[] buf; #ifdef FS_DEBUG - sceIoClose(src_handle); - sceIoClose(dest_handle); + sceIoClose(srcHandle); + sceIoClose(destHandle); #else - pspIoCloseFile(src_handle); - pspIoCloseFile(dest_handle); + pspIoCloseFile(srcHandle); + pspIoCloseFile(destHandle); #endif scePowerUnlock(0); return 0; } - static int CopyDir(const std::string &src_path, const std::string &dest_path) { + static int CopyDir(const std::string &src_path, const std::string &destPath) { int ret = 0; SceUID dir; @@ -467,9 +477,9 @@ namespace FS { // This may fail or not, but we don't care -> make the dir if it doesn't exist, otherwise continue. #ifdef FS_DEBUG - sceIoMkdir(dest_path.c_str(), 0777); + sceIoMkdir(destPath.c_str(), 0777); #else - pspIoMakeDir(dest_path.c_str(), 0777); + pspIoMakeDir(destPath.c_str(), 0777); #endif do { @@ -486,7 +496,7 @@ namespace FS { continue; std::string src = FS::BuildPath(src_path, entry.d_name); - std::string dest = FS::BuildPath(dest_path, entry.d_name); + std::string dest = FS::BuildPath(destPath, entry.d_name); if (FIO_S_ISDIR(entry.d_stat.st_mode)) FS::CopyDir(src, dest); // Copy Folder (via recursion) @@ -504,28 +514,29 @@ namespace FS { } static void ClearCopyData(void) { - fs_copy_entry.copy_path.clear(); - fs_copy_entry.copy_filename.clear(); - fs_copy_entry.is_dir = false; + fs_copy_entry.path.clear(); + fs_copy_entry.filename.clear(); + fs_copy_entry.isDir = false; } void Copy(SceIoDirent &entry, const std::string &path) { FS::ClearCopyData(); - fs_copy_entry.copy_path = FS::BuildPath(path, entry.d_name); - fs_copy_entry.copy_filename.append(entry.d_name); + fs_copy_entry.path = FS::BuildPath(path, entry.d_name); + fs_copy_entry.filename.append(entry.d_name); - if (FIO_S_ISDIR(entry.d_stat.st_mode)) - fs_copy_entry.is_dir = true; + if (FIO_S_ISDIR(entry.d_stat.st_mode)) { + fs_copy_entry.isDir = true; + } } int Paste(void) { int ret = 0; - std::string path = FS::BuildPath(cfg.cwd, fs_copy_entry.copy_filename); + std::string path = FS::BuildPath(cfg.cwd, fs_copy_entry.filename); - if (fs_copy_entry.is_dir) // Copy folder recursively - ret = FS::CopyDir(fs_copy_entry.copy_path, path); + if (fs_copy_entry.isDir) // Copy folder recursively + ret = FS::CopyDir(fs_copy_entry.path, path); else // Copy file - ret = FS::CopyFile(fs_copy_entry.copy_path, path); + ret = FS::CopyFile(fs_copy_entry.path, path); FS::ClearCopyData(); return ret; @@ -582,10 +593,10 @@ namespace FS { int Move(void) { int ret = 0; - std::string path = FS::BuildPath(cfg.cwd, fs_copy_entry.copy_filename); + std::string path = FS::BuildPath(cfg.cwd, fs_copy_entry.filename); - if (R_FAILED(ret = sceIoMove(fs_copy_entry.copy_path.c_str(), path.c_str()))) { - Log::Error("sceIoMove(%s, %s) failed: 0x%x\n", fs_copy_entry.copy_filename.c_str(), path.c_str(), ret); + if (R_FAILED(ret = sceIoMove(fs_copy_entry.path.c_str(), path.c_str()))) { + Log::Error("sceIoMove(%s, %s) failed: 0x%x\n", fs_copy_entry.filename.c_str(), path.c_str(), ret); FS::ClearCopyData(); return ret; } @@ -722,14 +733,18 @@ namespace FS { return 0; } - + std::string BuildPath(const std::string &path, const std::string &filename) { - std::string new_path = path; - - if (new_path.back() != '/') - new_path.append("/"); + std::string result; + result.reserve(path.size() + 1 + filename.size()); + + result += path; + + if (!path.empty() && path.back() != '/') { + result += '/'; + } - new_path.append(filename); - return new_path; + result += filename; + return result; } } diff --git a/app/source/ftppsp.cpp b/app/source/ftppsp.cpp index 918e8d26..c4e75426 100644 --- a/app/source/ftppsp.cpp +++ b/app/source/ftppsp.cpp @@ -10,7 +10,6 @@ #include #include #include -#include #include #include diff --git a/app/source/gui.cpp b/app/source/gui.cpp index 91adeb4d..154ec92f 100644 --- a/app/source/gui.cpp +++ b/app/source/gui.cpp @@ -1,5 +1,4 @@ #include -#include #include #include "colours.h" diff --git a/app/source/gui/filebrowser.cpp b/app/source/gui/filebrowser.cpp index 02ae624c..6acd994d 100644 --- a/app/source/gui/filebrowser.cpp +++ b/app/source/gui/filebrowser.cpp @@ -131,7 +131,7 @@ namespace GUI { break; case FileTypeImage: - item.texture = Textures::LoadImage(path.c_str()); + item.texture = Textures::LoadImage(path.c_str(), item.entries[item.selected].d_stat.st_size); if (item.texture) item.state = MENU_STATE_IMAGEVIEWER; break; diff --git a/app/source/gui/game_launcher.cpp b/app/source/gui/game_launcher.cpp index 30635a8e..faba9846 100644 --- a/app/source/gui/game_launcher.cpp +++ b/app/source/gui/game_launcher.cpp @@ -40,8 +40,9 @@ namespace CSO { z.next_in = Z_NULL; z.avail_in = 0; - if (inflateInit2(&z, -15) != Z_OK) + if (inflateInit2(&z, -15) != Z_OK) { return -1; + } z.next_in = reinterpret_cast(i_buff); z.avail_in = i_size; @@ -50,8 +51,9 @@ namespace CSO { inflate(&z, Z_FINISH); size = o_size - z.avail_out; - if (inflateEnd(&z) != Z_OK) + if (inflateEnd(&z) != Z_OK) { return -1; + } return size; } @@ -62,55 +64,67 @@ namespace CSO { char tmp_buf[SECTOR_SIZE * 2] = {0}, tmp_buf_2[SECTOR_SIZE * 2] = {0}; int ret = 0, error = 0; - if (R_FAILED(error = sceIoLseek(fd, 0, PSP_SEEK_SET))) + if (R_FAILED(error = sceIoLseek(fd, 0, PSP_SEEK_SET))) { return error; + } - if (R_FAILED(error = sceIoRead(fd, &ciso, sizeof(ciso)))) + if (R_FAILED(error = sceIoRead(fd, &ciso, sizeof(ciso)))) { return error; + } - if (static_cast((pos + size)) > ciso.total_bytes) + if (static_cast((pos + size)) > ciso.total_bytes) { size = ciso.total_bytes - pos; + } int max_sector = ciso.total_bytes / ciso.block_size - 1; int start_sec = pos / SECTOR_SIZE; int end_sec = (pos + size - 1) / SECTOR_SIZE; int sector_num = start_sec; - if (sector_num > max_sector) + if (sector_num > max_sector) { return -1; + } - if (end_sec > max_sector) + if (end_sec > max_sector) { end_sec = max_sector; + } ret = 0; while(sector_num <= end_sec) { - if (R_FAILED(error = sceIoLseek(fd, sizeof(ciso) + (sector_num * 4), PSP_SEEK_SET))) + if (R_FAILED(error = sceIoLseek(fd, sizeof(ciso) + (sector_num * 4), PSP_SEEK_SET))) { return error; + } - if (R_FAILED(error = sceIoRead(fd, &index, 4))) + if (R_FAILED(error = sceIoRead(fd, &index, 4))) { return error; + } u32 zip_flag = index & 0x80000000; index = (index & 0x7FFFFFFF) << ciso.align; - if (R_FAILED(error = sceIoRead(fd, &index2, 4))) + if (R_FAILED(error = sceIoRead(fd, &index2, 4))) { return error; + } int read_size = ((index2 & 0x7FFFFFFF) << ciso.align) - index; - if (R_FAILED(error = sceIoLseek(fd, index, PSP_SEEK_SET))) + if (R_FAILED(error = sceIoLseek(fd, index, PSP_SEEK_SET))) { return error; + } if (zip_flag != 0) { - if (R_FAILED(error = sceIoRead(fd, tmp_buf, ciso.block_size))) + if (R_FAILED(error = sceIoRead(fd, tmp_buf, ciso.block_size))) { return error; + } } else { - if (R_FAILED(error = sceIoRead(fd, tmp_buf_2, read_size))) + if (R_FAILED(error = sceIoRead(fd, tmp_buf_2, read_size))) { return error; + } - if (R_FAILED(error = CSO::Inflate(tmp_buf, ciso.block_size, tmp_buf_2, read_size))) + if (R_FAILED(error = CSO::Inflate(tmp_buf, ciso.block_size, tmp_buf_2, read_size))) { return error; + } } if ((sector_num > start_sec) && (sector_num < end_sec)) { @@ -121,11 +135,13 @@ namespace CSO { int start_pos = 0; int end_pos = ciso.block_size; - if (sector_num == start_sec) + if (sector_num == start_sec) { start_pos = pos - (start_sec * ciso.block_size); + } - if (sector_num == end_sec) + if (sector_num == end_sec) { end_pos = (pos + size) - (end_sec * ciso.block_size); + } read_size = end_pos - start_pos; std::memcpy(buf, &tmp_buf[start_pos], read_size); @@ -171,10 +187,12 @@ namespace ISO { } int ReadFile(void *buf, const std::string &path, int type, int pos, int size) { - if (type == 0) + if (type == 0) { return ISO::Read(buf, path, pos, size); - else if (type == 1) + } + else if (type == 1) { return CSO::Read(reinterpret_cast(buf), path, pos, size); + } return -1; } @@ -187,8 +205,9 @@ namespace ISO { int now_dir_num = 1; int ret = 0; - if (*name == '/') + if (*name == '/') { name++; + } std::strcpy(work, name); char *ptr = std::strrchr(work, '/'); @@ -210,8 +229,9 @@ namespace ISO { u8 magic[8] = { 0x01, 0x43, 0x44, 0x30, 0x30, 0x31, 0x01, 0x00 }; //Invalid Magic - if (std::memcmp(header, magic, sizeof(header)) != 0) + if (std::memcmp(header, magic, sizeof(header)) != 0) { return -1; + } /////// ISO::ReadFile(&path_table_size, path, type, 0x8084, 4); @@ -219,8 +239,9 @@ namespace ISO { path_table_addr *= SECTOR_SIZE; char *table_buf = new char[path_table_size]; - if (!table_buf) + if (!table_buf) { return -1; + } ret = ISO::ReadFile(table_buf, path, type, path_table_addr, path_table_size); @@ -236,8 +257,9 @@ namespace ISO { while(tbl_ptr < path_table_size) { u8 len_di = static_cast(table_buf[tbl_ptr]); - if (len_di == 0) + if (len_di == 0) { break; + } tbl_ptr += 6; @@ -248,16 +270,18 @@ namespace ISO { befor_dir_num = now_dir_num; ptr = strchr(ptr, '/'); - if (ptr != nullptr) + if (ptr != nullptr) { ptr++; + } else { BINARY2INT(&dir_recode_addr, &table_buf[tbl_ptr - 6]); break; } } } - else + else { tbl_ptr += 2; + } tbl_ptr += (len_di + 1) & ~1; // padding now_dir_num++; @@ -266,15 +290,17 @@ namespace ISO { delete[] table_buf; - if (dir_recode_addr == 0) + if (dir_recode_addr == 0) { return -1; + } dir_recode_addr *= SECTOR_SIZE; int dir_record_size = 0; ret = ISO::ReadFile(&dir_record_size, path, type, dir_recode_addr + 10, 4); char *dir_buf = new char[dir_record_size]; - if (!dir_buf) + if (!dir_buf) { return -1; + } int dir_ptr = 0; ret = -1; @@ -282,8 +308,9 @@ namespace ISO { while(dir_ptr < dir_record_size) { u8 len_dr = static_cast(dir_buf[dir_ptr]); - if (len_dr == 0) + if (len_dr == 0) { dir_ptr++; + } else { if (strncasecmp(&dir_buf[dir_ptr + 33], s_file, dir_buf[dir_ptr + 32]) == 0) { BINARY2INT(pos, &dir_buf[dir_ptr + 2]); @@ -369,11 +396,13 @@ namespace GameLauncher { u32 magic = 0; ISO::Read(&magic, path.c_str(), 0, sizeof(magic)); - if (magic == 0x4F534943) + if (magic == 0x4F534943) { type = 1; + } - if (R_FAILED(ret = ISO::GetInfo(&pos, &size, &size_pos, path, type, file.c_str()))) + if (R_FAILED(ret = ISO::GetInfo(&pos, &size, &size_pos, path, type, file.c_str()))) { return ret; + } *data = new u8[size]; ISO::ReadFile(*data, path.c_str(), type, pos, size); @@ -533,8 +562,9 @@ namespace GameLauncher { new_path.append(path); new_path.append(title); - if (!(FS::DirExists(new_path))) + if (!(FS::DirExists(new_path))) { FS::RecursiveMakeDir(new_path); + } new_path.append(ext); // "/icon0.png" FS::WriteFile(new_path, data, size); @@ -550,23 +580,24 @@ namespace GameLauncher { } EbootMeta meta = { 0 }; - - std::string ext = FS::GetFileExt(path); - + const char *ext = FS::GetFileExt(path.c_str()); // ISO/CSO - if ((!ext.compare(".ISO")) || (!ext.compare(".CSO"))) { - if (R_FAILED(ret = GameLauncher::GetISOMeta(path, &meta))) + if ((strncasecmp(ext, "cso", 3) == 0) || (strncasecmp(ext, "iso", 3) == 0)) { + if (R_FAILED(ret = GameLauncher::GetISOMeta(path, &meta))) { return ret; + } } else { - if (R_FAILED(ret = GameLauncher::GetEbootMeta(path, &meta))) + if (R_FAILED(ret = GameLauncher::GetEbootMeta(path, &meta))) { return ret; + } } g2dTexture *icon0 = nullptr; - if (meta.icon0_data) + if (meta.icon0_data) { icon0 = Textures::LoadImageBufferPNG(meta.icon0_data, meta.icon0_size); + } char install_date[128] = {0}; const char *months[] = { "Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov" }; @@ -602,70 +633,86 @@ namespace GameLauncher { int ctrl = Utils::ReadControls(); - if (ctrl & PSP_CTRL_LEFT) + if (ctrl & PSP_CTRL_LEFT) { selection--; - else if (ctrl & PSP_CTRL_RIGHT) + } + else if (ctrl & PSP_CTRL_RIGHT) { selection++; + } Utils::SetBounds(selection, 0, 4); - if (Utils::IsButtonPressed(PSP_CTRL_ENTER)) + if (Utils::IsButtonPressed(PSP_CTRL_ENTER)) { Utils::LaunchEboot(path.c_str()); + } if (Utils::IsButtonPressed(PSP_CTRL_SQUARE)) { switch(selection) { case MetadataIcon0: - if (meta.icon0_data) + if (meta.icon0_data) { GameLauncher::ExportData("/PSP/PHOTO/", meta.title, "/ICON0.PNG", meta.icon0_data, meta.icon0_size); + } break; case MetadataIcon1: - if (meta.icon1_data) + if (meta.icon1_data) { GameLauncher::ExportData("/PSP/PHOTO/", meta.title, "/ICON1.PMF", meta.icon1_data, meta.icon1_size); + } break; case MetadataPic0: - if (meta.pic0_data) + if (meta.pic0_data) { GameLauncher::ExportData("/PSP/PHOTO/", meta.title, "/PIC0.PNG", meta.pic0_data, meta.pic0_size); + } break; case MetadataPic1: - if (meta.pic1_data) + if (meta.pic1_data) { GameLauncher::ExportData("/PSP/PHOTO/", meta.title, "/PIC1.PNG", meta.pic1_data, meta.pic1_size); + } break; case MetadataSnd0: - if (meta.snd0_data) + if (meta.snd0_data) { GameLauncher::ExportData("/PSP/MUSIC/", meta.title, "/SND0.AT3", meta.snd0_data, meta.snd0_size); + } break; } } - if (Utils::IsButtonPressed(PSP_CTRL_CANCEL)) + if (Utils::IsButtonPressed(PSP_CTRL_CANCEL)) { break; + } } - if (icon0) + if (icon0) { g2dTexFree(&icon0); + } - if (meta.title) + if (meta.title) { delete[] meta.title; + } - if (meta.icon0_data) + if (meta.icon0_data) { delete[] meta.icon0_data; + } - if (meta.icon1_data) + if (meta.icon1_data) { delete[] meta.icon1_data; + } - if (meta.pic0_data) + if (meta.pic0_data) { delete[] meta.pic0_data; + } - if (meta.pic1_data) + if (meta.pic1_data) { delete[] meta.pic1_data; + } - if (meta.snd0_data) + if (meta.snd0_data) { delete[] meta.snd0_data; + } return 0; } diff --git a/app/source/gui/options.cpp b/app/source/gui/options.cpp index 38ba57c6..1a06e30f 100644 --- a/app/source/gui/options.cpp +++ b/app/source/gui/options.cpp @@ -6,39 +6,44 @@ #include "g2d.h" #include "gui.h" #include "kernel_functions.h" +#include "log.h" #include "textures.h" #include "utils.h" static int row = 0, column = 0; -static bool copy = false, move = false, options_more = false; +static bool copy = false, move = false, moreOptions = false; namespace Options { static void ResetSelector(void) { row = 0; column = 0; } + + static void RefreshDirectory(MenuItem &item) { + FS::GetDirList(cfg.cwd, item.entries); + GUI::ResetCheckbox(item); + } static void HandleMultipleCopy(MenuItem &item, int (*func)()) { int ret = 0; std::vector entries; - if (R_FAILED(ret = FS::GetDirList(item.checked_cwd.data(), entries))) + if (R_FAILED(ret = FS::GetDirList(item.checked_cwd.data(), entries))) { return; + } for (u32 i = 0; i < item.checked_copy.size(); i++) { - if (item.checked_copy.at(i)) { + if (item.checked_copy[i]) { FS::Copy(entries[i], item.checked_cwd); + if (R_FAILED((*func)())) { - FS::GetDirList(cfg.cwd, item.entries); - GUI::ResetCheckbox(item); + Options::RefreshDirectory(item); break; } } } - FS::GetDirList(cfg.cwd, item.entries); - GUI::ResetCheckbox(item); - entries.clear(); + Options::RefreshDirectory(item); } static void CreateFolder(MenuItem &item) { @@ -46,8 +51,7 @@ namespace Options { std::string path = FS::BuildPath(cfg.cwd, name); if (R_SUCCEEDED(FS::MakeDir(path.c_str()))) { - FS::GetDirList(cfg.cwd, item.entries); - GUI::ResetCheckbox(item); + Options::RefreshDirectory(item); } } @@ -56,8 +60,7 @@ namespace Options { std::string path = FS::BuildPath(cfg.cwd, name); if (R_SUCCEEDED(FS::CreateFile(path.c_str()))) { - FS::GetDirList(cfg.cwd, item.entries); - GUI::ResetCheckbox(item); + Options::RefreshDirectory(item); } } @@ -73,28 +76,33 @@ namespace Options { #endif FS::GetDirList(cfg.cwd, item.entries); Options::ResetSelector(); - options_more = false; + moreOptions = false; item.state = MENU_STATE_FILEBROWSER; } } static void Copy(MenuItem &item) { if (!copy) { - if ((item.checked_count >= 1) && (item.checked_cwd.compare(cfg.cwd) != 0)) + if ((item.checked_count >= 1) && (item.checked_cwd.compare(cfg.cwd) != 0)) { GUI::ResetCheckbox(item); - if (item.checked_count <= 1) + } + if (item.checked_count <= 1) { FS::Copy(item.entries[item.selected], cfg.cwd); + } copy = !copy; item.state = MENU_STATE_FILEBROWSER; } else { - if ((item.checked_count > 1) && (item.checked_cwd.compare(cfg.cwd) != 0)) + Log::Error("In !copy\n"); + if ((item.checked_count > 1) && (item.checked_cwd.compare(cfg.cwd) != 0)) { + Log::Error("In !copy IF\n"); Options::HandleMultipleCopy(item, &FS::Paste); + } else { + Log::Error("In !copy ELSE\n"); if (R_SUCCEEDED(FS::Paste())) { - FS::GetDirList(cfg.cwd, item.entries); - GUI::ResetCheckbox(item); + Options::RefreshDirectory(item); } } @@ -106,18 +114,20 @@ namespace Options { static void Move(MenuItem &item) { if (!move) { - if ((item.checked_count >= 1) && (item.checked_cwd.compare(cfg.cwd) != 0)) + if ((item.checked_count >= 1) && (item.checked_cwd.compare(cfg.cwd) != 0)) { GUI::ResetCheckbox(item); + } - if (item.checked_count <= 1) + if (item.checked_count <= 1) { FS::Copy(item.entries[item.selected], cfg.cwd); + } } else { - if ((item.checked_count > 1) && (item.checked_cwd.compare(cfg.cwd) != 0)) + if ((item.checked_count > 1) && (item.checked_cwd.compare(cfg.cwd) != 0)) { Options::HandleMultipleCopy(item, &FS::Move); + } else if (R_SUCCEEDED(FS::Move())) { - FS::GetDirList(cfg.cwd, item.entries); - GUI::ResetCheckbox(item); + Options::RefreshDirectory(item); } } @@ -128,34 +138,44 @@ namespace Options { namespace GUI { void DisplayFileOptions(MenuItem &item) { + int cancelWidth = intraFontMeasureText(font, "CANCEL"); + G2D::DrawRect(0, 18, 480, 254, G2D_RGBA(0, 0, 0, cfg.dark_theme? 50 : 80)); G2D::DrawImage(options_dialog[cfg.dark_theme], (480 - options_dialog[0]->w) / 2, (272 - options_dialog[0]->h) / 2); G2D::FontSetStyle(1.f, TITLE_COLOUR, INTRAFONT_ALIGN_LEFT); G2D::DrawText(140, 52, "Actions"); - if (row == 0 && column == 0) + if (row == 0 && column == 0) { G2D::DrawRect(132, 71, 107, 38, SELECTOR_COLOUR); - else if (row == 1 && column == 0) + } + else if (row == 1 && column == 0) { G2D::DrawRect(241, 71, 107, 38, SELECTOR_COLOUR); - else if (row == 0 && column == 1) + } + else if (row == 0 && column == 1) { G2D::DrawRect(132, 110, 107, 38, SELECTOR_COLOUR); - else if (row == 1 && column == 1) + } + else if (row == 1 && column == 1) { G2D::DrawRect(241, 110, 107, 38, SELECTOR_COLOUR); - else if (row == 0 && column == 2 && !options_more) + } + else if (row == 0 && column == 2 && !moreOptions) { G2D::DrawRect(132, 148, 107, 38, SELECTOR_COLOUR); - else if (row == 1 && column == 2 && !options_more) + } + else if (row == 1 && column == 2 && !moreOptions) { G2D::DrawRect(241, 148, 107, 38, SELECTOR_COLOUR); - else if (column == 3 && !options_more) - G2D::DrawRect((340 - intraFontMeasureText(font, "CANCEL")) - 5, (230 - (font->texYSize - 6)) - 5, intraFontMeasureText(font, "CANCEL") + 10, + } + else if (column == 3 && !moreOptions) { + G2D::DrawRect((340 - cancelWidth) - 5, (230 - (font->texYSize - 6)) - 5, cancelWidth + 10, (font->texYSize - 6) + 10, SELECTOR_COLOUR); - else if (column == 2 && options_more) - G2D::DrawRect((340 - intraFontMeasureText(font, "CANCEL")) - 5, (230 - (font->texYSize - 6)) - 5, intraFontMeasureText(font, "CANCEL") + 10, + } + else if (column == 2 && moreOptions) { + G2D::DrawRect((340 - cancelWidth) - 5, (230 - (font->texYSize - 6)) - 5, cancelWidth + 10, (font->texYSize - 6) + 10, SELECTOR_COLOUR); + } - G2D::DrawText(340 - intraFontMeasureText(font, "CANCEL"), 230 - (font->texYSize - 15), "CANCEL"); + G2D::DrawText(340 - cancelWidth, 230 - (font->texYSize - 15), "CANCEL"); G2D::FontSetStyle(1.f, TEXT_COLOUR, INTRAFONT_ALIGN_LEFT); - if (!options_more) { + if (!moreOptions) { G2D::DrawText(143, 95, "Properties"); G2D::DrawText(143, 133, copy? "Paste" : "Copy"); G2D::DrawText(143, 171, "Delete"); @@ -171,84 +191,97 @@ namespace GUI { } void ControlFileOptions(MenuItem &item, int &ctrl) { - if (ctrl & PSP_CTRL_RIGHT) + if (ctrl & PSP_CTRL_RIGHT) { row++; - else if (ctrl & PSP_CTRL_LEFT) + } + else if (ctrl & PSP_CTRL_LEFT) { row--; + } - if (ctrl & PSP_CTRL_DOWN) + if (ctrl & PSP_CTRL_DOWN) { column++; - else if (ctrl & PSP_CTRL_UP) + } + else if (ctrl & PSP_CTRL_UP) { column--; + } - if (!options_more) { + if (!moreOptions) { Utils::SetBounds(row, 0, 1); Utils::SetBounds(column, 0, 3); } else { Utils::SetBounds(column, 0, 2); - if (column == 1) + if (column == 1) { Utils::SetBounds(row, 0, 0); - else + } + else { Utils::SetBounds(row, 0, 1); + } } if (Utils::IsButtonPressed(PSP_CTRL_ENTER)) { - const std::string filename = item.entries[item.selected].d_name; - if (row == 0) { - if (!options_more) { - if (column == 0) + if (!moreOptions) { + if (column == 0) { item.state = MENU_STATE_PROPERTIES; - else if (column == 1) + } + else if (column == 1) { Options::Copy(item); - else if (column == 2) + } + else if (column == 2) { item.state = MENU_STATE_DELETE; + } } else { - if (column == 0) + if (column == 0) { Options::CreateFolder(item); - else if (column == 1) - Options::Rename(item, filename); + } + else if (column == 1) { + Options::Rename(item, item.entries[item.selected].d_name); + } } } else if (row == 1) { - if (!options_more) { + if (!moreOptions) { if (column == 0) { FS::GetDirList(cfg.cwd, item.entries); Options::ResetSelector(); - options_more = false; + moreOptions = false; item.selected = 0; item.state = MENU_STATE_FILEBROWSER; } - else if (column == 1) + else if (column == 1) { Options::Move(item); + } else if (column == 2) { Options::ResetSelector(); - options_more = true; + moreOptions = true; } } else { - if (column == 0) + if (column == 0) { Options::CreateFile(item); + } } } if (column == 3) { copy = false; move = false; Options::ResetSelector(); - options_more = false; + moreOptions = false; item.state = MENU_STATE_FILEBROWSER; } } if (Utils::IsButtonPressed(PSP_CTRL_CANCEL)) { Options::ResetSelector(); - if (!options_more) + if (!moreOptions) { item.state = MENU_STATE_FILEBROWSER; - else - options_more = false; + } + else { + moreOptions = false; + } } } } diff --git a/app/source/kernel_functions.cpp b/app/source/kernel_functions.cpp index b0a11017..d5aa2257 100644 --- a/app/source/kernel_functions.cpp +++ b/app/source/kernel_functions.cpp @@ -1,25 +1,7 @@ -#include - #include "kernel_functions.h" -#include "kubridge.h" -#include "log.h" -#include "systemctrl.h" -#include "utils.h" // audio_driver functions -int pspAudioSetFrequency(int frequency) { - struct KernelCallArg args = { 0 }; - void *func_addr = nullptr; - int ret = 0; - - func_addr = (void *)sctrlHENFindFunction("sceAudio_driver", "sceAudio_driver", 0xA2BEAA6C); - args.arg1 = static_cast(frequency); - - if (R_FAILED(ret = kuKernelCall(func_addr, &args))) - Log::Error("%s: pspAudioSetFrequency returns 0x%08X\n", __func__, args.ret1); - - return args.ret1; -} +int pspAudioSetFrequency(int frequency); // display driver functions int pspDisplayEnable(void); @@ -41,6 +23,3 @@ int pspIoGetstat(const char *file, SceIoStat *stat); int pspIoRename(const char *oldname, const char *newname); int pspIoRemoveFile(const char *file); int pspIoDevctl(const char *dev, unsigned int cmd, void *indata, int inlen, void *outdata, int outlen); - -// module_driver functions -int pspKernelLoadModuleBuffer(SceSize size, void *buf, s32 flag, const SceKernelLMOption *option); diff --git a/app/source/main.cpp b/app/source/main.cpp index d813cd38..94908fcb 100644 --- a/app/source/main.cpp +++ b/app/source/main.cpp @@ -11,6 +11,7 @@ PSP_MODULE_INFO("CMFileManager", 0x800, VERSION_MAJOR, VERSION_MINOR); PSP_MAIN_THREAD_ATTR(THREAD_ATTR_USER | THREAD_ATTR_VFPU); +PSP_HEAP_THRESHOLD_SIZE_KB(1024); PSP_HEAP_SIZE_KB(-2048); bool g_running = true; diff --git a/app/source/screenshot.cpp b/app/source/screenshot.cpp index 3d7d803b..00745489 100644 --- a/app/source/screenshot.cpp +++ b/app/source/screenshot.cpp @@ -1,13 +1,11 @@ #include +#include #include #include -#include -#include #include #include #include "fs.h" -#include "libpng/png.h" #include "utils.h" namespace Screenshot { diff --git a/app/source/textures.cpp b/app/source/textures.cpp index ebf7142d..47b81a88 100644 --- a/app/source/textures.cpp +++ b/app/source/textures.cpp @@ -1,12 +1,12 @@ #include #include #include -#include +#include +#include #include "fs.h" #include "libnsbmp.h" -#include "libnsgif.h" -#include "libpng/png.h" +#include "nsgif.h" #include "log.h" #include "textures.h" #include "utils.h" @@ -59,80 +59,47 @@ g2dTexture *file_icons[NUM_FILE_ICONS], *icon_dir[NUM_THEMES], *icon_check[NUM_T *bg_header, *icon_sd[NUM_THEMES], *icon_secure[NUM_THEMES], *ic_play_btn, *ftp_icon[NUM_THEMES], *sort_icon[NUM_THEMES], \ *dark_theme_icon[NUM_THEMES], *dev_options_icon[NUM_THEMES], *about_icon[NUM_THEMES]; -namespace BMP { - static void *bitmap_create(int width, int height, [[maybe_unused]] unsigned int state) { - /* ensure a stupidly large (>50Megs or so) bitmap is not created */ - if ((static_cast(width) * static_cast(height)) > (MAX_IMAGE_BYTES/BYTES_PER_PIXEL)) +namespace Bitmap { + static void *Create(int width, int height, [[maybe_unused]] unsigned int state) { + if (width > 512 && height > 512) { return nullptr; + } return std::calloc(width * height, BYTES_PER_PIXEL); } - static unsigned char *bitmap_get_buffer(void *bitmap) { - assert(bitmap); - return static_cast(bitmap); - } - - static size_t bitmap_get_bpp([[maybe_unused]] void *bitmap) { - return BYTES_PER_PIXEL; - } - - static void bitmap_destroy(void *bitmap) { - assert(bitmap); - std::free(bitmap); - } -} - -namespace GIF { - static void *bitmap_create(int width, int height) { - /* ensure a stupidly large bitmap is not created */ - if ((static_cast(width) * static_cast(height)) > (MAX_IMAGE_BYTES/BYTES_PER_PIXEL)) + static void *Create(int width, int height) { + if (width > 512 && height > 512) { return nullptr; + } return std::calloc(width * height, BYTES_PER_PIXEL); } - - static void bitmap_set_opaque([[maybe_unused]] void *bitmap, [[maybe_unused]] bool opaque) { - assert(bitmap); - } - - static bool bitmap_test_opaque([[maybe_unused]] void *bitmap) { - assert(bitmap); - return false; - } - static unsigned char *bitmap_get_buffer(void *bitmap) { - assert(bitmap); + static unsigned char *GetBuffer(void *bitmap) { return static_cast(bitmap); } - static void bitmap_destroy(void *bitmap) { - assert(bitmap); + static void Destroy(void *bitmap) { std::free(bitmap); } - - static void bitmap_modified([[maybe_unused]] void *bitmap) { - assert(bitmap); - return; - } } namespace Textures { static g2dTexture *LoadImageBufferBMP(unsigned char *data, int size) { - bmp_bitmap_callback_vt bitmap_callbacks = { - BMP::bitmap_create, - BMP::bitmap_destroy, - BMP::bitmap_get_buffer, - BMP::bitmap_get_bpp + bmp_bitmap_callback_vt callbacks = { + .bitmap_create = Bitmap::Create, + .bitmap_destroy = Bitmap::Destroy, + .bitmap_get_buffer = Bitmap::GetBuffer, }; bmp_result code = BMP_OK; bmp_image bmp; - bmp_create(&bmp, &bitmap_callbacks); + bmp_create(&bmp, &callbacks); code = bmp_analyse(&bmp, size, data); if (code != BMP_OK) { - Log::Error("bmp_analyse failed: %d\n", code); + Log::Error("%s(bmp_analyse) failed: %d\n", __func__, code); bmp_finalise(&bmp); return nullptr; } @@ -140,14 +107,14 @@ namespace Textures { code = bmp_decode(&bmp); if (code != BMP_OK) { if ((code != BMP_INSUFFICIENT_DATA) && (code != BMP_DATA_ERROR)) { - Log::Error("bmp_decode failed: %d\n", code); + Log::Error("%s(bmp_decode) failed: %d\n", __func__, code); bmp_finalise(&bmp); return nullptr; } /* skip if the decoded image would be ridiculously large */ if ((bmp.width * bmp.height) > 200000) { - Log::Error("bmp_decode failed: width*height is over 200000\n"); + Log::Error("%s(bmp_decode) failed: width*height is over 200000\n", __func__); bmp_finalise(&bmp); return nullptr; } @@ -159,123 +126,147 @@ namespace Textures { } static g2dTexture *LoadImageBufferGIF(unsigned char *data, int size) { - gif_bitmap_callback_vt bitmap_callbacks = { - GIF::bitmap_create, - GIF::bitmap_destroy, - GIF::bitmap_get_buffer, - GIF::bitmap_set_opaque, - GIF::bitmap_test_opaque, - GIF::bitmap_modified + const nsgif_bitmap_cb_vt callbacks = { + .create = Bitmap::Create, + .destroy = Bitmap::Destroy, + .get_buffer = Bitmap::GetBuffer, }; - - gif_animation gif; - gif_result code = GIF_OK; - gif_create(&gif, &bitmap_callbacks); - - do { - code = gif_initialise(&gif, size, data); - if (code != GIF_OK && code != GIF_WORKING) { - Log::Error("gif_initialise failed: %d\n", code); - gif_finalise(&gif); - return nullptr; - } - } while (code != GIF_OK); - - code = gif_decode_frame(&gif, 0); - if (code != GIF_OK) { - Log::Error("gif_decode_frame failed: %d\n", code); + + nsgif_t *gif; + nsgif_error err = nsgif_create(&callbacks, NSGIF_BITMAP_FMT_ABGR8888, &gif); + if (err != NSGIF_OK) { + Log::Error("%s(nsgif_create) failed: %d\n", __func__, err); return nullptr; } - - g2dTexture *tex = g2dTexLoad(static_cast(gif.frame_image), gif.width, gif.height, G2D_SWIZZLE); - gif_finalise(&gif); + + err = nsgif_data_scan(gif, size, data); + if (err != NSGIF_OK) { + Log::Error("%s(nsgif_data_scan) failed: %d\n", __func__, err); + nsgif_destroy(gif); + return nullptr; + } + + nsgif_bitmap_t *bitmap; + const nsgif_info_t *info = nsgif_get_info(gif); + err = nsgif_frame_decode(gif, 0, &bitmap); + if (err != NSGIF_OK) { + Log::Error("%s(nsgif_frame_decode) failed: %d\n", __func__, err); + nsgif_destroy(gif); + return nullptr; + } + + g2dTexture *tex = g2dTexLoad(static_cast(bitmap), info->width, info->height, G2D_SWIZZLE); + nsgif_destroy(gif); return tex; } g2dTexture *LoadImageBufferJPEG(unsigned char *data, int size) { - struct jpeg_decompress_struct info; - struct jpeg_error_mgr err; - - info.err = jpeg_std_error(&err); - jpeg_create_decompress(&info); - jpeg_mem_src(&info, data, size); - jpeg_read_header(&info, TRUE); - - info.out_color_space = JCS_EXT_RGBA; - jpeg_start_decompress(&info); - - u8 *buffer = new u8[info.output_width * info.output_height * 4]; - int stride = info.output_width * 4; - - while (info.output_scanline < info.output_height) { - u8 *ptr = &buffer[stride * info.output_scanline]; - jpeg_read_scanlines(&info, &ptr, 1); + tjhandle tj = tjInitDecompress(); + if (!tj) { + Log::Error("%s(tjInitDecompress) failed: %s\n", __func__, tjGetErrorStr()); + return nullptr; } - - jpeg_finish_decompress(&info); - g2dTexture *tex = g2dTexLoad(buffer, info.output_width, info.output_height, G2D_SWIZZLE); - jpeg_destroy_decompress(&info); - delete[] buffer; + + int width = 0, height = 0, jpegSubsamp = 0; + if (tjDecompressHeader2(tj, data, size, &width, &height, &jpegSubsamp) != 0) { + Log::Error("%s(tjDecompressHeader2) failed: %s\n", __func__, tjGetErrorStr()); + tjDestroy(tj); + return nullptr; + } + + if (width > 512 || height > 512) { + Log::Error("%s g2d does not support images greater than 512x512\n", __func__); + tjDestroy(tj); + return nullptr; + } + + int stride = width * 4; + u8 *buffer = static_cast(std::malloc(stride * height)); + if (!buffer) { + Log::Error("%s failed to allocate buffer\n", __func__); + tjDestroy(tj); + return nullptr; + } + + if (tjDecompress2(tj, data, size, buffer, width, stride, height, TJPF_RGBA, TJFLAG_FASTDCT) != 0) { + Log::Error("%s(tjDecompress2) failed: %s\n", __func__, tjGetErrorStr()); + std::free(buffer); + tjDestroy(tj); + return nullptr; + } + + g2dTexture *tex = g2dTexLoad(buffer, width, height, G2D_SWIZZLE); + std::free(buffer); + tjDestroy(tj); return tex; } g2dTexture *LoadImageBufferPNG(unsigned char *data, int size) { g2dTexture *tex = nullptr; png_image image; - std::memset(&image, 0, (sizeof image)); + std::memset(&image, 0, sizeof(png_image)); image.version = PNG_IMAGE_VERSION; - - if (png_image_begin_read_from_memory(&image, data, size) != 0) { - png_bytep buffer; - image.format = PNG_FORMAT_RGBA; - buffer = new png_byte[PNG_IMAGE_SIZE(image)]; - - if (buffer != nullptr && png_image_finish_read(&image, nullptr, buffer, 0, nullptr) != 0) { - tex = g2dTexLoad(buffer, image.width, image.height, G2D_SWIZZLE); - delete[] buffer; - png_image_free(&image); - } - else { - if (buffer == nullptr) { - Log::Error("png_byte buffer: returned nullptr\n"); - png_image_free(&image); - } - else { - Log::Error("png_image_finish_read failed: %s\n", image.message); - delete[] buffer; - } - } + + if (!png_image_begin_read_from_memory(&image, data, size)) { + Log::Error("%s(png_image_begin_read_from_memory) failed: %s\n", __func__, image.message); + return nullptr; } - else - Log::Error("png_image_begin_read_from_memory failed: %s\n", image.message); - + + image.format = PNG_FORMAT_RGBA; + + if (image.width > 512 || image.height > 512) { + Log::Error("%s g2d does not support images greater than 512x512\n", __func__); + png_image_free(&image); + return nullptr; + } + + const png_alloc_size_t imageSize = PNG_IMAGE_SIZE(image); + png_bytep buffer = static_cast(std::malloc(imageSize)); + if (!buffer) { + Log::Error("%s failed to allocate buffer\n", __func__); + png_image_free(&image); + return nullptr; + } + + if (png_image_finish_read(&image, nullptr, buffer, 0, nullptr)) { + tex = g2dTexLoad(buffer, image.width, image.height, G2D_SWIZZLE); + } + else { + Log::Error("%s(png_image_finish_read) failed: %s\n", __func__, image.message); + } + + std::free(buffer); + png_image_free(&image); return tex; } - g2dTexture *LoadImage(const std::string &path) { + g2dTexture *LoadImage(const std::string &path, int size) { int ret = 0; - u64 size = FS::GetFileSize(path); - unsigned char *data = new unsigned char[size]; + unsigned char *data = static_cast(std::malloc(size)); if (R_FAILED(ret = FS::ReadFile(path, data, size))) { - Log::Error("LoadImage FS::ReadFile failed 0x%08x\n", ret); - delete[] data; + Log::Error("%s(FS::ReadFile) failed: 0x%08x\n", __func__, ret); + std::free(data); return nullptr; } g2dTexture *tex = nullptr; - std::string ext = FS::GetFileExt(path); + const char *ext = FS::GetFileExt(path.c_str()); - if (ext == ".BMP") + if (strncasecmp(ext, "bmp", 3) == 0) { tex = Textures::LoadImageBufferBMP(data, size); - else if (ext == ".GIF") + } + else if (strncasecmp(ext, "gif", 3) == 0) { tex = Textures::LoadImageBufferGIF(data, size); - else if ((ext == ".JPEG") || (ext == ".JPG")) + } + else if ((strncasecmp(ext, "jpeg", 4) == 0) || (strncasecmp(ext, "jpg", 3) == 0)) { tex = Textures::LoadImageBufferJPEG(data, size); - else if (ext == ".PNG") + } + else if (strncasecmp(ext, "png", 3) == 0) { tex = Textures::LoadImageBufferPNG(data, size); + } - delete[] data; + std::free(data); return tex; } @@ -391,8 +382,9 @@ namespace Textures { g2dTexFree(&icon_dir[i]); } - for (int i = 0; i < NUM_FILE_ICONS; i++) + for (int i = 0; i < NUM_FILE_ICONS; i++) { g2dTexFree(&file_icons[i]); + } for (int i = 0; i < NUM_BATT_ICONS; i++) { g2dTexFree(&battery_charging[i]); diff --git a/app/source/utils.cpp b/app/source/utils.cpp index 24a161bf..6b2e1ebc 100644 --- a/app/source/utils.cpp +++ b/app/source/utils.cpp @@ -21,9 +21,6 @@ enum PspCtrlButtons PSP_CTRL_ENTER, PSP_CTRL_CANCEL; BROWSE_STATE device = BROWSE_STATE_EXTERNAL; int g_psp_language = PSP_SYSTEMPARAM_LANGUAGE_ENGLISH; -extern unsigned char display_driver_prx_start[], fs_driver_prx_start[], module_driver_prx_start[]; -extern unsigned int display_driver_prx_size, fs_driver_prx_size, module_driver_prx_size; - namespace Utils { constexpr unsigned int CTRL_DEADZONE_DELAY = 500000; constexpr unsigned int CTRL_DELAY = 100000; @@ -33,18 +30,16 @@ namespace Utils { static int last_button_tick = 0, deadzone_tick = 0; static bool usb_module_loaded = false; static bool usb_actived = false; - static SceUID module_driver_id = 0; typedef struct { const char *path = nullptr; int id = 0; - unsigned char *data = nullptr; - unsigned int size = 0; } Module; static std::vector kernel_modules { - { "display_driver.prx", -1, display_driver_prx_start, display_driver_prx_size }, - { "fs_driver.prx", -1, fs_driver_prx_start, fs_driver_prx_size } + { "audio_driver.prx", -1, }, + { "display_driver.prx", -1, }, + { "fs_driver.prx", -1, } }; static std::vector usb_modules { @@ -115,48 +110,6 @@ namespace Utils { return ret; } - // Basically removes and re-creates prx from memory -> then remove it after inital load - static int LoadStartModuleMemInitial(const char *path, const void *buf, SceSize size) { - int ret = 0; - SceUID modID = 0; - - // Don't care if this passes or fails - sceIoRemove(path); - SceUID file = sceIoOpen(path, PSP_O_WRONLY | PSP_O_CREAT, 0777); - sceIoWrite(file, buf, size); - sceIoClose(file); - - if (R_FAILED(ret = modID = kuKernelLoadModule(path, 0, nullptr))) { - Log::Error("kuKernelLoadModule(%s) failed: 0x%08x\n", path, ret); - return ret; - } - - if (R_FAILED(ret = sceKernelStartModule(modID, 0, nullptr, nullptr, nullptr))) { - Log::Error("sceKernelStartModule(%s) failed: 0x%08x\n", path, ret); - return ret; - } - - sceIoRemove(path); - return 0; - } - - static int LoadStartModuleMem(const char *path, void *buf, SceSize size) { - int ret = 0; - SceUID modID = 0; - - if (R_FAILED(ret = modID = pspKernelLoadModuleBuffer(size, buf, 0, nullptr))) { - Log::Error("kuKernelLoadModule(%s) failed: 0x%08x\n", path, ret); - return ret; - } - - if (R_FAILED(ret = sceKernelStartModule(modID, 0, nullptr, nullptr, nullptr))) { - Log::Error("sceKernelStartModule(%s) failed: 0x%08x\n", path, ret); - return ret; - } - - return 0; - } - static void StopUnloadModules(SceUID modID) { sceKernelStopModule(modID, 0, nullptr, nullptr, nullptr); sceKernelUnloadModule(modID); @@ -262,23 +215,19 @@ namespace Utils { } void InitKernelDrivers(void) { - module_driver_id = LoadStartModuleMemInitial("module_driver.prx", module_driver_prx_start, module_driver_prx_size); - for (unsigned int i = 0; i < kernel_modules.size(); ++i) - kernel_modules[i].id = Utils::LoadStartModuleMem(kernel_modules[i].path, kernel_modules[i].data, kernel_modules[i].size); + kernel_modules[i].id = Utils::LoadStartModule(kernel_modules[i].path); Utils::InitUSB(); } void TermKernelDrivers(void) { - Utils::ExitUSB(); - for (int i = kernel_modules.size() - 1; i >= 0; --i) { Utils::StopUnloadModules(kernel_modules[i].id); kernel_modules[i].id = -1; } - Utils::StopUnloadModules(module_driver_id); + Utils::ExitUSB(); } void UpdateUSB(void) { diff --git a/module_driver/Makefile b/audio_driver/Makefile similarity index 72% rename from module_driver/Makefile rename to audio_driver/Makefile index 3cde7fc0..c7cca222 100644 --- a/module_driver/Makefile +++ b/audio_driver/Makefile @@ -1,5 +1,5 @@ -TARGET = module_driver -OBJS = module_driver.o exports.o ModuleMgrForKernel.o +TARGET = audio_driver +OBJS = audio_driver.o exports.o PRX_EXPORTS = exports.exp @@ -13,11 +13,11 @@ CXXFLAGS = $(CFLAGS) -fno-exceptions -fno-rtti ASFLAGS = $(CFLAGS) LDFLAGS = -nostartfiles +LIBS = -lpspaudio_driver PSPSDK=$(shell psp-config --pspsdk-path) include $(PSPSDK)/lib/build_prx.mak all: psp-build-exports -s $(PRX_EXPORTS) - mv module_driver.S "../app/drivers/" - mv module_driver.prx "../app/data/" + mv audio_driver.S "../app/drivers/" diff --git a/audio_driver/audio_driver.c b/audio_driver/audio_driver.c new file mode 100644 index 00000000..b1444d3b --- /dev/null +++ b/audio_driver/audio_driver.c @@ -0,0 +1,20 @@ +#include +#include + +PSP_MODULE_INFO("audio_driver", PSP_MODULE_KERNEL, 1, 4); +PSP_NO_CREATE_MAIN_THREAD(); + +int pspAudioSetFrequency(int frequency) { + u32 k1 = pspSdkSetK1(0); + int ret = sceAudioSetFrequency(frequency); + pspSdkSetK1(k1); + return ret; +} + +int module_start(SceSize args, void *argp) { + return 0; +} + +int module_stop(void) { + return 0; +} diff --git a/module_driver/exports.exp b/audio_driver/exports.exp similarity index 81% rename from module_driver/exports.exp rename to audio_driver/exports.exp index 04d805a7..b171d258 100644 --- a/module_driver/exports.exp +++ b/audio_driver/exports.exp @@ -9,8 +9,8 @@ PSP_EXPORT_FUNC(module_stop) PSP_EXPORT_VAR(module_info) PSP_EXPORT_END -PSP_EXPORT_START(module_driver, 0, 0x4001) -PSP_EXPORT_FUNC(pspKernelLoadModuleBuffer) +PSP_EXPORT_START(audio_driver, 0, 0x4001) +PSP_EXPORT_FUNC(pspAudioSetFrequency) PSP_EXPORT_END PSP_END_EXPORTS diff --git a/display_driver/Makefile b/display_driver/Makefile index 0de60062..7ebcb32f 100644 --- a/display_driver/Makefile +++ b/display_driver/Makefile @@ -21,4 +21,3 @@ include $(PSPSDK)/lib/build_prx.mak all: psp-build-exports -s $(PRX_EXPORTS) mv display_driver.S "../app/drivers/" - mv display_driver.prx "../app/data/" diff --git a/fs_driver/Makefile b/fs_driver/Makefile index b92f25e0..99aae19c 100644 --- a/fs_driver/Makefile +++ b/fs_driver/Makefile @@ -24,4 +24,3 @@ include $(PSPSDK)/lib/build_prx.mak all: psp-build-exports -s $(PRX_EXPORTS) mv fs_driver.S "../app/drivers/" - mv fs_driver.prx "../app/data/" diff --git a/launcher/Makefile b/launcher/Makefile index 3089b8ce..6393afb1 100644 --- a/launcher/Makefile +++ b/launcher/Makefile @@ -2,8 +2,6 @@ TARGET = CMFileManager OBJS = source/main.o -PSP_LARGE_MEMORY = 1 - VERSION_MAJOR := 4 VERSION_MINOR := 1 VERSION_MICRO := 0 diff --git a/libs/include/FLAC/all.h b/libs/include/FLAC/all.h deleted file mode 100644 index 6ba03c19..00000000 --- a/libs/include/FLAC/all.h +++ /dev/null @@ -1,371 +0,0 @@ -/* libFLAC - Free Lossless Audio Codec library - * Copyright (C) 2000-2009 Josh Coalson - * Copyright (C) 2011-2016 Xiph.Org Foundation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of the Xiph.org Foundation nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FLAC__ALL_H -#define FLAC__ALL_H - -#include "export.h" - -#include "assert.h" -#include "callback.h" -#include "format.h" -#include "metadata.h" -#include "ordinals.h" -#include "stream_decoder.h" -#include "stream_encoder.h" - -/** \mainpage - * - * \section intro Introduction - * - * This is the documentation for the FLAC C and C++ APIs. It is - * highly interconnected; this introduction should give you a top - * level idea of the structure and how to find the information you - * need. As a prerequisite you should have at least a basic - * knowledge of the FLAC format, documented - * here. - * - * \section c_api FLAC C API - * - * The FLAC C API is the interface to libFLAC, a set of structures - * describing the components of FLAC streams, and functions for - * encoding and decoding streams, as well as manipulating FLAC - * metadata in files. The public include files will be installed - * in your include area (for example /usr/include/FLAC/...). - * - * By writing a little code and linking against libFLAC, it is - * relatively easy to add FLAC support to another program. The - * library is licensed under Xiph's BSD license. - * Complete source code of libFLAC as well as the command-line - * encoder and plugins is available and is a useful source of - * examples. - * - * Aside from encoders and decoders, libFLAC provides a powerful - * metadata interface for manipulating metadata in FLAC files. It - * allows the user to add, delete, and modify FLAC metadata blocks - * and it can automatically take advantage of PADDING blocks to avoid - * rewriting the entire FLAC file when changing the size of the - * metadata. - * - * libFLAC usually only requires the standard C library and C math - * library. In particular, threading is not used so there is no - * dependency on a thread library. However, libFLAC does not use - * global variables and should be thread-safe. - * - * libFLAC also supports encoding to and decoding from Ogg FLAC. - * However the metadata editing interfaces currently have limited - * read-only support for Ogg FLAC files. - * - * \section cpp_api FLAC C++ API - * - * The FLAC C++ API is a set of classes that encapsulate the - * structures and functions in libFLAC. They provide slightly more - * functionality with respect to metadata but are otherwise - * equivalent. For the most part, they share the same usage as - * their counterparts in libFLAC, and the FLAC C API documentation - * can be used as a supplement. The public include files - * for the C++ API will be installed in your include area (for - * example /usr/include/FLAC++/...). - * - * libFLAC++ is also licensed under - * Xiph's BSD license. - * - * \section getting_started Getting Started - * - * A good starting point for learning the API is to browse through - * the modules. Modules are logical - * groupings of related functions or classes, which correspond roughly - * to header files or sections of header files. Each module includes a - * detailed description of the general usage of its functions or - * classes. - * - * From there you can go on to look at the documentation of - * individual functions. You can see different views of the individual - * functions through the links in top bar across this page. - * - * If you prefer a more hands-on approach, you can jump right to some - * example code. - * - * \section porting_guide Porting Guide - * - * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink - * has been introduced which gives detailed instructions on how to - * port your code to newer versions of FLAC. - * - * \section embedded_developers Embedded Developers - * - * libFLAC has grown larger over time as more functionality has been - * included, but much of it may be unnecessary for a particular embedded - * implementation. Unused parts may be pruned by some simple editing of - * src/libFLAC/Makefile.am. In general, the decoders, encoders, and - * metadata interface are all independent from each other. - * - * It is easiest to just describe the dependencies: - * - * - All modules depend on the \link flac_format Format \endlink module. - * - The decoders and encoders depend on the bitbuffer. - * - The decoder is independent of the encoder. The encoder uses the - * decoder because of the verify feature, but this can be removed if - * not needed. - * - Parts of the metadata interface require the stream decoder (but not - * the encoder). - * - Ogg support is selectable through the compile time macro - * \c FLAC__HAS_OGG. - * - * For example, if your application only requires the stream decoder, no - * encoder, and no metadata interface, you can remove the stream encoder - * and the metadata interface, which will greatly reduce the size of the - * library. - * - * Also, there are several places in the libFLAC code with comments marked - * with "OPT:" where a \#define can be changed to enable code that might be - * faster on a specific platform. Experimenting with these can yield faster - * binaries. - */ - -/** \defgroup porting Porting Guide for New Versions - * - * This module describes differences in the library interfaces from - * version to version. It assists in the porting of code that uses - * the libraries to newer versions of FLAC. - * - * One simple facility for making porting easier that has been added - * in FLAC 1.1.3 is a set of \#defines in \c export.h of each - * library's includes (e.g. \c include/FLAC/export.h). The - * \#defines mirror the libraries' - * libtool version numbers, - * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT, - * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE. - * These can be used to support multiple versions of an API during the - * transition phase, e.g. - * - * \code - * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7 - * legacy code - * #else - * new code - * #endif - * \endcode - * - * The source will work for multiple versions and the legacy code can - * easily be removed when the transition is complete. - * - * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in - * include/FLAC/export.h), which can be used to determine whether or not - * the library has been compiled with support for Ogg FLAC. This is - * simpler than trying to call an Ogg init function and catching the - * error. - */ - -/** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3 - * \ingroup porting - * - * \brief - * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3. - * - * The main change between the APIs in 1.1.2 and 1.1.3 is that they have - * been simplified. First, libOggFLAC has been merged into libFLAC and - * libOggFLAC++ has been merged into libFLAC++. Second, both the three - * decoding layers and three encoding layers have been merged into a - * single stream decoder and stream encoder. That is, the functionality - * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged - * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and - * FLAC__FileEncoder into FLAC__StreamEncoder. Only the - * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means - * is there is now a single API that can be used to encode or decode - * streams to/from native FLAC or Ogg FLAC and the single API can work - * on both seekable and non-seekable streams. - * - * Instead of creating an encoder or decoder of a certain layer, now the - * client will always create a FLAC__StreamEncoder or - * FLAC__StreamDecoder. The old layers are now differentiated by the - * initialization function. For example, for the decoder, - * FLAC__stream_decoder_init() has been replaced by - * FLAC__stream_decoder_init_stream(). This init function takes - * callbacks for the I/O, and the seeking callbacks are optional. This - * allows the client to use the same object for seekable and - * non-seekable streams. For decoding a FLAC file directly, the client - * can use FLAC__stream_decoder_init_file() and pass just a filename - * and fewer callbacks; most of the other callbacks are supplied - * internally. For situations where fopen()ing by filename is not - * possible (e.g. Unicode filenames on Windows) the client can instead - * open the file itself and supply the FILE* to - * FLAC__stream_decoder_init_FILE(). The init functions now returns a - * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState. - * Since the callbacks and client data are now passed to the init - * function, the FLAC__stream_decoder_set_*_callback() functions and - * FLAC__stream_decoder_set_client_data() are no longer needed. The - * rest of the calls to the decoder are the same as before. - * - * There are counterpart init functions for Ogg FLAC, e.g. - * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls - * and callbacks are the same as for native FLAC. - * - * As an example, in FLAC 1.1.2 a seekable stream decoder would have - * been set up like so: - * - * \code - * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new(); - * if(decoder == NULL) do_something; - * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true); - * [... other settings ...] - * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback); - * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback); - * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback); - * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback); - * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback); - * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback); - * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback); - * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback); - * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data); - * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something; - * \endcode - * - * In FLAC 1.1.3 it is like this: - * - * \code - * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new(); - * if(decoder == NULL) do_something; - * FLAC__stream_decoder_set_md5_checking(decoder, true); - * [... other settings ...] - * if(FLAC__stream_decoder_init_stream( - * decoder, - * my_read_callback, - * my_seek_callback, // or NULL - * my_tell_callback, // or NULL - * my_length_callback, // or NULL - * my_eof_callback, // or NULL - * my_write_callback, - * my_metadata_callback, // or NULL - * my_error_callback, - * my_client_data - * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something; - * \endcode - * - * or you could do; - * - * \code - * [...] - * FILE *file = fopen("somefile.flac","rb"); - * if(file == NULL) do_somthing; - * if(FLAC__stream_decoder_init_FILE( - * decoder, - * file, - * my_write_callback, - * my_metadata_callback, // or NULL - * my_error_callback, - * my_client_data - * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something; - * \endcode - * - * or just: - * - * \code - * [...] - * if(FLAC__stream_decoder_init_file( - * decoder, - * "somefile.flac", - * my_write_callback, - * my_metadata_callback, // or NULL - * my_error_callback, - * my_client_data - * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something; - * \endcode - * - * Another small change to the decoder is in how it handles unparseable - * streams. Before, when the decoder found an unparseable stream - * (reserved for when the decoder encounters a stream from a future - * encoder that it can't parse), it changed the state to - * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead - * drops sync and calls the error callback with a new error code - * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is - * more robust. If your error callback does not discriminate on the the - * error state, your code does not need to be changed. - * - * The encoder now has a new setting: - * FLAC__stream_encoder_set_apodization(). This is for setting the - * method used to window the data before LPC analysis. You only need to - * add a call to this function if the default is not suitable. There - * are also two new convenience functions that may be useful: - * FLAC__metadata_object_cuesheet_calculate_cddb_id() and - * FLAC__metadata_get_cuesheet(). - * - * The \a bytes parameter to FLAC__StreamDecoderReadCallback, - * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback - * is now \c size_t instead of \c uint32_t. - */ - -/** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4 - * \ingroup porting - * - * \brief - * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4. - * - * There were no changes to any of the interfaces from 1.1.3 to 1.1.4. - * There was a slight change in the implementation of - * FLAC__stream_encoder_set_metadata(); the function now makes a copy - * of the \a metadata array of pointers so the client no longer needs - * to maintain it after the call. The objects themselves that are - * pointed to by the array are still not copied though and must be - * maintained until the call to FLAC__stream_encoder_finish(). - */ - -/** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0 - * \ingroup porting - * - * \brief - * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0. - * - * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0. - * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added. - * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added. - * - * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN - * has changed to reflect the conversion of one of the reserved bits - * into active use. It used to be \c 2 and now is \c 1. However the - * FLAC frame header length has not changed, so to skip the proper - * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN + - * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN - */ - -/** \defgroup flac FLAC C API - * - * The FLAC C API is the interface to libFLAC, a set of structures - * describing the components of FLAC streams, and functions for - * encoding and decoding streams, as well as manipulating FLAC - * metadata in files. - * - * You should start with the format components as all other modules - * are dependent on it. - */ - -#endif diff --git a/libs/include/FLAC/assert.h b/libs/include/FLAC/assert.h deleted file mode 100644 index 55b34777..00000000 --- a/libs/include/FLAC/assert.h +++ /dev/null @@ -1,46 +0,0 @@ -/* libFLAC - Free Lossless Audio Codec library - * Copyright (C) 2001-2009 Josh Coalson - * Copyright (C) 2011-2016 Xiph.Org Foundation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of the Xiph.org Foundation nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FLAC__ASSERT_H -#define FLAC__ASSERT_H - -/* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */ -#ifndef NDEBUG -#include -#define FLAC__ASSERT(x) assert(x) -#define FLAC__ASSERT_DECLARATION(x) x -#else -#define FLAC__ASSERT(x) -#define FLAC__ASSERT_DECLARATION(x) -#endif - -#endif diff --git a/libs/include/FLAC/callback.h b/libs/include/FLAC/callback.h deleted file mode 100644 index 38e23002..00000000 --- a/libs/include/FLAC/callback.h +++ /dev/null @@ -1,185 +0,0 @@ -/* libFLAC - Free Lossless Audio Codec library - * Copyright (C) 2004-2009 Josh Coalson - * Copyright (C) 2011-2016 Xiph.Org Foundation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of the Xiph.org Foundation nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FLAC__CALLBACK_H -#define FLAC__CALLBACK_H - -#include "ordinals.h" -#include /* for size_t */ - -/** \file include/FLAC/callback.h - * - * \brief - * This module defines the structures for describing I/O callbacks - * to the other FLAC interfaces. - * - * See the detailed documentation for callbacks in the - * \link flac_callbacks callbacks \endlink module. - */ - -/** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures - * \ingroup flac - * - * \brief - * This module defines the structures for describing I/O callbacks - * to the other FLAC interfaces. - * - * The purpose of the I/O callback functions is to create a common way - * for the metadata interfaces to handle I/O. - * - * Originally the metadata interfaces required filenames as the way of - * specifying FLAC files to operate on. This is problematic in some - * environments so there is an additional option to specify a set of - * callbacks for doing I/O on the FLAC file, instead of the filename. - * - * In addition to the callbacks, a FLAC__IOHandle type is defined as an - * opaque structure for a data source. - * - * The callback function prototypes are similar (but not identical) to the - * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use - * stdio streams to implement the callbacks, you can pass fread, fwrite, and - * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or - * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle - * is required. \warning You generally CANNOT directly use fseek or ftell - * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems - * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with - * large files. You will have to find an equivalent function (e.g. ftello), - * or write a wrapper. The same is true for feof() since this is usually - * implemented as a macro, not as a function whose address can be taken. - * - * \{ - */ - -#ifdef __cplusplus -extern "C" { -#endif - -/** This is the opaque handle type used by the callbacks. Typically - * this is a \c FILE* or address of a file descriptor. - */ -typedef void* FLAC__IOHandle; - -/** Signature for the read callback. - * The signature and semantics match POSIX fread() implementations - * and can generally be used interchangeably. - * - * \param ptr The address of the read buffer. - * \param size The size of the records to be read. - * \param nmemb The number of records to be read. - * \param handle The handle to the data source. - * \retval size_t - * The number of records read. - */ -typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle); - -/** Signature for the write callback. - * The signature and semantics match POSIX fwrite() implementations - * and can generally be used interchangeably. - * - * \param ptr The address of the write buffer. - * \param size The size of the records to be written. - * \param nmemb The number of records to be written. - * \param handle The handle to the data source. - * \retval size_t - * The number of records written. - */ -typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle); - -/** Signature for the seek callback. - * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT - * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long' - * and 32-bits wide. - * - * \param handle The handle to the data source. - * \param offset The new position, relative to \a whence - * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END - * \retval int - * \c 0 on success, \c -1 on error. - */ -typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence); - -/** Signature for the tell callback. - * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT - * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long' - * and 32-bits wide. - * - * \param handle The handle to the data source. - * \retval FLAC__int64 - * The current position on success, \c -1 on error. - */ -typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle); - -/** Signature for the EOF callback. - * The signature and semantics mostly match POSIX feof() but WATCHOUT: - * on many systems, feof() is a macro, so in this case a wrapper function - * must be provided instead. - * - * \param handle The handle to the data source. - * \retval int - * \c 0 if not at end of file, nonzero if at end of file. - */ -typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle); - -/** Signature for the close callback. - * The signature and semantics match POSIX fclose() implementations - * and can generally be used interchangeably. - * - * \param handle The handle to the data source. - * \retval int - * \c 0 on success, \c EOF on error. - */ -typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle); - -/** A structure for holding a set of callbacks. - * Each FLAC interface that requires a FLAC__IOCallbacks structure will - * describe which of the callbacks are required. The ones that are not - * required may be set to NULL. - * - * If the seek requirement for an interface is optional, you can signify that - * a data source is not seekable by setting the \a seek field to \c NULL. - */ -typedef struct { - FLAC__IOCallback_Read read; - FLAC__IOCallback_Write write; - FLAC__IOCallback_Seek seek; - FLAC__IOCallback_Tell tell; - FLAC__IOCallback_Eof eof; - FLAC__IOCallback_Close close; -} FLAC__IOCallbacks; - -/* \} */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libs/include/FLAC/export.h b/libs/include/FLAC/export.h deleted file mode 100644 index 3e3e7648..00000000 --- a/libs/include/FLAC/export.h +++ /dev/null @@ -1,97 +0,0 @@ -/* libFLAC - Free Lossless Audio Codec library - * Copyright (C) 2000-2009 Josh Coalson - * Copyright (C) 2011-2016 Xiph.Org Foundation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of the Xiph.org Foundation nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FLAC__EXPORT_H -#define FLAC__EXPORT_H - -/** \file include/FLAC/export.h - * - * \brief - * This module contains \#defines and symbols for exporting function - * calls, and providing version information and compiled-in features. - * - * See the \link flac_export export \endlink module. - */ - -/** \defgroup flac_export FLAC/export.h: export symbols - * \ingroup flac - * - * \brief - * This module contains \#defines and symbols for exporting function - * calls, and providing version information and compiled-in features. - * - * If you are compiling with MSVC and will link to the static library - * (libFLAC.lib) you should define FLAC__NO_DLL in your project to - * make sure the symbols are exported properly. - * - * \{ - */ - -#if defined(FLAC__NO_DLL) -#define FLAC_API - -#elif defined(_WIN32) -#ifdef FLAC_API_EXPORTS -#define FLAC_API __declspec(dllexport) -#else -#define FLAC_API __declspec(dllimport) -#endif - -#elif defined(FLAC__USE_VISIBILITY_ATTR) -#define FLAC_API __attribute__ ((visibility ("default"))) - -#else -#define FLAC_API - -#endif - -/** These \#defines will mirror the libtool-based library version number, see - * http://www.gnu.org/software/libtool/manual/libtool.html#Libtool-versioning - */ -#define FLAC_API_VERSION_CURRENT 11 -#define FLAC_API_VERSION_REVISION 0 /**< see above */ -#define FLAC_API_VERSION_AGE 3 /**< see above */ - -#ifdef __cplusplus -extern "C" { -#endif - -/** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */ -extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC; - -#ifdef __cplusplus -} -#endif - -/* \} */ - -#endif diff --git a/libs/include/FLAC/format.h b/libs/include/FLAC/format.h deleted file mode 100644 index 769ab8af..00000000 --- a/libs/include/FLAC/format.h +++ /dev/null @@ -1,1025 +0,0 @@ -/* libFLAC - Free Lossless Audio Codec library - * Copyright (C) 2000-2009 Josh Coalson - * Copyright (C) 2011-2016 Xiph.Org Foundation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of the Xiph.org Foundation nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FLAC__FORMAT_H -#define FLAC__FORMAT_H - -#include "export.h" -#include "ordinals.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** \file include/FLAC/format.h - * - * \brief - * This module contains structure definitions for the representation - * of FLAC format components in memory. These are the basic - * structures used by the rest of the interfaces. - * - * See the detailed documentation in the - * \link flac_format format \endlink module. - */ - -/** \defgroup flac_format FLAC/format.h: format components - * \ingroup flac - * - * \brief - * This module contains structure definitions for the representation - * of FLAC format components in memory. These are the basic - * structures used by the rest of the interfaces. - * - * First, you should be familiar with the - * FLAC format. Many of the values here - * follow directly from the specification. As a user of libFLAC, the - * interesting parts really are the structures that describe the frame - * header and metadata blocks. - * - * The format structures here are very primitive, designed to store - * information in an efficient way. Reading information from the - * structures is easy but creating or modifying them directly is - * more complex. For the most part, as a user of a library, editing - * is not necessary; however, for metadata blocks it is, so there are - * convenience functions provided in the \link flac_metadata metadata - * module \endlink to simplify the manipulation of metadata blocks. - * - * \note - * It's not the best convention, but symbols ending in _LEN are in bits - * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of - * global variables because they are usually used when declaring byte - * arrays and some compilers require compile-time knowledge of array - * sizes when declared on the stack. - * - * \{ - */ - - -/* - Most of the values described in this file are defined by the FLAC - format specification. There is nothing to tune here. -*/ - -/** The largest legal metadata type code. */ -#define FLAC__MAX_METADATA_TYPE_CODE (126u) - -/** The minimum block size, in samples, permitted by the format. */ -#define FLAC__MIN_BLOCK_SIZE (16u) - -/** The maximum block size, in samples, permitted by the format. */ -#define FLAC__MAX_BLOCK_SIZE (65535u) - -/** The maximum block size, in samples, permitted by the FLAC subset for - * sample rates up to 48kHz. */ -#define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u) - -/** The maximum number of channels permitted by the format. */ -#define FLAC__MAX_CHANNELS (8u) - -/** The minimum sample resolution permitted by the format. */ -#define FLAC__MIN_BITS_PER_SAMPLE (4u) - -/** The maximum sample resolution permitted by the format. */ -#define FLAC__MAX_BITS_PER_SAMPLE (32u) - -/** The maximum sample resolution permitted by libFLAC. - * - * \warning - * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However, - * the reference encoder/decoder is currently limited to 24 bits because - * of prevalent 32-bit math, so make sure and use this value when - * appropriate. - */ -#define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u) - -/** The maximum sample rate permitted by the format. The value is - * ((2 ^ 16) - 1) * 10; see FLAC format - * as to why. - */ -#define FLAC__MAX_SAMPLE_RATE (655350u) - -/** The maximum LPC order permitted by the format. */ -#define FLAC__MAX_LPC_ORDER (32u) - -/** The maximum LPC order permitted by the FLAC subset for sample rates - * up to 48kHz. */ -#define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u) - -/** The minimum quantized linear predictor coefficient precision - * permitted by the format. - */ -#define FLAC__MIN_QLP_COEFF_PRECISION (5u) - -/** The maximum quantized linear predictor coefficient precision - * permitted by the format. - */ -#define FLAC__MAX_QLP_COEFF_PRECISION (15u) - -/** The maximum order of the fixed predictors permitted by the format. */ -#define FLAC__MAX_FIXED_ORDER (4u) - -/** The maximum Rice partition order permitted by the format. */ -#define FLAC__MAX_RICE_PARTITION_ORDER (15u) - -/** The maximum Rice partition order permitted by the FLAC Subset. */ -#define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u) - -/** The version string of the release, stamped onto the libraries and binaries. - * - * \note - * This does not correspond to the shared library version number, which - * is used to determine binary compatibility. - */ -extern FLAC_API const char *FLAC__VERSION_STRING; - -/** The vendor string inserted by the encoder into the VORBIS_COMMENT block. - * This is a NUL-terminated ASCII string; when inserted into the - * VORBIS_COMMENT the trailing null is stripped. - */ -extern FLAC_API const char *FLAC__VENDOR_STRING; - -/** The byte string representation of the beginning of a FLAC stream. */ -extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */ - -/** The 32-bit integer big-endian representation of the beginning of - * a FLAC stream. - */ -extern FLAC_API const uint32_t FLAC__STREAM_SYNC; /* = 0x664C6143 */ - -/** The length of the FLAC signature in bits. */ -extern FLAC_API const uint32_t FLAC__STREAM_SYNC_LEN; /* = 32 bits */ - -/** The length of the FLAC signature in bytes. */ -#define FLAC__STREAM_SYNC_LENGTH (4u) - - -/***************************************************************************** - * - * Subframe structures - * - *****************************************************************************/ - -/*****************************************************************************/ - -/** An enumeration of the available entropy coding methods. */ -typedef enum { - FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0, - /**< Residual is coded by partitioning into contexts, each with it's own - * 4-bit Rice parameter. */ - - FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1 - /**< Residual is coded by partitioning into contexts, each with it's own - * 5-bit Rice parameter. */ -} FLAC__EntropyCodingMethodType; - -/** Maps a FLAC__EntropyCodingMethodType to a C string. - * - * Using a FLAC__EntropyCodingMethodType as the index to this array will - * give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[]; - - -/** Contents of a Rice partitioned residual - */ -typedef struct { - - uint32_t *parameters; - /**< The Rice parameters for each context. */ - - uint32_t *raw_bits; - /**< Widths for escape-coded partitions. Will be non-zero for escaped - * partitions and zero for unescaped partitions. - */ - - uint32_t capacity_by_order; - /**< The capacity of the \a parameters and \a raw_bits arrays - * specified as an order, i.e. the number of array elements - * allocated is 2 ^ \a capacity_by_order. - */ -} FLAC__EntropyCodingMethod_PartitionedRiceContents; - -/** Header for a Rice partitioned residual. (c.f. format specification) - */ -typedef struct { - - uint32_t order; - /**< The partition order, i.e. # of contexts = 2 ^ \a order. */ - - const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents; - /**< The context's Rice parameters and/or raw bits. */ - -} FLAC__EntropyCodingMethod_PartitionedRice; - -extern FLAC_API const uint32_t FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */ -extern FLAC_API const uint32_t FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */ -extern FLAC_API const uint32_t FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */ -extern FLAC_API const uint32_t FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */ - -extern FLAC_API const uint32_t FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER; -/**< == (1<format specification) - */ -typedef struct { - FLAC__EntropyCodingMethodType type; - union { - FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice; - } data; -} FLAC__EntropyCodingMethod; - -extern FLAC_API const uint32_t FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */ - -/*****************************************************************************/ - -/** An enumeration of the available subframe types. */ -typedef enum { - FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */ - FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */ - FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */ - FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */ -} FLAC__SubframeType; - -/** Maps a FLAC__SubframeType to a C string. - * - * Using a FLAC__SubframeType as the index to this array will - * give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__SubframeTypeString[]; - - -/** CONSTANT subframe. (c.f. format specification) - */ -typedef struct { - FLAC__int32 value; /**< The constant signal value. */ -} FLAC__Subframe_Constant; - - -/** VERBATIM subframe. (c.f. format specification) - */ -typedef struct { - const FLAC__int32 *data; /**< A pointer to verbatim signal. */ -} FLAC__Subframe_Verbatim; - - -/** FIXED subframe. (c.f. format specification) - */ -typedef struct { - FLAC__EntropyCodingMethod entropy_coding_method; - /**< The residual coding method. */ - - uint32_t order; - /**< The polynomial order. */ - - FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER]; - /**< Warmup samples to prime the predictor, length == order. */ - - const FLAC__int32 *residual; - /**< The residual signal, length == (blocksize minus order) samples. */ -} FLAC__Subframe_Fixed; - - -/** LPC subframe. (c.f. format specification) - */ -typedef struct { - FLAC__EntropyCodingMethod entropy_coding_method; - /**< The residual coding method. */ - - uint32_t order; - /**< The FIR order. */ - - uint32_t qlp_coeff_precision; - /**< Quantized FIR filter coefficient precision in bits. */ - - int quantization_level; - /**< The qlp coeff shift needed. */ - - FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER]; - /**< FIR filter coefficients. */ - - FLAC__int32 warmup[FLAC__MAX_LPC_ORDER]; - /**< Warmup samples to prime the predictor, length == order. */ - - const FLAC__int32 *residual; - /**< The residual signal, length == (blocksize minus order) samples. */ -} FLAC__Subframe_LPC; - -extern FLAC_API const uint32_t FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */ -extern FLAC_API const uint32_t FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */ - - -/** FLAC subframe structure. (c.f. format specification) - */ -typedef struct { - FLAC__SubframeType type; - union { - FLAC__Subframe_Constant constant; - FLAC__Subframe_Fixed fixed; - FLAC__Subframe_LPC lpc; - FLAC__Subframe_Verbatim verbatim; - } data; - uint32_t wasted_bits; -} FLAC__Subframe; - -/** == 1 (bit) - * - * This used to be a zero-padding bit (hence the name - * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a - * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1 - * to mean something else. - */ -extern FLAC_API const uint32_t FLAC__SUBFRAME_ZERO_PAD_LEN; -extern FLAC_API const uint32_t FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */ -extern FLAC_API const uint32_t FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */ - -extern FLAC_API const uint32_t FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */ -extern FLAC_API const uint32_t FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */ -extern FLAC_API const uint32_t FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */ -extern FLAC_API const uint32_t FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */ - -/*****************************************************************************/ - - -/***************************************************************************** - * - * Frame structures - * - *****************************************************************************/ - -/** An enumeration of the available channel assignments. */ -typedef enum { - FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */ - FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */ - FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */ - FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */ -} FLAC__ChannelAssignment; - -/** Maps a FLAC__ChannelAssignment to a C string. - * - * Using a FLAC__ChannelAssignment as the index to this array will - * give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__ChannelAssignmentString[]; - -/** An enumeration of the possible frame numbering methods. */ -typedef enum { - FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */ - FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */ -} FLAC__FrameNumberType; - -/** Maps a FLAC__FrameNumberType to a C string. - * - * Using a FLAC__FrameNumberType as the index to this array will - * give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__FrameNumberTypeString[]; - - -/** FLAC frame header structure. (c.f. format specification) - */ -typedef struct { - uint32_t blocksize; - /**< The number of samples per subframe. */ - - uint32_t sample_rate; - /**< The sample rate in Hz. */ - - uint32_t channels; - /**< The number of channels (== number of subframes). */ - - FLAC__ChannelAssignment channel_assignment; - /**< The channel assignment for the frame. */ - - uint32_t bits_per_sample; - /**< The sample resolution. */ - - FLAC__FrameNumberType number_type; - /**< The numbering scheme used for the frame. As a convenience, the - * decoder will always convert a frame number to a sample number because - * the rules are complex. */ - - union { - FLAC__uint32 frame_number; - FLAC__uint64 sample_number; - } number; - /**< The frame number or sample number of first sample in frame; - * use the \a number_type value to determine which to use. */ - - FLAC__uint8 crc; - /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0) - * of the raw frame header bytes, meaning everything before the CRC byte - * including the sync code. - */ -} FLAC__FrameHeader; - -extern FLAC_API const uint32_t FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */ -extern FLAC_API const uint32_t FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */ -extern FLAC_API const uint32_t FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */ -extern FLAC_API const uint32_t FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */ -extern FLAC_API const uint32_t FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */ -extern FLAC_API const uint32_t FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */ -extern FLAC_API const uint32_t FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */ -extern FLAC_API const uint32_t FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */ -extern FLAC_API const uint32_t FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */ -extern FLAC_API const uint32_t FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */ - - -/** FLAC frame footer structure. (c.f. format specification) - */ -typedef struct { - FLAC__uint16 crc; - /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with - * 0) of the bytes before the crc, back to and including the frame header - * sync code. - */ -} FLAC__FrameFooter; - -extern FLAC_API const uint32_t FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */ - - -/** FLAC frame structure. (c.f. format specification) - */ -typedef struct { - FLAC__FrameHeader header; - FLAC__Subframe subframes[FLAC__MAX_CHANNELS]; - FLAC__FrameFooter footer; -} FLAC__Frame; - -/*****************************************************************************/ - - -/***************************************************************************** - * - * Meta-data structures - * - *****************************************************************************/ - -/** An enumeration of the available metadata block types. */ -typedef enum { - - FLAC__METADATA_TYPE_STREAMINFO = 0, - /**< STREAMINFO block */ - - FLAC__METADATA_TYPE_PADDING = 1, - /**< PADDING block */ - - FLAC__METADATA_TYPE_APPLICATION = 2, - /**< APPLICATION block */ - - FLAC__METADATA_TYPE_SEEKTABLE = 3, - /**< SEEKTABLE block */ - - FLAC__METADATA_TYPE_VORBIS_COMMENT = 4, - /**< VORBISCOMMENT block (a.k.a. FLAC tags) */ - - FLAC__METADATA_TYPE_CUESHEET = 5, - /**< CUESHEET block */ - - FLAC__METADATA_TYPE_PICTURE = 6, - /**< PICTURE block */ - - FLAC__METADATA_TYPE_UNDEFINED = 7, - /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */ - - FLAC__MAX_METADATA_TYPE = FLAC__MAX_METADATA_TYPE_CODE, - /**< No type will ever be greater than this. There is not enough room in the protocol block. */ -} FLAC__MetadataType; - -/** Maps a FLAC__MetadataType to a C string. - * - * Using a FLAC__MetadataType as the index to this array will - * give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__MetadataTypeString[]; - - -/** FLAC STREAMINFO structure. (c.f. format specification) - */ -typedef struct { - uint32_t min_blocksize, max_blocksize; - uint32_t min_framesize, max_framesize; - uint32_t sample_rate; - uint32_t channels; - uint32_t bits_per_sample; - FLAC__uint64 total_samples; - FLAC__byte md5sum[16]; -} FLAC__StreamMetadata_StreamInfo; - -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */ - -/** The total stream length of the STREAMINFO block in bytes. */ -#define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u) - -/** FLAC PADDING structure. (c.f. format specification) - */ -typedef struct { - int dummy; - /**< Conceptually this is an empty struct since we don't store the - * padding bytes. Empty structs are not allowed by some C compilers, - * hence the dummy. - */ -} FLAC__StreamMetadata_Padding; - - -/** FLAC APPLICATION structure. (c.f. format specification) - */ -typedef struct { - FLAC__byte id[4]; - FLAC__byte *data; -} FLAC__StreamMetadata_Application; - -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */ - -/** SeekPoint structure used in SEEKTABLE blocks. (c.f. format specification) - */ -typedef struct { - FLAC__uint64 sample_number; - /**< The sample number of the target frame. */ - - FLAC__uint64 stream_offset; - /**< The offset, in bytes, of the target frame with respect to - * beginning of the first frame. */ - - uint32_t frame_samples; - /**< The number of samples in the target frame. */ -} FLAC__StreamMetadata_SeekPoint; - -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */ - -/** The total stream length of a seek point in bytes. */ -#define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u) - -/** The value used in the \a sample_number field of - * FLAC__StreamMetadataSeekPoint used to indicate a placeholder - * point (== 0xffffffffffffffff). - */ -extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER; - - -/** FLAC SEEKTABLE structure. (c.f. format specification) - * - * \note From the format specification: - * - The seek points must be sorted by ascending sample number. - * - Each seek point's sample number must be the first sample of the - * target frame. - * - Each seek point's sample number must be unique within the table. - * - Existence of a SEEKTABLE block implies a correct setting of - * total_samples in the stream_info block. - * - Behavior is undefined when more than one SEEKTABLE block is - * present in a stream. - */ -typedef struct { - uint32_t num_points; - FLAC__StreamMetadata_SeekPoint *points; -} FLAC__StreamMetadata_SeekTable; - - -/** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. format specification) - * - * For convenience, the APIs maintain a trailing NUL character at the end of - * \a entry which is not counted toward \a length, i.e. - * \code strlen(entry) == length \endcode - */ -typedef struct { - FLAC__uint32 length; - FLAC__byte *entry; -} FLAC__StreamMetadata_VorbisComment_Entry; - -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */ - - -/** FLAC VORBIS_COMMENT structure. (c.f. format specification) - */ -typedef struct { - FLAC__StreamMetadata_VorbisComment_Entry vendor_string; - FLAC__uint32 num_comments; - FLAC__StreamMetadata_VorbisComment_Entry *comments; -} FLAC__StreamMetadata_VorbisComment; - -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */ - - -/** FLAC CUESHEET track index structure. (See the - * format specification for - * the full description of each field.) - */ -typedef struct { - FLAC__uint64 offset; - /**< Offset in samples, relative to the track offset, of the index - * point. - */ - - FLAC__byte number; - /**< The index point number. */ -} FLAC__StreamMetadata_CueSheet_Index; - -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */ - - -/** FLAC CUESHEET track structure. (See the - * format specification for - * the full description of each field.) - */ -typedef struct { - FLAC__uint64 offset; - /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */ - - FLAC__byte number; - /**< The track number. */ - - char isrc[13]; - /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */ - - uint32_t type:1; - /**< The track type: 0 for audio, 1 for non-audio. */ - - uint32_t pre_emphasis:1; - /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */ - - FLAC__byte num_indices; - /**< The number of track index points. */ - - FLAC__StreamMetadata_CueSheet_Index *indices; - /**< NULL if num_indices == 0, else pointer to array of index points. */ - -} FLAC__StreamMetadata_CueSheet_Track; - -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */ - - -/** FLAC CUESHEET structure. (See the - * format specification - * for the full description of each field.) - */ -typedef struct { - char media_catalog_number[129]; - /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In - * general, the media catalog number may be 0 to 128 bytes long; any - * unused characters should be right-padded with NUL characters. - */ - - FLAC__uint64 lead_in; - /**< The number of lead-in samples. */ - - FLAC__bool is_cd; - /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */ - - uint32_t num_tracks; - /**< The number of tracks. */ - - FLAC__StreamMetadata_CueSheet_Track *tracks; - /**< NULL if num_tracks == 0, else pointer to array of tracks. */ - -} FLAC__StreamMetadata_CueSheet; - -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */ - - -/** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */ -typedef enum { - FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */ - FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */ - FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */ - FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */ - FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */ - FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */ - FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */ - FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */ - FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */ - FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */ - FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */ - FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */ - FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */ - FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */ - FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */ - FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */ - FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */ - FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */ - FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */ - FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */ - FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */ - FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED -} FLAC__StreamMetadata_Picture_Type; - -/** Maps a FLAC__StreamMetadata_Picture_Type to a C string. - * - * Using a FLAC__StreamMetadata_Picture_Type as the index to this array - * will give the string equivalent. The contents should not be - * modified. - */ -extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[]; - -/** FLAC PICTURE structure. (See the - * format specification - * for the full description of each field.) - */ -typedef struct { - FLAC__StreamMetadata_Picture_Type type; - /**< The kind of picture stored. */ - - char *mime_type; - /**< Picture data's MIME type, in ASCII printable characters - * 0x20-0x7e, NUL terminated. For best compatibility with players, - * use picture data of MIME type \c image/jpeg or \c image/png. A - * MIME type of '-->' is also allowed, in which case the picture - * data should be a complete URL. In file storage, the MIME type is - * stored as a 32-bit length followed by the ASCII string with no NUL - * terminator, but is converted to a plain C string in this structure - * for convenience. - */ - - FLAC__byte *description; - /**< Picture's description in UTF-8, NUL terminated. In file storage, - * the description is stored as a 32-bit length followed by the UTF-8 - * string with no NUL terminator, but is converted to a plain C string - * in this structure for convenience. - */ - - FLAC__uint32 width; - /**< Picture's width in pixels. */ - - FLAC__uint32 height; - /**< Picture's height in pixels. */ - - FLAC__uint32 depth; - /**< Picture's color depth in bits-per-pixel. */ - - FLAC__uint32 colors; - /**< For indexed palettes (like GIF), picture's number of colors (the - * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth). - */ - - FLAC__uint32 data_length; - /**< Length of binary picture data in bytes. */ - - FLAC__byte *data; - /**< Binary picture data. */ - -} FLAC__StreamMetadata_Picture; - -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */ - - -/** Structure that is used when a metadata block of unknown type is loaded. - * The contents are opaque. The structure is used only internally to - * correctly handle unknown metadata. - */ -typedef struct { - FLAC__byte *data; -} FLAC__StreamMetadata_Unknown; - - -/** FLAC metadata block structure. (c.f. format specification) - */ -typedef struct { - FLAC__MetadataType type; - /**< The type of the metadata block; used determine which member of the - * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED - * then \a data.unknown must be used. */ - - FLAC__bool is_last; - /**< \c true if this metadata block is the last, else \a false */ - - uint32_t length; - /**< Length, in bytes, of the block data as it appears in the stream. */ - - union { - FLAC__StreamMetadata_StreamInfo stream_info; - FLAC__StreamMetadata_Padding padding; - FLAC__StreamMetadata_Application application; - FLAC__StreamMetadata_SeekTable seek_table; - FLAC__StreamMetadata_VorbisComment vorbis_comment; - FLAC__StreamMetadata_CueSheet cue_sheet; - FLAC__StreamMetadata_Picture picture; - FLAC__StreamMetadata_Unknown unknown; - } data; - /**< Polymorphic block data; use the \a type value to determine which - * to use. */ -} FLAC__StreamMetadata; - -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */ -extern FLAC_API const uint32_t FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */ - -/** The total stream length of a metadata block header in bytes. */ -#define FLAC__STREAM_METADATA_HEADER_LENGTH (4u) - -/*****************************************************************************/ - - -/***************************************************************************** - * - * Utility functions - * - *****************************************************************************/ - -/** Tests that a sample rate is valid for FLAC. - * - * \param sample_rate The sample rate to test for compliance. - * \retval FLAC__bool - * \c true if the given sample rate conforms to the specification, else - * \c false. - */ -FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(uint32_t sample_rate); - -/** Tests that a blocksize at the given sample rate is valid for the FLAC - * subset. - * - * \param blocksize The blocksize to test for compliance. - * \param sample_rate The sample rate is needed, since the valid subset - * blocksize depends on the sample rate. - * \retval FLAC__bool - * \c true if the given blocksize conforms to the specification for the - * subset at the given sample rate, else \c false. - */ -FLAC_API FLAC__bool FLAC__format_blocksize_is_subset(uint32_t blocksize, uint32_t sample_rate); - -/** Tests that a sample rate is valid for the FLAC subset. The subset rules - * for valid sample rates are slightly more complex since the rate has to - * be expressible completely in the frame header. - * - * \param sample_rate The sample rate to test for compliance. - * \retval FLAC__bool - * \c true if the given sample rate conforms to the specification for the - * subset, else \c false. - */ -FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(uint32_t sample_rate); - -/** Check a Vorbis comment entry name to see if it conforms to the Vorbis - * comment specification. - * - * Vorbis comment names must be composed only of characters from - * [0x20-0x3C,0x3E-0x7D]. - * - * \param name A NUL-terminated string to be checked. - * \assert - * \code name != NULL \endcode - * \retval FLAC__bool - * \c false if entry name is illegal, else \c true. - */ -FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name); - -/** Check a Vorbis comment entry value to see if it conforms to the Vorbis - * comment specification. - * - * Vorbis comment values must be valid UTF-8 sequences. - * - * \param value A string to be checked. - * \param length A the length of \a value in bytes. May be - * \c (uint32_t)(-1) to indicate that \a value is a plain - * UTF-8 NUL-terminated string. - * \assert - * \code value != NULL \endcode - * \retval FLAC__bool - * \c false if entry name is illegal, else \c true. - */ -FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, uint32_t length); - -/** Check a Vorbis comment entry to see if it conforms to the Vorbis - * comment specification. - * - * Vorbis comment entries must be of the form 'name=value', and 'name' and - * 'value' must be legal according to - * FLAC__format_vorbiscomment_entry_name_is_legal() and - * FLAC__format_vorbiscomment_entry_value_is_legal() respectively. - * - * \param entry An entry to be checked. - * \param length The length of \a entry in bytes. - * \assert - * \code value != NULL \endcode - * \retval FLAC__bool - * \c false if entry name is illegal, else \c true. - */ -FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, uint32_t length); - -/** Check a seek table to see if it conforms to the FLAC specification. - * See the format specification for limits on the contents of the - * seek table. - * - * \param seek_table A pointer to a seek table to be checked. - * \assert - * \code seek_table != NULL \endcode - * \retval FLAC__bool - * \c false if seek table is illegal, else \c true. - */ -FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table); - -/** Sort a seek table's seek points according to the format specification. - * This includes a "unique-ification" step to remove duplicates, i.e. - * seek points with identical \a sample_number values. Duplicate seek - * points are converted into placeholder points and sorted to the end of - * the table. - * - * \param seek_table A pointer to a seek table to be sorted. - * \assert - * \code seek_table != NULL \endcode - * \retval uint32_t - * The number of duplicate seek points converted into placeholders. - */ -FLAC_API uint32_t FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table); - -/** Check a cue sheet to see if it conforms to the FLAC specification. - * See the format specification for limits on the contents of the - * cue sheet. - * - * \param cue_sheet A pointer to an existing cue sheet to be checked. - * \param check_cd_da_subset If \c true, check CUESHEET against more - * stringent requirements for a CD-DA (audio) disc. - * \param violation Address of a pointer to a string. If there is a - * violation, a pointer to a string explanation of the - * violation will be returned here. \a violation may be - * \c NULL if you don't need the returned string. Do not - * free the returned string; it will always point to static - * data. - * \assert - * \code cue_sheet != NULL \endcode - * \retval FLAC__bool - * \c false if cue sheet is illegal, else \c true. - */ -FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation); - -/** Check picture data to see if it conforms to the FLAC specification. - * See the format specification for limits on the contents of the - * PICTURE block. - * - * \param picture A pointer to existing picture data to be checked. - * \param violation Address of a pointer to a string. If there is a - * violation, a pointer to a string explanation of the - * violation will be returned here. \a violation may be - * \c NULL if you don't need the returned string. Do not - * free the returned string; it will always point to static - * data. - * \assert - * \code picture != NULL \endcode - * \retval FLAC__bool - * \c false if picture data is illegal, else \c true. - */ -FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation); - -/* \} */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libs/include/FLAC/metadata.h b/libs/include/FLAC/metadata.h deleted file mode 100644 index 4c67b87f..00000000 --- a/libs/include/FLAC/metadata.h +++ /dev/null @@ -1,2182 +0,0 @@ -/* libFLAC - Free Lossless Audio Codec library - * Copyright (C) 2001-2009 Josh Coalson - * Copyright (C) 2011-2016 Xiph.Org Foundation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of the Xiph.org Foundation nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FLAC__METADATA_H -#define FLAC__METADATA_H - -#include /* for off_t */ -#include "export.h" -#include "callback.h" -#include "format.h" - -/* -------------------------------------------------------------------- - (For an example of how all these routines are used, see the source - code for the unit tests in src/test_libFLAC/metadata_*.c, or - metaflac in src/metaflac/) - ------------------------------------------------------------------*/ - -/** \file include/FLAC/metadata.h - * - * \brief - * This module provides functions for creating and manipulating FLAC - * metadata blocks in memory, and three progressively more powerful - * interfaces for traversing and editing metadata in FLAC files. - * - * See the detailed documentation for each interface in the - * \link flac_metadata metadata \endlink module. - */ - -/** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces - * \ingroup flac - * - * \brief - * This module provides functions for creating and manipulating FLAC - * metadata blocks in memory, and three progressively more powerful - * interfaces for traversing and editing metadata in native FLAC files. - * Note that currently only the Chain interface (level 2) supports Ogg - * FLAC files, and it is read-only i.e. no writing back changed - * metadata to file. - * - * There are three metadata interfaces of increasing complexity: - * - * Level 0: - * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and - * PICTURE blocks. - * - * Level 1: - * Read-write access to all metadata blocks. This level is write- - * efficient in most cases (more on this below), and uses less memory - * than level 2. - * - * Level 2: - * Read-write access to all metadata blocks. This level is write- - * efficient in all cases, but uses more memory since all metadata for - * the whole file is read into memory and manipulated before writing - * out again. - * - * What do we mean by efficient? Since FLAC metadata appears at the - * beginning of the file, when writing metadata back to a FLAC file - * it is possible to grow or shrink the metadata such that the entire - * file must be rewritten. However, if the size remains the same during - * changes or PADDING blocks are utilized, only the metadata needs to be - * overwritten, which is much faster. - * - * Efficient means the whole file is rewritten at most one time, and only - * when necessary. Level 1 is not efficient only in the case that you - * cause more than one metadata block to grow or shrink beyond what can - * be accommodated by padding. In this case you should probably use level - * 2, which allows you to edit all the metadata for a file in memory and - * write it out all at once. - * - * All levels know how to skip over and not disturb an ID3v2 tag at the - * front of the file. - * - * All levels access files via their filenames. In addition, level 2 - * has additional alternative read and write functions that take an I/O - * handle and callbacks, for situations where access by filename is not - * possible. - * - * In addition to the three interfaces, this module defines functions for - * creating and manipulating various metadata objects in memory. As we see - * from the Format module, FLAC metadata blocks in memory are very primitive - * structures for storing information in an efficient way. Reading - * information from the structures is easy but creating or modifying them - * directly is more complex. The metadata object routines here facilitate - * this by taking care of the consistency and memory management drudgery. - * - * Unless you will be using the level 1 or 2 interfaces to modify existing - * metadata however, you will not probably not need these. - * - * From a dependency standpoint, none of the encoders or decoders require - * the metadata module. This is so that embedded users can strip out the - * metadata module from libFLAC to reduce the size and complexity. - */ - -#ifdef __cplusplus -extern "C" { -#endif - - -/** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface - * \ingroup flac_metadata - * - * \brief - * The level 0 interface consists of individual routines to read the - * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring - * only a filename. - * - * They try to skip any ID3v2 tag at the head of the file. - * - * \{ - */ - -/** Read the STREAMINFO metadata block of the given FLAC file. This function - * will try to skip any ID3v2 tag at the head of the file. - * - * \param filename The path to the FLAC file to read. - * \param streaminfo A pointer to space for the STREAMINFO block. Since - * FLAC__StreamMetadata is a simple structure with no - * memory allocation involved, you pass the address of - * an existing structure. It need not be initialized. - * \assert - * \code filename != NULL \endcode - * \code streaminfo != NULL \endcode - * \retval FLAC__bool - * \c true if a valid STREAMINFO block was read from \a filename. Returns - * \c false if there was a memory allocation error, a file decoder error, - * or the file contained no STREAMINFO block. (A memory allocation error - * is possible because this function must set up a file decoder.) - */ -FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo); - -/** Read the VORBIS_COMMENT metadata block of the given FLAC file. This - * function will try to skip any ID3v2 tag at the head of the file. - * - * \param filename The path to the FLAC file to read. - * \param tags The address where the returned pointer will be - * stored. The \a tags object must be deleted by - * the caller using FLAC__metadata_object_delete(). - * \assert - * \code filename != NULL \endcode - * \code tags != NULL \endcode - * \retval FLAC__bool - * \c true if a valid VORBIS_COMMENT block was read from \a filename, - * and \a *tags will be set to the address of the metadata structure. - * Returns \c false if there was a memory allocation error, a file - * decoder error, or the file contained no VORBIS_COMMENT block, and - * \a *tags will be set to \c NULL. - */ -FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags); - -/** Read the CUESHEET metadata block of the given FLAC file. This - * function will try to skip any ID3v2 tag at the head of the file. - * - * \param filename The path to the FLAC file to read. - * \param cuesheet The address where the returned pointer will be - * stored. The \a cuesheet object must be deleted by - * the caller using FLAC__metadata_object_delete(). - * \assert - * \code filename != NULL \endcode - * \code cuesheet != NULL \endcode - * \retval FLAC__bool - * \c true if a valid CUESHEET block was read from \a filename, - * and \a *cuesheet will be set to the address of the metadata - * structure. Returns \c false if there was a memory allocation - * error, a file decoder error, or the file contained no CUESHEET - * block, and \a *cuesheet will be set to \c NULL. - */ -FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet); - -/** Read a PICTURE metadata block of the given FLAC file. This - * function will try to skip any ID3v2 tag at the head of the file. - * Since there can be more than one PICTURE block in a file, this - * function takes a number of parameters that act as constraints to - * the search. The PICTURE block with the largest area matching all - * the constraints will be returned, or \a *picture will be set to - * \c NULL if there was no such block. - * - * \param filename The path to the FLAC file to read. - * \param picture The address where the returned pointer will be - * stored. The \a picture object must be deleted by - * the caller using FLAC__metadata_object_delete(). - * \param type The desired picture type. Use \c -1 to mean - * "any type". - * \param mime_type The desired MIME type, e.g. "image/jpeg". The - * string will be matched exactly. Use \c NULL to - * mean "any MIME type". - * \param description The desired description. The string will be - * matched exactly. Use \c NULL to mean "any - * description". - * \param max_width The maximum width in pixels desired. Use - * \c (uint32_t)(-1) to mean "any width". - * \param max_height The maximum height in pixels desired. Use - * \c (uint32_t)(-1) to mean "any height". - * \param max_depth The maximum color depth in bits-per-pixel desired. - * Use \c (uint32_t)(-1) to mean "any depth". - * \param max_colors The maximum number of colors desired. Use - * \c (uint32_t)(-1) to mean "any number of colors". - * \assert - * \code filename != NULL \endcode - * \code picture != NULL \endcode - * \retval FLAC__bool - * \c true if a valid PICTURE block was read from \a filename, - * and \a *picture will be set to the address of the metadata - * structure. Returns \c false if there was a memory allocation - * error, a file decoder error, or the file contained no PICTURE - * block, and \a *picture will be set to \c NULL. - */ -FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, uint32_t max_width, uint32_t max_height, uint32_t max_depth, uint32_t max_colors); - -/* \} */ - - -/** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface - * \ingroup flac_metadata - * - * \brief - * The level 1 interface provides read-write access to FLAC file metadata and - * operates directly on the FLAC file. - * - * The general usage of this interface is: - * - * - Create an iterator using FLAC__metadata_simple_iterator_new() - * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check - * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to - * see if the file is writable, or only read access is allowed. - * - Use FLAC__metadata_simple_iterator_next() and - * FLAC__metadata_simple_iterator_prev() to traverse the blocks. - * This is does not read the actual blocks themselves. - * FLAC__metadata_simple_iterator_next() is relatively fast. - * FLAC__metadata_simple_iterator_prev() is slower since it needs to search - * forward from the front of the file. - * - Use FLAC__metadata_simple_iterator_get_block_type() or - * FLAC__metadata_simple_iterator_get_block() to access the actual data at - * the current iterator position. The returned object is yours to modify - * and free. - * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block - * back. You must have write permission to the original file. Make sure to - * read the whole comment to FLAC__metadata_simple_iterator_set_block() - * below. - * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks. - * Use the object creation functions from - * \link flac_metadata_object here \endlink to generate new objects. - * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block - * currently referred to by the iterator, or replace it with padding. - * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when - * finished. - * - * \note - * The FLAC file remains open the whole time between - * FLAC__metadata_simple_iterator_init() and - * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering - * the file during this time. - * - * \note - * Do not modify the \a is_last, \a length, or \a type fields of returned - * FLAC__StreamMetadata objects. These are managed automatically. - * - * \note - * If any of the modification functions - * (FLAC__metadata_simple_iterator_set_block(), - * FLAC__metadata_simple_iterator_delete_block(), - * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false, - * you should delete the iterator as it may no longer be valid. - * - * \{ - */ - -struct FLAC__Metadata_SimpleIterator; -/** The opaque structure definition for the level 1 iterator type. - * See the - * \link flac_metadata_level1 metadata level 1 module \endlink - * for a detailed description. - */ -typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator; - -/** Status type for FLAC__Metadata_SimpleIterator. - * - * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status(). - */ -typedef enum { - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0, - /**< The iterator is in the normal OK state */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, - /**< The data passed into a function violated the function's usage criteria */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE, - /**< The iterator could not open the target file */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE, - /**< The iterator could not find the FLAC signature at the start of the file */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE, - /**< The iterator tried to write to a file that was not writable */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA, - /**< The iterator encountered input that does not conform to the FLAC metadata specification */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR, - /**< The iterator encountered an error while reading the FLAC file */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, - /**< The iterator encountered an error while seeking in the FLAC file */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR, - /**< The iterator encountered an error while writing the FLAC file */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR, - /**< The iterator encountered an error renaming the FLAC file */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR, - /**< The iterator encountered an error removing the temporary file */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR, - /**< Memory allocation failed */ - - FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR - /**< The caller violated an assertion or an unexpected error occurred */ - -} FLAC__Metadata_SimpleIteratorStatus; - -/** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string. - * - * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[]; - - -/** Create a new iterator instance. - * - * \retval FLAC__Metadata_SimpleIterator* - * \c NULL if there was an error allocating memory, else the new instance. - */ -FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void); - -/** Free an iterator instance. Deletes the object pointed to by \a iterator. - * - * \param iterator A pointer to an existing iterator. - * \assert - * \code iterator != NULL \endcode - */ -FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator); - -/** Get the current status of the iterator. Call this after a function - * returns \c false to get the reason for the error. Also resets the status - * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK. - * - * \param iterator A pointer to an existing iterator. - * \assert - * \code iterator != NULL \endcode - * \retval FLAC__Metadata_SimpleIteratorStatus - * The current status of the iterator. - */ -FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator); - -/** Initialize the iterator to point to the first metadata block in the - * given FLAC file. - * - * \param iterator A pointer to an existing iterator. - * \param filename The path to the FLAC file. - * \param read_only If \c true, the FLAC file will be opened - * in read-only mode; if \c false, the FLAC - * file will be opened for edit even if no - * edits are performed. - * \param preserve_file_stats If \c true, the owner and modification - * time will be preserved even if the FLAC - * file is written to. - * \assert - * \code iterator != NULL \endcode - * \code filename != NULL \endcode - * \retval FLAC__bool - * \c false if a memory allocation error occurs, the file can't be - * opened, or another error occurs, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats); - -/** Returns \c true if the FLAC file is writable. If \c false, calls to - * FLAC__metadata_simple_iterator_set_block() and - * FLAC__metadata_simple_iterator_insert_block_after() will fail. - * - * \param iterator A pointer to an existing iterator. - * \assert - * \code iterator != NULL \endcode - * \retval FLAC__bool - * See above. - */ -FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator); - -/** Moves the iterator forward one metadata block, returning \c false if - * already at the end. - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \retval FLAC__bool - * \c false if already at the last metadata block of the chain, else - * \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator); - -/** Moves the iterator backward one metadata block, returning \c false if - * already at the beginning. - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \retval FLAC__bool - * \c false if already at the first metadata block of the chain, else - * \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator); - -/** Returns a flag telling if the current metadata block is the last. - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \retval FLAC__bool - * \c true if the current metadata block is the last in the file, - * else \c false. - */ -FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator); - -/** Get the offset of the metadata block at the current position. This - * avoids reading the actual block data which can save time for large - * blocks. - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \retval off_t - * The offset of the metadata block at the current iterator position. - * This is the byte offset relative to the beginning of the file of - * the current metadata block's header. - */ -FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator); - -/** Get the type of the metadata block at the current position. This - * avoids reading the actual block data which can save time for large - * blocks. - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \retval FLAC__MetadataType - * The type of the metadata block at the current iterator position. - */ -FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator); - -/** Get the length of the metadata block at the current position. This - * avoids reading the actual block data which can save time for large - * blocks. - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \retval uint32_t - * The length of the metadata block at the current iterator position. - * The is same length as that in the - * metadata block header, - * i.e. the length of the metadata body that follows the header. - */ -FLAC_API uint32_t FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator); - -/** Get the application ID of the \c APPLICATION block at the current - * position. This avoids reading the actual block data which can save - * time for large blocks. - * - * \param iterator A pointer to an existing initialized iterator. - * \param id A pointer to a buffer of at least \c 4 bytes where - * the ID will be stored. - * \assert - * \code iterator != NULL \endcode - * \code id != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \retval FLAC__bool - * \c true if the ID was successfully read, else \c false, in which - * case you should check FLAC__metadata_simple_iterator_status() to - * find out why. If the status is - * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the - * current metadata block is not an \c APPLICATION block. Otherwise - * if the status is - * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or - * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error - * occurred and the iterator can no longer be used. - */ -FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id); - -/** Get the metadata block at the current position. You can modify the - * block but must use FLAC__metadata_simple_iterator_set_block() to - * write it back to the FLAC file. - * - * You must call FLAC__metadata_object_delete() on the returned object - * when you are finished with it. - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \retval FLAC__StreamMetadata* - * The current metadata block, or \c NULL if there was a memory - * allocation error. - */ -FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator); - -/** Write a block back to the FLAC file. This function tries to be - * as efficient as possible; how the block is actually written is - * shown by the following: - * - * Existing block is a STREAMINFO block and the new block is a - * STREAMINFO block: the new block is written in place. Make sure - * you know what you're doing when changing the values of a - * STREAMINFO block. - * - * Existing block is a STREAMINFO block and the new block is a - * not a STREAMINFO block: this is an error since the first block - * must be a STREAMINFO block. Returns \c false without altering the - * file. - * - * Existing block is not a STREAMINFO block and the new block is a - * STREAMINFO block: this is an error since there may be only one - * STREAMINFO block. Returns \c false without altering the file. - * - * Existing block and new block are the same length: the existing - * block will be replaced by the new block, written in place. - * - * Existing block is longer than new block: if use_padding is \c true, - * the existing block will be overwritten in place with the new - * block followed by a PADDING block, if possible, to make the total - * size the same as the existing block. Remember that a padding - * block requires at least four bytes so if the difference in size - * between the new block and existing block is less than that, the - * entire file will have to be rewritten, using the new block's - * exact size. If use_padding is \c false, the entire file will be - * rewritten, replacing the existing block by the new block. - * - * Existing block is shorter than new block: if use_padding is \c true, - * the function will try and expand the new block into the following - * PADDING block, if it exists and doing so won't shrink the PADDING - * block to less than 4 bytes. If there is no following PADDING - * block, or it will shrink to less than 4 bytes, or use_padding is - * \c false, the entire file is rewritten, replacing the existing block - * with the new block. Note that in this case any following PADDING - * block is preserved as is. - * - * After writing the block, the iterator will remain in the same - * place, i.e. pointing to the new block. - * - * \param iterator A pointer to an existing initialized iterator. - * \param block The block to set. - * \param use_padding See above. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \code block != NULL \endcode - * \retval FLAC__bool - * \c true if successful, else \c false. - */ -FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding); - -/** This is similar to FLAC__metadata_simple_iterator_set_block() - * except that instead of writing over an existing block, it appends - * a block after the existing block. \a use_padding is again used to - * tell the function to try an expand into following padding in an - * attempt to avoid rewriting the entire file. - * - * This function will fail and return \c false if given a STREAMINFO - * block. - * - * After writing the block, the iterator will be pointing to the - * new block. - * - * \param iterator A pointer to an existing initialized iterator. - * \param block The block to set. - * \param use_padding See above. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \code block != NULL \endcode - * \retval FLAC__bool - * \c true if successful, else \c false. - */ -FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding); - -/** Deletes the block at the current position. This will cause the - * entire FLAC file to be rewritten, unless \a use_padding is \c true, - * in which case the block will be replaced by an equal-sized PADDING - * block. The iterator will be left pointing to the block before the - * one just deleted. - * - * You may not delete the STREAMINFO block. - * - * \param iterator A pointer to an existing initialized iterator. - * \param use_padding See above. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_simple_iterator_init() - * \retval FLAC__bool - * \c true if successful, else \c false. - */ -FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding); - -/* \} */ - - -/** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface - * \ingroup flac_metadata - * - * \brief - * The level 2 interface provides read-write access to FLAC file metadata; - * all metadata is read into memory, operated on in memory, and then written - * to file, which is more efficient than level 1 when editing multiple blocks. - * - * Currently Ogg FLAC is supported for read only, via - * FLAC__metadata_chain_read_ogg() but a subsequent - * FLAC__metadata_chain_write() will fail. - * - * The general usage of this interface is: - * - * - Create a new chain using FLAC__metadata_chain_new(). A chain is a - * linked list of FLAC metadata blocks. - * - Read all metadata into the chain from a FLAC file using - * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and - * check the status. - * - Optionally, consolidate the padding using - * FLAC__metadata_chain_merge_padding() or - * FLAC__metadata_chain_sort_padding(). - * - Create a new iterator using FLAC__metadata_iterator_new() - * - Initialize the iterator to point to the first element in the chain - * using FLAC__metadata_iterator_init() - * - Traverse the chain using FLAC__metadata_iterator_next and - * FLAC__metadata_iterator_prev(). - * - Get a block for reading or modification using - * FLAC__metadata_iterator_get_block(). The pointer to the object - * inside the chain is returned, so the block is yours to modify. - * Changes will be reflected in the FLAC file when you write the - * chain. You can also add and delete blocks (see functions below). - * - When done, write out the chain using FLAC__metadata_chain_write(). - * Make sure to read the whole comment to the function below. - * - Delete the chain using FLAC__metadata_chain_delete(). - * - * \note - * Even though the FLAC file is not open while the chain is being - * manipulated, you must not alter the file externally during - * this time. The chain assumes the FLAC file will not change - * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg() - * and FLAC__metadata_chain_write(). - * - * \note - * Do not modify the is_last, length, or type fields of returned - * FLAC__StreamMetadata objects. These are managed automatically. - * - * \note - * The metadata objects returned by FLAC__metadata_iterator_get_block() - * are owned by the chain; do not FLAC__metadata_object_delete() them. - * In the same way, blocks passed to FLAC__metadata_iterator_set_block() - * become owned by the chain and they will be deleted when the chain is - * deleted. - * - * \{ - */ - -struct FLAC__Metadata_Chain; -/** The opaque structure definition for the level 2 chain type. - */ -typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain; - -struct FLAC__Metadata_Iterator; -/** The opaque structure definition for the level 2 iterator type. - */ -typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator; - -typedef enum { - FLAC__METADATA_CHAIN_STATUS_OK = 0, - /**< The chain is in the normal OK state */ - - FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT, - /**< The data passed into a function violated the function's usage criteria */ - - FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE, - /**< The chain could not open the target file */ - - FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE, - /**< The chain could not find the FLAC signature at the start of the file */ - - FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE, - /**< The chain tried to write to a file that was not writable */ - - FLAC__METADATA_CHAIN_STATUS_BAD_METADATA, - /**< The chain encountered input that does not conform to the FLAC metadata specification */ - - FLAC__METADATA_CHAIN_STATUS_READ_ERROR, - /**< The chain encountered an error while reading the FLAC file */ - - FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR, - /**< The chain encountered an error while seeking in the FLAC file */ - - FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR, - /**< The chain encountered an error while writing the FLAC file */ - - FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR, - /**< The chain encountered an error renaming the FLAC file */ - - FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR, - /**< The chain encountered an error removing the temporary file */ - - FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR, - /**< Memory allocation failed */ - - FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR, - /**< The caller violated an assertion or an unexpected error occurred */ - - FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS, - /**< One or more of the required callbacks was NULL */ - - FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH, - /**< FLAC__metadata_chain_write() was called on a chain read by - * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(), - * or - * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile() - * was called on a chain read by - * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(). - * Matching read/write methods must always be used. */ - - FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL - /**< FLAC__metadata_chain_write_with_callbacks() was called when the - * chain write requires a tempfile; use - * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead. - * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was - * called when the chain write does not require a tempfile; use - * FLAC__metadata_chain_write_with_callbacks() instead. - * Always check FLAC__metadata_chain_check_if_tempfile_needed() - * before writing via callbacks. */ - -} FLAC__Metadata_ChainStatus; - -/** Maps a FLAC__Metadata_ChainStatus to a C string. - * - * Using a FLAC__Metadata_ChainStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[]; - -/*********** FLAC__Metadata_Chain ***********/ - -/** Create a new chain instance. - * - * \retval FLAC__Metadata_Chain* - * \c NULL if there was an error allocating memory, else the new instance. - */ -FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void); - -/** Free a chain instance. Deletes the object pointed to by \a chain. - * - * \param chain A pointer to an existing chain. - * \assert - * \code chain != NULL \endcode - */ -FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain); - -/** Get the current status of the chain. Call this after a function - * returns \c false to get the reason for the error. Also resets the - * status to FLAC__METADATA_CHAIN_STATUS_OK. - * - * \param chain A pointer to an existing chain. - * \assert - * \code chain != NULL \endcode - * \retval FLAC__Metadata_ChainStatus - * The current status of the chain. - */ -FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain); - -/** Read all metadata from a FLAC file into the chain. - * - * \param chain A pointer to an existing chain. - * \param filename The path to the FLAC file to read. - * \assert - * \code chain != NULL \endcode - * \code filename != NULL \endcode - * \retval FLAC__bool - * \c true if a valid list of metadata blocks was read from - * \a filename, else \c false. On failure, check the status with - * FLAC__metadata_chain_status(). - */ -FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename); - -/** Read all metadata from an Ogg FLAC file into the chain. - * - * \note Ogg FLAC metadata data writing is not supported yet and - * FLAC__metadata_chain_write() will fail. - * - * \param chain A pointer to an existing chain. - * \param filename The path to the Ogg FLAC file to read. - * \assert - * \code chain != NULL \endcode - * \code filename != NULL \endcode - * \retval FLAC__bool - * \c true if a valid list of metadata blocks was read from - * \a filename, else \c false. On failure, check the status with - * FLAC__metadata_chain_status(). - */ -FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename); - -/** Read all metadata from a FLAC stream into the chain via I/O callbacks. - * - * The \a handle need only be open for reading, but must be seekable. - * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb" - * for Windows). - * - * \param chain A pointer to an existing chain. - * \param handle The I/O handle of the FLAC stream to read. The - * handle will NOT be closed after the metadata is read; - * that is the duty of the caller. - * \param callbacks - * A set of callbacks to use for I/O. The mandatory - * callbacks are \a read, \a seek, and \a tell. - * \assert - * \code chain != NULL \endcode - * \retval FLAC__bool - * \c true if a valid list of metadata blocks was read from - * \a handle, else \c false. On failure, check the status with - * FLAC__metadata_chain_status(). - */ -FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks); - -/** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks. - * - * The \a handle need only be open for reading, but must be seekable. - * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb" - * for Windows). - * - * \note Ogg FLAC metadata data writing is not supported yet and - * FLAC__metadata_chain_write() will fail. - * - * \param chain A pointer to an existing chain. - * \param handle The I/O handle of the Ogg FLAC stream to read. The - * handle will NOT be closed after the metadata is read; - * that is the duty of the caller. - * \param callbacks - * A set of callbacks to use for I/O. The mandatory - * callbacks are \a read, \a seek, and \a tell. - * \assert - * \code chain != NULL \endcode - * \retval FLAC__bool - * \c true if a valid list of metadata blocks was read from - * \a handle, else \c false. On failure, check the status with - * FLAC__metadata_chain_status(). - */ -FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks); - -/** Checks if writing the given chain would require the use of a - * temporary file, or if it could be written in place. - * - * Under certain conditions, padding can be utilized so that writing - * edited metadata back to the FLAC file does not require rewriting the - * entire file. If rewriting is required, then a temporary workfile is - * required. When writing metadata using callbacks, you must check - * this function to know whether to call - * FLAC__metadata_chain_write_with_callbacks() or - * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When - * writing with FLAC__metadata_chain_write(), the temporary file is - * handled internally. - * - * \param chain A pointer to an existing chain. - * \param use_padding - * Whether or not padding will be allowed to be used - * during the write. The value of \a use_padding given - * here must match the value later passed to - * FLAC__metadata_chain_write_with_callbacks() or - * FLAC__metadata_chain_write_with_callbacks_with_tempfile(). - * \assert - * \code chain != NULL \endcode - * \retval FLAC__bool - * \c true if writing the current chain would require a tempfile, or - * \c false if metadata can be written in place. - */ -FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding); - -/** Write all metadata out to the FLAC file. This function tries to be as - * efficient as possible; how the metadata is actually written is shown by - * the following: - * - * If the current chain is the same size as the existing metadata, the new - * data is written in place. - * - * If the current chain is longer than the existing metadata, and - * \a use_padding is \c true, and the last block is a PADDING block of - * sufficient length, the function will truncate the final padding block - * so that the overall size of the metadata is the same as the existing - * metadata, and then just rewrite the metadata. Otherwise, if not all of - * the above conditions are met, the entire FLAC file must be rewritten. - * If you want to use padding this way it is a good idea to call - * FLAC__metadata_chain_sort_padding() first so that you have the maximum - * amount of padding to work with, unless you need to preserve ordering - * of the PADDING blocks for some reason. - * - * If the current chain is shorter than the existing metadata, and - * \a use_padding is \c true, and the final block is a PADDING block, the padding - * is extended to make the overall size the same as the existing data. If - * \a use_padding is \c true and the last block is not a PADDING block, a new - * PADDING block is added to the end of the new data to make it the same - * size as the existing data (if possible, see the note to - * FLAC__metadata_simple_iterator_set_block() about the four byte limit) - * and the new data is written in place. If none of the above apply or - * \a use_padding is \c false, the entire FLAC file is rewritten. - * - * If \a preserve_file_stats is \c true, the owner and modification time will - * be preserved even if the FLAC file is written. - * - * For this write function to be used, the chain must have been read with - * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not - * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(). - * - * \param chain A pointer to an existing chain. - * \param use_padding See above. - * \param preserve_file_stats See above. - * \assert - * \code chain != NULL \endcode - * \retval FLAC__bool - * \c true if the write succeeded, else \c false. On failure, - * check the status with FLAC__metadata_chain_status(). - */ -FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats); - -/** Write all metadata out to a FLAC stream via callbacks. - * - * (See FLAC__metadata_chain_write() for the details on how padding is - * used to write metadata in place if possible.) - * - * The \a handle must be open for updating and be seekable. The - * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b" - * for Windows). - * - * For this write function to be used, the chain must have been read with - * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(), - * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(). - * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned - * \c false. - * - * \param chain A pointer to an existing chain. - * \param use_padding See FLAC__metadata_chain_write() - * \param handle The I/O handle of the FLAC stream to write. The - * handle will NOT be closed after the metadata is - * written; that is the duty of the caller. - * \param callbacks A set of callbacks to use for I/O. The mandatory - * callbacks are \a write and \a seek. - * \assert - * \code chain != NULL \endcode - * \retval FLAC__bool - * \c true if the write succeeded, else \c false. On failure, - * check the status with FLAC__metadata_chain_status(). - */ -FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks); - -/** Write all metadata out to a FLAC stream via callbacks. - * - * (See FLAC__metadata_chain_write() for the details on how padding is - * used to write metadata in place if possible.) - * - * This version of the write-with-callbacks function must be used when - * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In - * this function, you must supply an I/O handle corresponding to the - * FLAC file to edit, and a temporary handle to which the new FLAC - * file will be written. It is the caller's job to move this temporary - * FLAC file on top of the original FLAC file to complete the metadata - * edit. - * - * The \a handle must be open for reading and be seekable. The - * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb" - * for Windows). - * - * The \a temp_handle must be open for writing. The - * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb" - * for Windows). It should be an empty stream, or at least positioned - * at the start-of-file (in which case it is the caller's duty to - * truncate it on return). - * - * For this write function to be used, the chain must have been read with - * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(), - * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(). - * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned - * \c true. - * - * \param chain A pointer to an existing chain. - * \param use_padding See FLAC__metadata_chain_write() - * \param handle The I/O handle of the original FLAC stream to read. - * The handle will NOT be closed after the metadata is - * written; that is the duty of the caller. - * \param callbacks A set of callbacks to use for I/O on \a handle. - * The mandatory callbacks are \a read, \a seek, and - * \a eof. - * \param temp_handle The I/O handle of the FLAC stream to write. The - * handle will NOT be closed after the metadata is - * written; that is the duty of the caller. - * \param temp_callbacks - * A set of callbacks to use for I/O on temp_handle. - * The only mandatory callback is \a write. - * \assert - * \code chain != NULL \endcode - * \retval FLAC__bool - * \c true if the write succeeded, else \c false. On failure, - * check the status with FLAC__metadata_chain_status(). - */ -FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks); - -/** Merge adjacent PADDING blocks into a single block. - * - * \note This function does not write to the FLAC file, it only - * modifies the chain. - * - * \warning Any iterator on the current chain will become invalid after this - * call. You should delete the iterator and get a new one. - * - * \param chain A pointer to an existing chain. - * \assert - * \code chain != NULL \endcode - */ -FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain); - -/** This function will move all PADDING blocks to the end on the metadata, - * then merge them into a single block. - * - * \note This function does not write to the FLAC file, it only - * modifies the chain. - * - * \warning Any iterator on the current chain will become invalid after this - * call. You should delete the iterator and get a new one. - * - * \param chain A pointer to an existing chain. - * \assert - * \code chain != NULL \endcode - */ -FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain); - - -/*********** FLAC__Metadata_Iterator ***********/ - -/** Create a new iterator instance. - * - * \retval FLAC__Metadata_Iterator* - * \c NULL if there was an error allocating memory, else the new instance. - */ -FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void); - -/** Free an iterator instance. Deletes the object pointed to by \a iterator. - * - * \param iterator A pointer to an existing iterator. - * \assert - * \code iterator != NULL \endcode - */ -FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator); - -/** Initialize the iterator to point to the first metadata block in the - * given chain. - * - * \param iterator A pointer to an existing iterator. - * \param chain A pointer to an existing and initialized (read) chain. - * \assert - * \code iterator != NULL \endcode - * \code chain != NULL \endcode - */ -FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain); - -/** Moves the iterator forward one metadata block, returning \c false if - * already at the end. - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_iterator_init() - * \retval FLAC__bool - * \c false if already at the last metadata block of the chain, else - * \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator); - -/** Moves the iterator backward one metadata block, returning \c false if - * already at the beginning. - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_iterator_init() - * \retval FLAC__bool - * \c false if already at the first metadata block of the chain, else - * \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator); - -/** Get the type of the metadata block at the current position. - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_iterator_init() - * \retval FLAC__MetadataType - * The type of the metadata block at the current iterator position. - */ -FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator); - -/** Get the metadata block at the current position. You can modify - * the block in place but must write the chain before the changes - * are reflected to the FLAC file. You do not need to call - * FLAC__metadata_iterator_set_block() to reflect the changes; - * the pointer returned by FLAC__metadata_iterator_get_block() - * points directly into the chain. - * - * \warning - * Do not call FLAC__metadata_object_delete() on the returned object; - * to delete a block use FLAC__metadata_iterator_delete_block(). - * - * \param iterator A pointer to an existing initialized iterator. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_iterator_init() - * \retval FLAC__StreamMetadata* - * The current metadata block. - */ -FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator); - -/** Set the metadata block at the current position, replacing the existing - * block. The new block passed in becomes owned by the chain and it will be - * deleted when the chain is deleted. - * - * \param iterator A pointer to an existing initialized iterator. - * \param block A pointer to a metadata block. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_iterator_init() - * \code block != NULL \endcode - * \retval FLAC__bool - * \c false if the conditions in the above description are not met, or - * a memory allocation error occurs, otherwise \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block); - -/** Removes the current block from the chain. If \a replace_with_padding is - * \c true, the block will instead be replaced with a padding block of equal - * size. You can not delete the STREAMINFO block. The iterator will be - * left pointing to the block before the one just "deleted", even if - * \a replace_with_padding is \c true. - * - * \param iterator A pointer to an existing initialized iterator. - * \param replace_with_padding See above. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_iterator_init() - * \retval FLAC__bool - * \c false if the conditions in the above description are not met, - * otherwise \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding); - -/** Insert a new block before the current block. You cannot insert a block - * before the first STREAMINFO block. You cannot insert a STREAMINFO block - * as there can be only one, the one that already exists at the head when you - * read in a chain. The chain takes ownership of the new block and it will be - * deleted when the chain is deleted. The iterator will be left pointing to - * the new block. - * - * \param iterator A pointer to an existing initialized iterator. - * \param block A pointer to a metadata block to insert. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_iterator_init() - * \retval FLAC__bool - * \c false if the conditions in the above description are not met, or - * a memory allocation error occurs, otherwise \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block); - -/** Insert a new block after the current block. You cannot insert a STREAMINFO - * block as there can be only one, the one that already exists at the head when - * you read in a chain. The chain takes ownership of the new block and it will - * be deleted when the chain is deleted. The iterator will be left pointing to - * the new block. - * - * \param iterator A pointer to an existing initialized iterator. - * \param block A pointer to a metadata block to insert. - * \assert - * \code iterator != NULL \endcode - * \a iterator has been successfully initialized with - * FLAC__metadata_iterator_init() - * \retval FLAC__bool - * \c false if the conditions in the above description are not met, or - * a memory allocation error occurs, otherwise \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block); - -/* \} */ - - -/** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods - * \ingroup flac_metadata - * - * \brief - * This module contains methods for manipulating FLAC metadata objects. - * - * Since many are variable length we have to be careful about the memory - * management. We decree that all pointers to data in the object are - * owned by the object and memory-managed by the object. - * - * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete() - * functions to create all instances. When using the - * FLAC__metadata_object_set_*() functions to set pointers to data, set - * \a copy to \c true to have the function make it's own copy of the data, or - * to \c false to give the object ownership of your data. In the latter case - * your pointer must be freeable by free() and will be free()d when the object - * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as - * the data pointer to a FLAC__metadata_object_set_*() function as long as - * the length argument is 0 and the \a copy argument is \c false. - * - * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function - * will return \c NULL in the case of a memory allocation error, otherwise a new - * object. The FLAC__metadata_object_set_*() functions return \c false in the - * case of a memory allocation error. - * - * We don't have the convenience of C++ here, so note that the library relies - * on you to keep the types straight. In other words, if you pass, for - * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to - * FLAC__metadata_object_application_set_data(), you will get an assertion - * failure. - * - * For convenience the FLAC__metadata_object_vorbiscomment_*() functions - * maintain a trailing NUL on each Vorbis comment entry. This is not counted - * toward the length or stored in the stream, but it can make working with plain - * comments (those that don't contain embedded-NULs in the value) easier. - * Entries passed into these functions have trailing NULs added if missing, and - * returned entries are guaranteed to have a trailing NUL. - * - * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis - * comment entry/name/value will first validate that it complies with the Vorbis - * comment specification and return false if it does not. - * - * There is no need to recalculate the length field on metadata blocks you - * have modified. They will be calculated automatically before they are - * written back to a file. - * - * \{ - */ - - -/** Create a new metadata object instance of the given type. - * - * The object will be "empty"; i.e. values and data pointers will be \c 0, - * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have - * the vendor string set (but zero comments). - * - * Do not pass in a value greater than or equal to - * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're - * doing. - * - * \param type Type of object to create - * \retval FLAC__StreamMetadata* - * \c NULL if there was an error allocating memory or the type code is - * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance. - */ -FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type); - -/** Create a copy of an existing metadata object. - * - * The copy is a "deep" copy, i.e. dynamically allocated data within the - * object is also copied. The caller takes ownership of the new block and - * is responsible for freeing it with FLAC__metadata_object_delete(). - * - * \param object Pointer to object to copy. - * \assert - * \code object != NULL \endcode - * \retval FLAC__StreamMetadata* - * \c NULL if there was an error allocating memory, else the new instance. - */ -FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object); - -/** Free a metadata object. Deletes the object pointed to by \a object. - * - * The delete is a "deep" delete, i.e. dynamically allocated data within the - * object is also deleted. - * - * \param object A pointer to an existing object. - * \assert - * \code object != NULL \endcode - */ -FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object); - -/** Compares two metadata objects. - * - * The compare is "deep", i.e. dynamically allocated data within the - * object is also compared. - * - * \param block1 A pointer to an existing object. - * \param block2 A pointer to an existing object. - * \assert - * \code block1 != NULL \endcode - * \code block2 != NULL \endcode - * \retval FLAC__bool - * \c true if objects are identical, else \c false. - */ -FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2); - -/** Sets the application data of an APPLICATION block. - * - * If \a copy is \c true, a copy of the data is stored; otherwise, the object - * takes ownership of the pointer. The existing data will be freed if this - * function is successful, otherwise the original data will remain if \a copy - * is \c true and malloc() fails. - * - * \note It is safe to pass a const pointer to \a data if \a copy is \c true. - * - * \param object A pointer to an existing APPLICATION object. - * \param data A pointer to the data to set. - * \param length The length of \a data in bytes. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode - * \code (data != NULL && length > 0) || - * (data == NULL && length == 0 && copy == false) \endcode - * \retval FLAC__bool - * \c false if \a copy is \c true and malloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, uint32_t length, FLAC__bool copy); - -/** Resize the seekpoint array. - * - * If the size shrinks, elements will truncated; if it grows, new placeholder - * points will be added to the end. - * - * \param object A pointer to an existing SEEKTABLE object. - * \param new_num_points The desired length of the array; may be \c 0. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) || - * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode - * \retval FLAC__bool - * \c false if memory allocation error, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, uint32_t new_num_points); - -/** Set a seekpoint in a seektable. - * - * \param object A pointer to an existing SEEKTABLE object. - * \param point_num Index into seekpoint array to set. - * \param point The point to set. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \code object->data.seek_table.num_points > point_num \endcode - */ -FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, uint32_t point_num, FLAC__StreamMetadata_SeekPoint point); - -/** Insert a seekpoint into a seektable. - * - * \param object A pointer to an existing SEEKTABLE object. - * \param point_num Index into seekpoint array to set. - * \param point The point to set. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \code object->data.seek_table.num_points >= point_num \endcode - * \retval FLAC__bool - * \c false if memory allocation error, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, uint32_t point_num, FLAC__StreamMetadata_SeekPoint point); - -/** Delete a seekpoint from a seektable. - * - * \param object A pointer to an existing SEEKTABLE object. - * \param point_num Index into seekpoint array to set. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \code object->data.seek_table.num_points > point_num \endcode - * \retval FLAC__bool - * \c false if memory allocation error, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, uint32_t point_num); - -/** Check a seektable to see if it conforms to the FLAC specification. - * See the format specification for limits on the contents of the - * seektable. - * - * \param object A pointer to an existing SEEKTABLE object. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \retval FLAC__bool - * \c false if seek table is illegal, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object); - -/** Append a number of placeholder points to the end of a seek table. - * - * \note - * As with the other ..._seektable_template_... functions, you should - * call FLAC__metadata_object_seektable_template_sort() when finished - * to make the seek table legal. - * - * \param object A pointer to an existing SEEKTABLE object. - * \param num The number of placeholder points to append. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \retval FLAC__bool - * \c false if memory allocation fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, uint32_t num); - -/** Append a specific seek point template to the end of a seek table. - * - * \note - * As with the other ..._seektable_template_... functions, you should - * call FLAC__metadata_object_seektable_template_sort() when finished - * to make the seek table legal. - * - * \param object A pointer to an existing SEEKTABLE object. - * \param sample_number The sample number of the seek point template. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \retval FLAC__bool - * \c false if memory allocation fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number); - -/** Append specific seek point templates to the end of a seek table. - * - * \note - * As with the other ..._seektable_template_... functions, you should - * call FLAC__metadata_object_seektable_template_sort() when finished - * to make the seek table legal. - * - * \param object A pointer to an existing SEEKTABLE object. - * \param sample_numbers An array of sample numbers for the seek points. - * \param num The number of seek point templates to append. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \retval FLAC__bool - * \c false if memory allocation fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], uint32_t num); - -/** Append a set of evenly-spaced seek point templates to the end of a - * seek table. - * - * \note - * As with the other ..._seektable_template_... functions, you should - * call FLAC__metadata_object_seektable_template_sort() when finished - * to make the seek table legal. - * - * \param object A pointer to an existing SEEKTABLE object. - * \param num The number of placeholder points to append. - * \param total_samples The total number of samples to be encoded; - * the seekpoints will be spaced approximately - * \a total_samples / \a num samples apart. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \code total_samples > 0 \endcode - * \retval FLAC__bool - * \c false if memory allocation fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, uint32_t num, FLAC__uint64 total_samples); - -/** Append a set of evenly-spaced seek point templates to the end of a - * seek table. - * - * \note - * As with the other ..._seektable_template_... functions, you should - * call FLAC__metadata_object_seektable_template_sort() when finished - * to make the seek table legal. - * - * \param object A pointer to an existing SEEKTABLE object. - * \param samples The number of samples apart to space the placeholder - * points. The first point will be at sample \c 0, the - * second at sample \a samples, then 2*\a samples, and - * so on. As long as \a samples and \a total_samples - * are greater than \c 0, there will always be at least - * one seekpoint at sample \c 0. - * \param total_samples The total number of samples to be encoded; - * the seekpoints will be spaced - * \a samples samples apart. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \code samples > 0 \endcode - * \code total_samples > 0 \endcode - * \retval FLAC__bool - * \c false if memory allocation fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, uint32_t samples, FLAC__uint64 total_samples); - -/** Sort a seek table's seek points according to the format specification, - * removing duplicates. - * - * \param object A pointer to a seek table to be sorted. - * \param compact If \c false, behaves like FLAC__format_seektable_sort(). - * If \c true, duplicates are deleted and the seek table is - * shrunk appropriately; the number of placeholder points - * present in the seek table will be the same after the call - * as before. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode - * \retval FLAC__bool - * \c false if realloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact); - -/** Sets the vendor string in a VORBIS_COMMENT block. - * - * For convenience, a trailing NUL is added to the entry if it doesn't have - * one already. - * - * If \a copy is \c true, a copy of the entry is stored; otherwise, the object - * takes ownership of the \c entry.entry pointer. - * - * \note If this function returns \c false, the caller still owns the - * pointer. - * - * \param object A pointer to an existing VORBIS_COMMENT object. - * \param entry The entry to set the vendor string to. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode - * \code (entry.entry != NULL && entry.length > 0) || - * (entry.entry == NULL && entry.length == 0) \endcode - * \retval FLAC__bool - * \c false if memory allocation fails or \a entry does not comply with the - * Vorbis comment specification, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy); - -/** Resize the comment array. - * - * If the size shrinks, elements will truncated; if it grows, new empty - * fields will be added to the end. - * - * \param object A pointer to an existing VORBIS_COMMENT object. - * \param new_num_comments The desired length of the array; may be \c 0. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode - * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) || - * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode - * \retval FLAC__bool - * \c false if memory allocation fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, uint32_t new_num_comments); - -/** Sets a comment in a VORBIS_COMMENT block. - * - * For convenience, a trailing NUL is added to the entry if it doesn't have - * one already. - * - * If \a copy is \c true, a copy of the entry is stored; otherwise, the object - * takes ownership of the \c entry.entry pointer. - * - * \note If this function returns \c false, the caller still owns the - * pointer. - * - * \param object A pointer to an existing VORBIS_COMMENT object. - * \param comment_num Index into comment array to set. - * \param entry The entry to set the comment to. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode - * \code comment_num < object->data.vorbis_comment.num_comments \endcode - * \code (entry.entry != NULL && entry.length > 0) || - * (entry.entry == NULL && entry.length == 0) \endcode - * \retval FLAC__bool - * \c false if memory allocation fails or \a entry does not comply with the - * Vorbis comment specification, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, uint32_t comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy); - -/** Insert a comment in a VORBIS_COMMENT block at the given index. - * - * For convenience, a trailing NUL is added to the entry if it doesn't have - * one already. - * - * If \a copy is \c true, a copy of the entry is stored; otherwise, the object - * takes ownership of the \c entry.entry pointer. - * - * \note If this function returns \c false, the caller still owns the - * pointer. - * - * \param object A pointer to an existing VORBIS_COMMENT object. - * \param comment_num The index at which to insert the comment. The comments - * at and after \a comment_num move right one position. - * To append a comment to the end, set \a comment_num to - * \c object->data.vorbis_comment.num_comments . - * \param entry The comment to insert. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode - * \code object->data.vorbis_comment.num_comments >= comment_num \endcode - * \code (entry.entry != NULL && entry.length > 0) || - * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode - * \retval FLAC__bool - * \c false if memory allocation fails or \a entry does not comply with the - * Vorbis comment specification, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, uint32_t comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy); - -/** Appends a comment to a VORBIS_COMMENT block. - * - * For convenience, a trailing NUL is added to the entry if it doesn't have - * one already. - * - * If \a copy is \c true, a copy of the entry is stored; otherwise, the object - * takes ownership of the \c entry.entry pointer. - * - * \note If this function returns \c false, the caller still owns the - * pointer. - * - * \param object A pointer to an existing VORBIS_COMMENT object. - * \param entry The comment to insert. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode - * \code (entry.entry != NULL && entry.length > 0) || - * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode - * \retval FLAC__bool - * \c false if memory allocation fails or \a entry does not comply with the - * Vorbis comment specification, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy); - -/** Replaces comments in a VORBIS_COMMENT block with a new one. - * - * For convenience, a trailing NUL is added to the entry if it doesn't have - * one already. - * - * Depending on the value of \a all, either all or just the first comment - * whose field name(s) match the given entry's name will be replaced by the - * given entry. If no comments match, \a entry will simply be appended. - * - * If \a copy is \c true, a copy of the entry is stored; otherwise, the object - * takes ownership of the \c entry.entry pointer. - * - * \note If this function returns \c false, the caller still owns the - * pointer. - * - * \param object A pointer to an existing VORBIS_COMMENT object. - * \param entry The comment to insert. - * \param all If \c true, all comments whose field name matches - * \a entry's field name will be removed, and \a entry will - * be inserted at the position of the first matching - * comment. If \c false, only the first comment whose - * field name matches \a entry's field name will be - * replaced with \a entry. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode - * \code (entry.entry != NULL && entry.length > 0) || - * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode - * \retval FLAC__bool - * \c false if memory allocation fails or \a entry does not comply with the - * Vorbis comment specification, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy); - -/** Delete a comment in a VORBIS_COMMENT block at the given index. - * - * \param object A pointer to an existing VORBIS_COMMENT object. - * \param comment_num The index of the comment to delete. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode - * \code object->data.vorbis_comment.num_comments > comment_num \endcode - * \retval FLAC__bool - * \c false if realloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, uint32_t comment_num); - -/** Creates a Vorbis comment entry from NUL-terminated name and value strings. - * - * On return, the filled-in \a entry->entry pointer will point to malloc()ed - * memory and shall be owned by the caller. For convenience the entry will - * have a terminating NUL. - * - * \param entry A pointer to a Vorbis comment entry. The entry's - * \c entry pointer should not point to allocated - * memory as it will be overwritten. - * \param field_name The field name in ASCII, \c NUL terminated. - * \param field_value The field value in UTF-8, \c NUL terminated. - * \assert - * \code entry != NULL \endcode - * \code field_name != NULL \endcode - * \code field_value != NULL \endcode - * \retval FLAC__bool - * \c false if malloc() fails, or if \a field_name or \a field_value does - * not comply with the Vorbis comment specification, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(FLAC__StreamMetadata_VorbisComment_Entry *entry, const char *field_name, const char *field_value); - -/** Splits a Vorbis comment entry into NUL-terminated name and value strings. - * - * The returned pointers to name and value will be allocated by malloc() - * and shall be owned by the caller. - * - * \param entry An existing Vorbis comment entry. - * \param field_name The address of where the returned pointer to the - * field name will be stored. - * \param field_value The address of where the returned pointer to the - * field value will be stored. - * \assert - * \code (entry.entry != NULL && entry.length > 0) \endcode - * \code memchr(entry.entry, '=', entry.length) != NULL \endcode - * \code field_name != NULL \endcode - * \code field_value != NULL \endcode - * \retval FLAC__bool - * \c false if memory allocation fails or \a entry does not comply with the - * Vorbis comment specification, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value); - -/** Check if the given Vorbis comment entry's field name matches the given - * field name. - * - * \param entry An existing Vorbis comment entry. - * \param field_name The field name to check. - * \param field_name_length The length of \a field_name, not including the - * terminating \c NUL. - * \assert - * \code (entry.entry != NULL && entry.length > 0) \endcode - * \retval FLAC__bool - * \c true if the field names match, else \c false - */ -FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, uint32_t field_name_length); - -/** Find a Vorbis comment with the given field name. - * - * The search begins at entry number \a offset; use an offset of 0 to - * search from the beginning of the comment array. - * - * \param object A pointer to an existing VORBIS_COMMENT object. - * \param offset The offset into the comment array from where to start - * the search. - * \param field_name The field name of the comment to find. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode - * \code field_name != NULL \endcode - * \retval int - * The offset in the comment array of the first comment whose field - * name matches \a field_name, or \c -1 if no match was found. - */ -FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, uint32_t offset, const char *field_name); - -/** Remove first Vorbis comment matching the given field name. - * - * \param object A pointer to an existing VORBIS_COMMENT object. - * \param field_name The field name of comment to delete. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode - * \retval int - * \c -1 for memory allocation error, \c 0 for no matching entries, - * \c 1 for one matching entry deleted. - */ -FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name); - -/** Remove all Vorbis comments matching the given field name. - * - * \param object A pointer to an existing VORBIS_COMMENT object. - * \param field_name The field name of comments to delete. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode - * \retval int - * \c -1 for memory allocation error, \c 0 for no matching entries, - * else the number of matching entries deleted. - */ -FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name); - -/** Create a new CUESHEET track instance. - * - * The object will be "empty"; i.e. values and data pointers will be \c 0. - * - * \retval FLAC__StreamMetadata_CueSheet_Track* - * \c NULL if there was an error allocating memory, else the new instance. - */ -FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void); - -/** Create a copy of an existing CUESHEET track object. - * - * The copy is a "deep" copy, i.e. dynamically allocated data within the - * object is also copied. The caller takes ownership of the new object and - * is responsible for freeing it with - * FLAC__metadata_object_cuesheet_track_delete(). - * - * \param object Pointer to object to copy. - * \assert - * \code object != NULL \endcode - * \retval FLAC__StreamMetadata_CueSheet_Track* - * \c NULL if there was an error allocating memory, else the new instance. - */ -FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object); - -/** Delete a CUESHEET track object - * - * \param object A pointer to an existing CUESHEET track object. - * \assert - * \code object != NULL \endcode - */ -FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object); - -/** Resize a track's index point array. - * - * If the size shrinks, elements will truncated; if it grows, new blank - * indices will be added to the end. - * - * \param object A pointer to an existing CUESHEET object. - * \param track_num The index of the track to modify. NOTE: this is not - * necessarily the same as the track's \a number field. - * \param new_num_indices The desired length of the array; may be \c 0. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \code object->data.cue_sheet.num_tracks > track_num \endcode - * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) || - * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode - * \retval FLAC__bool - * \c false if memory allocation error, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, uint32_t track_num, uint32_t new_num_indices); - -/** Insert an index point in a CUESHEET track at the given index. - * - * \param object A pointer to an existing CUESHEET object. - * \param track_num The index of the track to modify. NOTE: this is not - * necessarily the same as the track's \a number field. - * \param index_num The index into the track's index array at which to - * insert the index point. NOTE: this is not necessarily - * the same as the index point's \a number field. The - * indices at and after \a index_num move right one - * position. To append an index point to the end, set - * \a index_num to - * \c object->data.cue_sheet.tracks[track_num].num_indices . - * \param index The index point to insert. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \code object->data.cue_sheet.num_tracks > track_num \endcode - * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode - * \retval FLAC__bool - * \c false if realloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, uint32_t track_num, uint32_t index_num, FLAC__StreamMetadata_CueSheet_Index index); - -/** Insert a blank index point in a CUESHEET track at the given index. - * - * A blank index point is one in which all field values are zero. - * - * \param object A pointer to an existing CUESHEET object. - * \param track_num The index of the track to modify. NOTE: this is not - * necessarily the same as the track's \a number field. - * \param index_num The index into the track's index array at which to - * insert the index point. NOTE: this is not necessarily - * the same as the index point's \a number field. The - * indices at and after \a index_num move right one - * position. To append an index point to the end, set - * \a index_num to - * \c object->data.cue_sheet.tracks[track_num].num_indices . - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \code object->data.cue_sheet.num_tracks > track_num \endcode - * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode - * \retval FLAC__bool - * \c false if realloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, uint32_t track_num, uint32_t index_num); - -/** Delete an index point in a CUESHEET track at the given index. - * - * \param object A pointer to an existing CUESHEET object. - * \param track_num The index into the track array of the track to - * modify. NOTE: this is not necessarily the same - * as the track's \a number field. - * \param index_num The index into the track's index array of the index - * to delete. NOTE: this is not necessarily the same - * as the index's \a number field. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \code object->data.cue_sheet.num_tracks > track_num \endcode - * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode - * \retval FLAC__bool - * \c false if realloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, uint32_t track_num, uint32_t index_num); - -/** Resize the track array. - * - * If the size shrinks, elements will truncated; if it grows, new blank - * tracks will be added to the end. - * - * \param object A pointer to an existing CUESHEET object. - * \param new_num_tracks The desired length of the array; may be \c 0. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) || - * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode - * \retval FLAC__bool - * \c false if memory allocation error, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, uint32_t new_num_tracks); - -/** Sets a track in a CUESHEET block. - * - * If \a copy is \c true, a copy of the track is stored; otherwise, the object - * takes ownership of the \a track pointer. - * - * \param object A pointer to an existing CUESHEET object. - * \param track_num Index into track array to set. NOTE: this is not - * necessarily the same as the track's \a number field. - * \param track The track to set the track to. You may safely pass in - * a const pointer if \a copy is \c true. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \code track_num < object->data.cue_sheet.num_tracks \endcode - * \code (track->indices != NULL && track->num_indices > 0) || - * (track->indices == NULL && track->num_indices == 0) \endcode - * \retval FLAC__bool - * \c false if \a copy is \c true and malloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, uint32_t track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy); - -/** Insert a track in a CUESHEET block at the given index. - * - * If \a copy is \c true, a copy of the track is stored; otherwise, the object - * takes ownership of the \a track pointer. - * - * \param object A pointer to an existing CUESHEET object. - * \param track_num The index at which to insert the track. NOTE: this - * is not necessarily the same as the track's \a number - * field. The tracks at and after \a track_num move right - * one position. To append a track to the end, set - * \a track_num to \c object->data.cue_sheet.num_tracks . - * \param track The track to insert. You may safely pass in a const - * pointer if \a copy is \c true. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \code object->data.cue_sheet.num_tracks >= track_num \endcode - * \retval FLAC__bool - * \c false if \a copy is \c true and malloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, uint32_t track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy); - -/** Insert a blank track in a CUESHEET block at the given index. - * - * A blank track is one in which all field values are zero. - * - * \param object A pointer to an existing CUESHEET object. - * \param track_num The index at which to insert the track. NOTE: this - * is not necessarily the same as the track's \a number - * field. The tracks at and after \a track_num move right - * one position. To append a track to the end, set - * \a track_num to \c object->data.cue_sheet.num_tracks . - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \code object->data.cue_sheet.num_tracks >= track_num \endcode - * \retval FLAC__bool - * \c false if \a copy is \c true and malloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, uint32_t track_num); - -/** Delete a track in a CUESHEET block at the given index. - * - * \param object A pointer to an existing CUESHEET object. - * \param track_num The index into the track array of the track to - * delete. NOTE: this is not necessarily the same - * as the track's \a number field. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \code object->data.cue_sheet.num_tracks > track_num \endcode - * \retval FLAC__bool - * \c false if realloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, uint32_t track_num); - -/** Check a cue sheet to see if it conforms to the FLAC specification. - * See the format specification for limits on the contents of the - * cue sheet. - * - * \param object A pointer to an existing CUESHEET object. - * \param check_cd_da_subset If \c true, check CUESHEET against more - * stringent requirements for a CD-DA (audio) disc. - * \param violation Address of a pointer to a string. If there is a - * violation, a pointer to a string explanation of the - * violation will be returned here. \a violation may be - * \c NULL if you don't need the returned string. Do not - * free the returned string; it will always point to static - * data. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \retval FLAC__bool - * \c false if cue sheet is illegal, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation); - -/** Calculate and return the CDDB/freedb ID for a cue sheet. The function - * assumes the cue sheet corresponds to a CD; the result is undefined - * if the cuesheet's is_cd bit is not set. - * - * \param object A pointer to an existing CUESHEET object. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode - * \retval FLAC__uint32 - * The unsigned integer representation of the CDDB/freedb ID - */ -FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object); - -/** Sets the MIME type of a PICTURE block. - * - * If \a copy is \c true, a copy of the string is stored; otherwise, the object - * takes ownership of the pointer. The existing string will be freed if this - * function is successful, otherwise the original string will remain if \a copy - * is \c true and malloc() fails. - * - * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true. - * - * \param object A pointer to an existing PICTURE object. - * \param mime_type A pointer to the MIME type string. The string must be - * ASCII characters 0x20-0x7e, NUL-terminated. No validation - * is done. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode - * \code (mime_type != NULL) \endcode - * \retval FLAC__bool - * \c false if \a copy is \c true and malloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy); - -/** Sets the description of a PICTURE block. - * - * If \a copy is \c true, a copy of the string is stored; otherwise, the object - * takes ownership of the pointer. The existing string will be freed if this - * function is successful, otherwise the original string will remain if \a copy - * is \c true and malloc() fails. - * - * \note It is safe to pass a const pointer to \a description if \a copy is \c true. - * - * \param object A pointer to an existing PICTURE object. - * \param description A pointer to the description string. The string must be - * valid UTF-8, NUL-terminated. No validation is done. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode - * \code (description != NULL) \endcode - * \retval FLAC__bool - * \c false if \a copy is \c true and malloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy); - -/** Sets the picture data of a PICTURE block. - * - * If \a copy is \c true, a copy of the data is stored; otherwise, the object - * takes ownership of the pointer. Also sets the \a data_length field of the - * metadata object to what is passed in as the \a length parameter. The - * existing data will be freed if this function is successful, otherwise the - * original data and data_length will remain if \a copy is \c true and - * malloc() fails. - * - * \note It is safe to pass a const pointer to \a data if \a copy is \c true. - * - * \param object A pointer to an existing PICTURE object. - * \param data A pointer to the data to set. - * \param length The length of \a data in bytes. - * \param copy See above. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode - * \code (data != NULL && length > 0) || - * (data == NULL && length == 0 && copy == false) \endcode - * \retval FLAC__bool - * \c false if \a copy is \c true and malloc() fails, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy); - -/** Check a PICTURE block to see if it conforms to the FLAC specification. - * See the format specification for limits on the contents of the - * PICTURE block. - * - * \param object A pointer to existing PICTURE block to be checked. - * \param violation Address of a pointer to a string. If there is a - * violation, a pointer to a string explanation of the - * violation will be returned here. \a violation may be - * \c NULL if you don't need the returned string. Do not - * free the returned string; it will always point to static - * data. - * \assert - * \code object != NULL \endcode - * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode - * \retval FLAC__bool - * \c false if PICTURE block is illegal, else \c true. - */ -FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation); - -/* \} */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libs/include/FLAC/ordinals.h b/libs/include/FLAC/ordinals.h deleted file mode 100644 index 75b830d6..00000000 --- a/libs/include/FLAC/ordinals.h +++ /dev/null @@ -1,85 +0,0 @@ -/* libFLAC - Free Lossless Audio Codec library - * Copyright (C) 2000-2009 Josh Coalson - * Copyright (C) 2011-2016 Xiph.Org Foundation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of the Xiph.org Foundation nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FLAC__ORDINALS_H -#define FLAC__ORDINALS_H - -#if defined(_MSC_VER) && _MSC_VER < 1600 - -/* Microsoft Visual Studio earlier than the 2010 version did not provide - * the 1999 ISO C Standard header file . - */ - -typedef signed __int8 FLAC__int8; -typedef signed __int16 FLAC__int16; -typedef signed __int32 FLAC__int32; -typedef signed __int64 FLAC__int64; -typedef unsigned __int8 FLAC__uint8; -typedef unsigned __int16 FLAC__uint16; -typedef unsigned __int32 FLAC__uint32; -typedef unsigned __int64 FLAC__uint64; - -#else - -/* For MSVC 2010 and everything else which provides . */ - -#include - -typedef int8_t FLAC__int8; -typedef uint8_t FLAC__uint8; - -typedef int16_t FLAC__int16; -typedef int32_t FLAC__int32; -typedef int64_t FLAC__int64; -typedef uint16_t FLAC__uint16; -typedef uint32_t FLAC__uint32; -typedef uint64_t FLAC__uint64; - -#endif - -typedef int FLAC__bool; - -typedef FLAC__uint8 FLAC__byte; - - -#ifdef true -#undef true -#endif -#ifdef false -#undef false -#endif -#ifndef __cplusplus -#define true 1 -#define false 0 -#endif - -#endif diff --git a/libs/include/FLAC/stream_decoder.h b/libs/include/FLAC/stream_decoder.h deleted file mode 100644 index 57215c5e..00000000 --- a/libs/include/FLAC/stream_decoder.h +++ /dev/null @@ -1,1559 +0,0 @@ -/* libFLAC - Free Lossless Audio Codec library - * Copyright (C) 2000-2009 Josh Coalson - * Copyright (C) 2011-2016 Xiph.Org Foundation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of the Xiph.org Foundation nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FLAC__STREAM_DECODER_H -#define FLAC__STREAM_DECODER_H - -#include /* for FILE */ -#include "export.h" -#include "format.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -/** \file include/FLAC/stream_decoder.h - * - * \brief - * This module contains the functions which implement the stream - * decoder. - * - * See the detailed documentation in the - * \link flac_stream_decoder stream decoder \endlink module. - */ - -/** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces - * \ingroup flac - * - * \brief - * This module describes the decoder layers provided by libFLAC. - * - * The stream decoder can be used to decode complete streams either from - * the client via callbacks, or directly from a file, depending on how - * it is initialized. When decoding via callbacks, the client provides - * callbacks for reading FLAC data and writing decoded samples, and - * handling metadata and errors. If the client also supplies seek-related - * callback, the decoder function for sample-accurate seeking within the - * FLAC input is also available. When decoding from a file, the client - * needs only supply a filename or open \c FILE* and write/metadata/error - * callbacks; the rest of the callbacks are supplied internally. For more - * info see the \link flac_stream_decoder stream decoder \endlink module. - */ - -/** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface - * \ingroup flac_decoder - * - * \brief - * This module contains the functions which implement the stream - * decoder. - * - * The stream decoder can decode native FLAC, and optionally Ogg FLAC - * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files. - * - * The basic usage of this decoder is as follows: - * - The program creates an instance of a decoder using - * FLAC__stream_decoder_new(). - * - The program overrides the default settings using - * FLAC__stream_decoder_set_*() functions. - * - The program initializes the instance to validate the settings and - * prepare for decoding using - * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE() - * or FLAC__stream_decoder_init_file() for native FLAC, - * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE() - * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC - * - The program calls the FLAC__stream_decoder_process_*() functions - * to decode data, which subsequently calls the callbacks. - * - The program finishes the decoding with FLAC__stream_decoder_finish(), - * which flushes the input and output and resets the decoder to the - * uninitialized state. - * - The instance may be used again or deleted with - * FLAC__stream_decoder_delete(). - * - * In more detail, the program will create a new instance by calling - * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*() - * functions to override the default decoder options, and call - * one of the FLAC__stream_decoder_init_*() functions. - * - * There are three initialization functions for native FLAC, one for - * setting up the decoder to decode FLAC data from the client via - * callbacks, and two for decoding directly from a FLAC file. - * - * For decoding via callbacks, use FLAC__stream_decoder_init_stream(). - * You must also supply several callbacks for handling I/O. Some (like - * seeking) are optional, depending on the capabilities of the input. - * - * For decoding directly from a file, use FLAC__stream_decoder_init_FILE() - * or FLAC__stream_decoder_init_file(). Then you must only supply an open - * \c FILE* or filename and fewer callbacks; the decoder will handle - * the other callbacks internally. - * - * There are three similarly-named init functions for decoding from Ogg - * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the - * library has been built with Ogg support. - * - * Once the decoder is initialized, your program will call one of several - * functions to start the decoding process: - * - * - FLAC__stream_decoder_process_single() - Tells the decoder to process at - * most one metadata block or audio frame and return, calling either the - * metadata callback or write callback, respectively, once. If the decoder - * loses sync it will return with only the error callback being called. - * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder - * to process the stream from the current location and stop upon reaching - * the first audio frame. The client will get one metadata, write, or error - * callback per metadata block, audio frame, or sync error, respectively. - * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder - * to process the stream from the current location until the read callback - * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or - * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata, - * write, or error callback per metadata block, audio frame, or sync error, - * respectively. - * - * When the decoder has finished decoding (normally or through an abort), - * the instance is finished by calling FLAC__stream_decoder_finish(), which - * ensures the decoder is in the correct state and frees memory. Then the - * instance may be deleted with FLAC__stream_decoder_delete() or initialized - * again to decode another stream. - * - * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method. - * At any point after the stream decoder has been initialized, the client can - * call this function to seek to an exact sample within the stream. - * Subsequently, the first time the write callback is called it will be - * passed a (possibly partial) block starting at that sample. - * - * If the client cannot seek via the callback interface provided, but still - * has another way of seeking, it can flush the decoder using - * FLAC__stream_decoder_flush() and start feeding data from the new position - * through the read callback. - * - * The stream decoder also provides MD5 signature checking. If this is - * turned on before initialization, FLAC__stream_decoder_finish() will - * report when the decoded MD5 signature does not match the one stored - * in the STREAMINFO block. MD5 checking is automatically turned off - * (until the next FLAC__stream_decoder_reset()) if there is no signature - * in the STREAMINFO block or when a seek is attempted. - * - * The FLAC__stream_decoder_set_metadata_*() functions deserve special - * attention. By default, the decoder only calls the metadata_callback for - * the STREAMINFO block. These functions allow you to tell the decoder - * explicitly which blocks to parse and return via the metadata_callback - * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(), - * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(), - * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify - * which blocks to return. Remember that metadata blocks can potentially - * be big (for example, cover art) so filtering out the ones you don't - * use can reduce the memory requirements of the decoder. Also note the - * special forms FLAC__stream_decoder_set_metadata_respond_application(id) - * and FLAC__stream_decoder_set_metadata_ignore_application(id) for - * filtering APPLICATION blocks based on the application ID. - * - * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but - * they still can legally be filtered from the metadata_callback. - * - * \note - * The "set" functions may only be called when the decoder is in the - * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after - * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but - * before FLAC__stream_decoder_init_*(). If this is the case they will - * return \c true, otherwise \c false. - * - * \note - * FLAC__stream_decoder_finish() resets all settings to the constructor - * defaults, including the callbacks. - * - * \{ - */ - - -/** State values for a FLAC__StreamDecoder - * - * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state(). - */ -typedef enum { - - FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0, - /**< The decoder is ready to search for metadata. */ - - FLAC__STREAM_DECODER_READ_METADATA, - /**< The decoder is ready to or is in the process of reading metadata. */ - - FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC, - /**< The decoder is ready to or is in the process of searching for the - * frame sync code. - */ - - FLAC__STREAM_DECODER_READ_FRAME, - /**< The decoder is ready to or is in the process of reading a frame. */ - - FLAC__STREAM_DECODER_END_OF_STREAM, - /**< The decoder has reached the end of the stream. */ - - FLAC__STREAM_DECODER_OGG_ERROR, - /**< An error occurred in the underlying Ogg layer. */ - - FLAC__STREAM_DECODER_SEEK_ERROR, - /**< An error occurred while seeking. The decoder must be flushed - * with FLAC__stream_decoder_flush() or reset with - * FLAC__stream_decoder_reset() before decoding can continue. - */ - - FLAC__STREAM_DECODER_ABORTED, - /**< The decoder was aborted by the read or write callback. */ - - FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR, - /**< An error occurred allocating memory. The decoder is in an invalid - * state and can no longer be used. - */ - - FLAC__STREAM_DECODER_UNINITIALIZED - /**< The decoder is in the uninitialized state; one of the - * FLAC__stream_decoder_init_*() functions must be called before samples - * can be processed. - */ - -} FLAC__StreamDecoderState; - -/** Maps a FLAC__StreamDecoderState to a C string. - * - * Using a FLAC__StreamDecoderState as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamDecoderStateString[]; - - -/** Possible return values for the FLAC__stream_decoder_init_*() functions. - */ -typedef enum { - - FLAC__STREAM_DECODER_INIT_STATUS_OK = 0, - /**< Initialization was successful. */ - - FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER, - /**< The library was not compiled with support for the given container - * format. - */ - - FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS, - /**< A required callback was not supplied. */ - - FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR, - /**< An error occurred allocating memory. */ - - FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE, - /**< fopen() failed in FLAC__stream_decoder_init_file() or - * FLAC__stream_decoder_init_ogg_file(). */ - - FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED - /**< FLAC__stream_decoder_init_*() was called when the decoder was - * already initialized, usually because - * FLAC__stream_decoder_finish() was not called. - */ - -} FLAC__StreamDecoderInitStatus; - -/** Maps a FLAC__StreamDecoderInitStatus to a C string. - * - * Using a FLAC__StreamDecoderInitStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[]; - - -/** Return values for the FLAC__StreamDecoder read callback. - */ -typedef enum { - - FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, - /**< The read was OK and decoding can continue. */ - - FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM, - /**< The read was attempted while at the end of the stream. Note that - * the client must only return this value when the read callback was - * called when already at the end of the stream. Otherwise, if the read - * itself moves to the end of the stream, the client should still return - * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on - * the next read callback it should return - * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count - * of \c 0. - */ - - FLAC__STREAM_DECODER_READ_STATUS_ABORT - /**< An unrecoverable error occurred. The decoder will return from the process call. */ - -} FLAC__StreamDecoderReadStatus; - -/** Maps a FLAC__StreamDecoderReadStatus to a C string. - * - * Using a FLAC__StreamDecoderReadStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[]; - - -/** Return values for the FLAC__StreamDecoder seek callback. - */ -typedef enum { - - FLAC__STREAM_DECODER_SEEK_STATUS_OK, - /**< The seek was OK and decoding can continue. */ - - FLAC__STREAM_DECODER_SEEK_STATUS_ERROR, - /**< An unrecoverable error occurred. The decoder will return from the process call. */ - - FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED - /**< Client does not support seeking. */ - -} FLAC__StreamDecoderSeekStatus; - -/** Maps a FLAC__StreamDecoderSeekStatus to a C string. - * - * Using a FLAC__StreamDecoderSeekStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[]; - - -/** Return values for the FLAC__StreamDecoder tell callback. - */ -typedef enum { - - FLAC__STREAM_DECODER_TELL_STATUS_OK, - /**< The tell was OK and decoding can continue. */ - - FLAC__STREAM_DECODER_TELL_STATUS_ERROR, - /**< An unrecoverable error occurred. The decoder will return from the process call. */ - - FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED - /**< Client does not support telling the position. */ - -} FLAC__StreamDecoderTellStatus; - -/** Maps a FLAC__StreamDecoderTellStatus to a C string. - * - * Using a FLAC__StreamDecoderTellStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[]; - - -/** Return values for the FLAC__StreamDecoder length callback. - */ -typedef enum { - - FLAC__STREAM_DECODER_LENGTH_STATUS_OK, - /**< The length call was OK and decoding can continue. */ - - FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR, - /**< An unrecoverable error occurred. The decoder will return from the process call. */ - - FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED - /**< Client does not support reporting the length. */ - -} FLAC__StreamDecoderLengthStatus; - -/** Maps a FLAC__StreamDecoderLengthStatus to a C string. - * - * Using a FLAC__StreamDecoderLengthStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[]; - - -/** Return values for the FLAC__StreamDecoder write callback. - */ -typedef enum { - - FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE, - /**< The write was OK and decoding can continue. */ - - FLAC__STREAM_DECODER_WRITE_STATUS_ABORT - /**< An unrecoverable error occurred. The decoder will return from the process call. */ - -} FLAC__StreamDecoderWriteStatus; - -/** Maps a FLAC__StreamDecoderWriteStatus to a C string. - * - * Using a FLAC__StreamDecoderWriteStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[]; - - -/** Possible values passed back to the FLAC__StreamDecoder error callback. - * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch- - * all. The rest could be caused by bad sync (false synchronization on - * data that is not the start of a frame) or corrupted data. The error - * itself is the decoder's best guess at what happened assuming a correct - * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER - * could be caused by a correct sync on the start of a frame, but some - * data in the frame header was corrupted. Or it could be the result of - * syncing on a point the stream that looked like the starting of a frame - * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM - * could be because the decoder encountered a valid frame made by a future - * version of the encoder which it cannot parse, or because of a false - * sync making it appear as though an encountered frame was generated by - * a future encoder. - */ -typedef enum { - - FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC, - /**< An error in the stream caused the decoder to lose synchronization. */ - - FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER, - /**< The decoder encountered a corrupted frame header. */ - - FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH, - /**< The frame's data did not match the CRC in the footer. */ - - FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM - /**< The decoder encountered reserved fields in use in the stream. */ - -} FLAC__StreamDecoderErrorStatus; - -/** Maps a FLAC__StreamDecoderErrorStatus to a C string. - * - * Using a FLAC__StreamDecoderErrorStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[]; - - -/*********************************************************************** - * - * class FLAC__StreamDecoder - * - ***********************************************************************/ - -struct FLAC__StreamDecoderProtected; -struct FLAC__StreamDecoderPrivate; -/** The opaque structure definition for the stream decoder type. - * See the \link flac_stream_decoder stream decoder module \endlink - * for a detailed description. - */ -typedef struct { - struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */ - struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */ -} FLAC__StreamDecoder; - -/** Signature for the read callback. - * - * A function pointer matching this signature must be passed to - * FLAC__stream_decoder_init*_stream(). The supplied function will be - * called when the decoder needs more input data. The address of the - * buffer to be filled is supplied, along with the number of bytes the - * buffer can hold. The callback may choose to supply less data and - * modify the byte count but must be careful not to overflow the buffer. - * The callback then returns a status code chosen from - * FLAC__StreamDecoderReadStatus. - * - * Here is an example of a read callback for stdio streams: - * \code - * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) - * { - * FILE *file = ((MyClientData*)client_data)->file; - * if(*bytes > 0) { - * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file); - * if(ferror(file)) - * return FLAC__STREAM_DECODER_READ_STATUS_ABORT; - * else if(*bytes == 0) - * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; - * else - * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; - * } - * else - * return FLAC__STREAM_DECODER_READ_STATUS_ABORT; - * } - * \endcode - * - * \note In general, FLAC__StreamDecoder functions which change the - * state should not be called on the \a decoder while in the callback. - * - * \param decoder The decoder instance calling the callback. - * \param buffer A pointer to a location for the callee to store - * data to be decoded. - * \param bytes A pointer to the size of the buffer. On entry - * to the callback, it contains the maximum number - * of bytes that may be stored in \a buffer. The - * callee must set it to the actual number of bytes - * stored (0 in case of error or end-of-stream) before - * returning. - * \param client_data The callee's client data set through - * FLAC__stream_decoder_init_*(). - * \retval FLAC__StreamDecoderReadStatus - * The callee's return status. Note that the callback should return - * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if - * zero bytes were read and there is no more data to be read. - */ -typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data); - -/** Signature for the seek callback. - * - * A function pointer matching this signature may be passed to - * FLAC__stream_decoder_init*_stream(). The supplied function will be - * called when the decoder needs to seek the input stream. The decoder - * will pass the absolute byte offset to seek to, 0 meaning the - * beginning of the stream. - * - * Here is an example of a seek callback for stdio streams: - * \code - * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data) - * { - * FILE *file = ((MyClientData*)client_data)->file; - * if(file == stdin) - * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED; - * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0) - * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; - * else - * return FLAC__STREAM_DECODER_SEEK_STATUS_OK; - * } - * \endcode - * - * \note In general, FLAC__StreamDecoder functions which change the - * state should not be called on the \a decoder while in the callback. - * - * \param decoder The decoder instance calling the callback. - * \param absolute_byte_offset The offset from the beginning of the stream - * to seek to. - * \param client_data The callee's client data set through - * FLAC__stream_decoder_init_*(). - * \retval FLAC__StreamDecoderSeekStatus - * The callee's return status. - */ -typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data); - -/** Signature for the tell callback. - * - * A function pointer matching this signature may be passed to - * FLAC__stream_decoder_init*_stream(). The supplied function will be - * called when the decoder wants to know the current position of the - * stream. The callback should return the byte offset from the - * beginning of the stream. - * - * Here is an example of a tell callback for stdio streams: - * \code - * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data) - * { - * FILE *file = ((MyClientData*)client_data)->file; - * off_t pos; - * if(file == stdin) - * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED; - * else if((pos = ftello(file)) < 0) - * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; - * else { - * *absolute_byte_offset = (FLAC__uint64)pos; - * return FLAC__STREAM_DECODER_TELL_STATUS_OK; - * } - * } - * \endcode - * - * \note In general, FLAC__StreamDecoder functions which change the - * state should not be called on the \a decoder while in the callback. - * - * \param decoder The decoder instance calling the callback. - * \param absolute_byte_offset A pointer to storage for the current offset - * from the beginning of the stream. - * \param client_data The callee's client data set through - * FLAC__stream_decoder_init_*(). - * \retval FLAC__StreamDecoderTellStatus - * The callee's return status. - */ -typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data); - -/** Signature for the length callback. - * - * A function pointer matching this signature may be passed to - * FLAC__stream_decoder_init*_stream(). The supplied function will be - * called when the decoder wants to know the total length of the stream - * in bytes. - * - * Here is an example of a length callback for stdio streams: - * \code - * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data) - * { - * FILE *file = ((MyClientData*)client_data)->file; - * struct stat filestats; - * - * if(file == stdin) - * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED; - * else if(fstat(fileno(file), &filestats) != 0) - * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR; - * else { - * *stream_length = (FLAC__uint64)filestats.st_size; - * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK; - * } - * } - * \endcode - * - * \note In general, FLAC__StreamDecoder functions which change the - * state should not be called on the \a decoder while in the callback. - * - * \param decoder The decoder instance calling the callback. - * \param stream_length A pointer to storage for the length of the stream - * in bytes. - * \param client_data The callee's client data set through - * FLAC__stream_decoder_init_*(). - * \retval FLAC__StreamDecoderLengthStatus - * The callee's return status. - */ -typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data); - -/** Signature for the EOF callback. - * - * A function pointer matching this signature may be passed to - * FLAC__stream_decoder_init*_stream(). The supplied function will be - * called when the decoder needs to know if the end of the stream has - * been reached. - * - * Here is an example of a EOF callback for stdio streams: - * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data) - * \code - * { - * FILE *file = ((MyClientData*)client_data)->file; - * return feof(file)? true : false; - * } - * \endcode - * - * \note In general, FLAC__StreamDecoder functions which change the - * state should not be called on the \a decoder while in the callback. - * - * \param decoder The decoder instance calling the callback. - * \param client_data The callee's client data set through - * FLAC__stream_decoder_init_*(). - * \retval FLAC__bool - * \c true if the currently at the end of the stream, else \c false. - */ -typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data); - -/** Signature for the write callback. - * - * A function pointer matching this signature must be passed to one of - * the FLAC__stream_decoder_init_*() functions. - * The supplied function will be called when the decoder has decoded a - * single audio frame. The decoder will pass the frame metadata as well - * as an array of pointers (one for each channel) pointing to the - * decoded audio. - * - * \note In general, FLAC__StreamDecoder functions which change the - * state should not be called on the \a decoder while in the callback. - * - * \param decoder The decoder instance calling the callback. - * \param frame The description of the decoded frame. See - * FLAC__Frame. - * \param buffer An array of pointers to decoded channels of data. - * Each pointer will point to an array of signed - * samples of length \a frame->header.blocksize. - * Channels will be ordered according to the FLAC - * specification; see the documentation for the - * frame header. - * \param client_data The callee's client data set through - * FLAC__stream_decoder_init_*(). - * \retval FLAC__StreamDecoderWriteStatus - * The callee's return status. - */ -typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data); - -/** Signature for the metadata callback. - * - * A function pointer matching this signature must be passed to one of - * the FLAC__stream_decoder_init_*() functions. - * The supplied function will be called when the decoder has decoded a - * metadata block. In a valid FLAC file there will always be one - * \c STREAMINFO block, followed by zero or more other metadata blocks. - * These will be supplied by the decoder in the same order as they - * appear in the stream and always before the first audio frame (i.e. - * write callback). The metadata block that is passed in must not be - * modified, and it doesn't live beyond the callback, so you should make - * a copy of it with FLAC__metadata_object_clone() if you will need it - * elsewhere. Since metadata blocks can potentially be large, by - * default the decoder only calls the metadata callback for the - * \c STREAMINFO block; you can instruct the decoder to pass or filter - * other blocks with FLAC__stream_decoder_set_metadata_*() calls. - * - * \note In general, FLAC__StreamDecoder functions which change the - * state should not be called on the \a decoder while in the callback. - * - * \param decoder The decoder instance calling the callback. - * \param metadata The decoded metadata block. - * \param client_data The callee's client data set through - * FLAC__stream_decoder_init_*(). - */ -typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data); - -/** Signature for the error callback. - * - * A function pointer matching this signature must be passed to one of - * the FLAC__stream_decoder_init_*() functions. - * The supplied function will be called whenever an error occurs during - * decoding. - * - * \note In general, FLAC__StreamDecoder functions which change the - * state should not be called on the \a decoder while in the callback. - * - * \param decoder The decoder instance calling the callback. - * \param status The error encountered by the decoder. - * \param client_data The callee's client data set through - * FLAC__stream_decoder_init_*(). - */ -typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data); - - -/*********************************************************************** - * - * Class constructor/destructor - * - ***********************************************************************/ - -/** Create a new stream decoder instance. The instance is created with - * default settings; see the individual FLAC__stream_decoder_set_*() - * functions for each setting's default. - * - * \retval FLAC__StreamDecoder* - * \c NULL if there was an error allocating memory, else the new instance. - */ -FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void); - -/** Free a decoder instance. Deletes the object pointed to by \a decoder. - * - * \param decoder A pointer to an existing decoder. - * \assert - * \code decoder != NULL \endcode - */ -FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder); - - -/*********************************************************************** - * - * Public class method prototypes - * - ***********************************************************************/ - -/** Set the serial number for the FLAC stream within the Ogg container. - * The default behavior is to use the serial number of the first Ogg - * page. Setting a serial number here will explicitly specify which - * stream is to be decoded. - * - * \note - * This does not need to be set for native FLAC decoding. - * - * \default \c use serial number of first page - * \param decoder A decoder instance to set. - * \param serial_number See above. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c false if the decoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number); - -/** Set the "MD5 signature checking" flag. If \c true, the decoder will - * compute the MD5 signature of the unencoded audio data while decoding - * and compare it to the signature from the STREAMINFO block, if it - * exists, during FLAC__stream_decoder_finish(). - * - * MD5 signature checking will be turned off (until the next - * FLAC__stream_decoder_reset()) if there is no signature in the - * STREAMINFO block or when a seek is attempted. - * - * Clients that do not use the MD5 check should leave this off to speed - * up decoding. - * - * \default \c false - * \param decoder A decoder instance to set. - * \param value Flag value (see above). - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c false if the decoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value); - -/** Direct the decoder to pass on all metadata blocks of type \a type. - * - * \default By default, only the \c STREAMINFO block is returned via the - * metadata callback. - * \param decoder A decoder instance to set. - * \param type See above. - * \assert - * \code decoder != NULL \endcode - * \a type is valid - * \retval FLAC__bool - * \c false if the decoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type); - -/** Direct the decoder to pass on all APPLICATION metadata blocks of the - * given \a id. - * - * \default By default, only the \c STREAMINFO block is returned via the - * metadata callback. - * \param decoder A decoder instance to set. - * \param id See above. - * \assert - * \code decoder != NULL \endcode - * \code id != NULL \endcode - * \retval FLAC__bool - * \c false if the decoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]); - -/** Direct the decoder to pass on all metadata blocks of any type. - * - * \default By default, only the \c STREAMINFO block is returned via the - * metadata callback. - * \param decoder A decoder instance to set. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c false if the decoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder); - -/** Direct the decoder to filter out all metadata blocks of type \a type. - * - * \default By default, only the \c STREAMINFO block is returned via the - * metadata callback. - * \param decoder A decoder instance to set. - * \param type See above. - * \assert - * \code decoder != NULL \endcode - * \a type is valid - * \retval FLAC__bool - * \c false if the decoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type); - -/** Direct the decoder to filter out all APPLICATION metadata blocks of - * the given \a id. - * - * \default By default, only the \c STREAMINFO block is returned via the - * metadata callback. - * \param decoder A decoder instance to set. - * \param id See above. - * \assert - * \code decoder != NULL \endcode - * \code id != NULL \endcode - * \retval FLAC__bool - * \c false if the decoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]); - -/** Direct the decoder to filter out all metadata blocks of any type. - * - * \default By default, only the \c STREAMINFO block is returned via the - * metadata callback. - * \param decoder A decoder instance to set. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c false if the decoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder); - -/** Get the current decoder state. - * - * \param decoder A decoder instance to query. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__StreamDecoderState - * The current decoder state. - */ -FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder); - -/** Get the current decoder state as a C string. - * - * \param decoder A decoder instance to query. - * \assert - * \code decoder != NULL \endcode - * \retval const char * - * The decoder state as a C string. Do not modify the contents. - */ -FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder); - -/** Get the "MD5 signature checking" flag. - * This is the value of the setting, not whether or not the decoder is - * currently checking the MD5 (remember, it can be turned off automatically - * by a seek). When the decoder is reset the flag will be restored to the - * value returned by this function. - * - * \param decoder A decoder instance to query. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * See above. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder); - -/** Get the total number of samples in the stream being decoded. - * Will only be valid after decoding has started and will contain the - * value from the \c STREAMINFO block. A value of \c 0 means "unknown". - * - * \param decoder A decoder instance to query. - * \assert - * \code decoder != NULL \endcode - * \retval uint32_t - * See above. - */ -FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder); - -/** Get the current number of channels in the stream being decoded. - * Will only be valid after decoding has started and will contain the - * value from the most recently decoded frame header. - * - * \param decoder A decoder instance to query. - * \assert - * \code decoder != NULL \endcode - * \retval uint32_t - * See above. - */ -FLAC_API uint32_t FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder); - -/** Get the current channel assignment in the stream being decoded. - * Will only be valid after decoding has started and will contain the - * value from the most recently decoded frame header. - * - * \param decoder A decoder instance to query. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__ChannelAssignment - * See above. - */ -FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder); - -/** Get the current sample resolution in the stream being decoded. - * Will only be valid after decoding has started and will contain the - * value from the most recently decoded frame header. - * - * \param decoder A decoder instance to query. - * \assert - * \code decoder != NULL \endcode - * \retval uint32_t - * See above. - */ -FLAC_API uint32_t FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder); - -/** Get the current sample rate in Hz of the stream being decoded. - * Will only be valid after decoding has started and will contain the - * value from the most recently decoded frame header. - * - * \param decoder A decoder instance to query. - * \assert - * \code decoder != NULL \endcode - * \retval uint32_t - * See above. - */ -FLAC_API uint32_t FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder); - -/** Get the current blocksize of the stream being decoded. - * Will only be valid after decoding has started and will contain the - * value from the most recently decoded frame header. - * - * \param decoder A decoder instance to query. - * \assert - * \code decoder != NULL \endcode - * \retval uint32_t - * See above. - */ -FLAC_API uint32_t FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder); - -/** Returns the decoder's current read position within the stream. - * The position is the byte offset from the start of the stream. - * Bytes before this position have been fully decoded. Note that - * there may still be undecoded bytes in the decoder's read FIFO. - * The returned position is correct even after a seek. - * - * \warning This function currently only works for native FLAC, - * not Ogg FLAC streams. - * - * \param decoder A decoder instance to query. - * \param position Address at which to return the desired position. - * \assert - * \code decoder != NULL \endcode - * \code position != NULL \endcode - * \retval FLAC__bool - * \c true if successful, \c false if the stream is not native FLAC, - * or there was an error from the 'tell' callback or it returned - * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position); - -/** Initialize the decoder instance to decode native FLAC streams. - * - * This flavor of initialization sets up the decoder to decode from a - * native FLAC stream. I/O is performed via callbacks to the client. - * For decoding from a plain file via filename or open FILE*, - * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE() - * provide a simpler interface. - * - * This function should be called after FLAC__stream_decoder_new() and - * FLAC__stream_decoder_set_*() but before any of the - * FLAC__stream_decoder_process_*() functions. Will set and return the - * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA - * if initialization succeeded. - * - * \param decoder An uninitialized decoder instance. - * \param read_callback See FLAC__StreamDecoderReadCallback. This - * pointer must not be \c NULL. - * \param seek_callback See FLAC__StreamDecoderSeekCallback. This - * pointer may be \c NULL if seeking is not - * supported. If \a seek_callback is not \c NULL then a - * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied. - * Alternatively, a dummy seek callback that just - * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED - * may also be supplied, all though this is slightly - * less efficient for the decoder. - * \param tell_callback See FLAC__StreamDecoderTellCallback. This - * pointer may be \c NULL if not supported by the client. If - * \a seek_callback is not \c NULL then a - * \a tell_callback must also be supplied. - * Alternatively, a dummy tell callback that just - * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED - * may also be supplied, all though this is slightly - * less efficient for the decoder. - * \param length_callback See FLAC__StreamDecoderLengthCallback. This - * pointer may be \c NULL if not supported by the client. If - * \a seek_callback is not \c NULL then a - * \a length_callback must also be supplied. - * Alternatively, a dummy length callback that just - * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED - * may also be supplied, all though this is slightly - * less efficient for the decoder. - * \param eof_callback See FLAC__StreamDecoderEofCallback. This - * pointer may be \c NULL if not supported by the client. If - * \a seek_callback is not \c NULL then a - * \a eof_callback must also be supplied. - * Alternatively, a dummy length callback that just - * returns \c false - * may also be supplied, all though this is slightly - * less efficient for the decoder. - * \param write_callback See FLAC__StreamDecoderWriteCallback. This - * pointer must not be \c NULL. - * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This - * pointer may be \c NULL if the callback is not - * desired. - * \param error_callback See FLAC__StreamDecoderErrorCallback. This - * pointer must not be \c NULL. - * \param client_data This value will be supplied to callbacks in their - * \a client_data argument. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__StreamDecoderInitStatus - * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; - * see FLAC__StreamDecoderInitStatus for the meanings of other return values. - */ -FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream( - FLAC__StreamDecoder *decoder, - FLAC__StreamDecoderReadCallback read_callback, - FLAC__StreamDecoderSeekCallback seek_callback, - FLAC__StreamDecoderTellCallback tell_callback, - FLAC__StreamDecoderLengthCallback length_callback, - FLAC__StreamDecoderEofCallback eof_callback, - FLAC__StreamDecoderWriteCallback write_callback, - FLAC__StreamDecoderMetadataCallback metadata_callback, - FLAC__StreamDecoderErrorCallback error_callback, - void *client_data -); - -/** Initialize the decoder instance to decode Ogg FLAC streams. - * - * This flavor of initialization sets up the decoder to decode from a - * FLAC stream in an Ogg container. I/O is performed via callbacks to the - * client. For decoding from a plain file via filename or open FILE*, - * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE() - * provide a simpler interface. - * - * This function should be called after FLAC__stream_decoder_new() and - * FLAC__stream_decoder_set_*() but before any of the - * FLAC__stream_decoder_process_*() functions. Will set and return the - * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA - * if initialization succeeded. - * - * \note Support for Ogg FLAC in the library is optional. If this - * library has been built without support for Ogg FLAC, this function - * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER. - * - * \param decoder An uninitialized decoder instance. - * \param read_callback See FLAC__StreamDecoderReadCallback. This - * pointer must not be \c NULL. - * \param seek_callback See FLAC__StreamDecoderSeekCallback. This - * pointer may be \c NULL if seeking is not - * supported. If \a seek_callback is not \c NULL then a - * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied. - * Alternatively, a dummy seek callback that just - * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED - * may also be supplied, all though this is slightly - * less efficient for the decoder. - * \param tell_callback See FLAC__StreamDecoderTellCallback. This - * pointer may be \c NULL if not supported by the client. If - * \a seek_callback is not \c NULL then a - * \a tell_callback must also be supplied. - * Alternatively, a dummy tell callback that just - * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED - * may also be supplied, all though this is slightly - * less efficient for the decoder. - * \param length_callback See FLAC__StreamDecoderLengthCallback. This - * pointer may be \c NULL if not supported by the client. If - * \a seek_callback is not \c NULL then a - * \a length_callback must also be supplied. - * Alternatively, a dummy length callback that just - * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED - * may also be supplied, all though this is slightly - * less efficient for the decoder. - * \param eof_callback See FLAC__StreamDecoderEofCallback. This - * pointer may be \c NULL if not supported by the client. If - * \a seek_callback is not \c NULL then a - * \a eof_callback must also be supplied. - * Alternatively, a dummy length callback that just - * returns \c false - * may also be supplied, all though this is slightly - * less efficient for the decoder. - * \param write_callback See FLAC__StreamDecoderWriteCallback. This - * pointer must not be \c NULL. - * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This - * pointer may be \c NULL if the callback is not - * desired. - * \param error_callback See FLAC__StreamDecoderErrorCallback. This - * pointer must not be \c NULL. - * \param client_data This value will be supplied to callbacks in their - * \a client_data argument. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__StreamDecoderInitStatus - * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; - * see FLAC__StreamDecoderInitStatus for the meanings of other return values. - */ -FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream( - FLAC__StreamDecoder *decoder, - FLAC__StreamDecoderReadCallback read_callback, - FLAC__StreamDecoderSeekCallback seek_callback, - FLAC__StreamDecoderTellCallback tell_callback, - FLAC__StreamDecoderLengthCallback length_callback, - FLAC__StreamDecoderEofCallback eof_callback, - FLAC__StreamDecoderWriteCallback write_callback, - FLAC__StreamDecoderMetadataCallback metadata_callback, - FLAC__StreamDecoderErrorCallback error_callback, - void *client_data -); - -/** Initialize the decoder instance to decode native FLAC files. - * - * This flavor of initialization sets up the decoder to decode from a - * plain native FLAC file. For non-stdio streams, you must use - * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O. - * - * This function should be called after FLAC__stream_decoder_new() and - * FLAC__stream_decoder_set_*() but before any of the - * FLAC__stream_decoder_process_*() functions. Will set and return the - * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA - * if initialization succeeded. - * - * \param decoder An uninitialized decoder instance. - * \param file An open FLAC file. The file should have been - * opened with mode \c "rb" and rewound. The file - * becomes owned by the decoder and should not be - * manipulated by the client while decoding. - * Unless \a file is \c stdin, it will be closed - * when FLAC__stream_decoder_finish() is called. - * Note however that seeking will not work when - * decoding from \c stdin since it is not seekable. - * \param write_callback See FLAC__StreamDecoderWriteCallback. This - * pointer must not be \c NULL. - * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This - * pointer may be \c NULL if the callback is not - * desired. - * \param error_callback See FLAC__StreamDecoderErrorCallback. This - * pointer must not be \c NULL. - * \param client_data This value will be supplied to callbacks in their - * \a client_data argument. - * \assert - * \code decoder != NULL \endcode - * \code file != NULL \endcode - * \retval FLAC__StreamDecoderInitStatus - * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; - * see FLAC__StreamDecoderInitStatus for the meanings of other return values. - */ -FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE( - FLAC__StreamDecoder *decoder, - FILE *file, - FLAC__StreamDecoderWriteCallback write_callback, - FLAC__StreamDecoderMetadataCallback metadata_callback, - FLAC__StreamDecoderErrorCallback error_callback, - void *client_data -); - -/** Initialize the decoder instance to decode Ogg FLAC files. - * - * This flavor of initialization sets up the decoder to decode from a - * plain Ogg FLAC file. For non-stdio streams, you must use - * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O. - * - * This function should be called after FLAC__stream_decoder_new() and - * FLAC__stream_decoder_set_*() but before any of the - * FLAC__stream_decoder_process_*() functions. Will set and return the - * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA - * if initialization succeeded. - * - * \note Support for Ogg FLAC in the library is optional. If this - * library has been built without support for Ogg FLAC, this function - * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER. - * - * \param decoder An uninitialized decoder instance. - * \param file An open FLAC file. The file should have been - * opened with mode \c "rb" and rewound. The file - * becomes owned by the decoder and should not be - * manipulated by the client while decoding. - * Unless \a file is \c stdin, it will be closed - * when FLAC__stream_decoder_finish() is called. - * Note however that seeking will not work when - * decoding from \c stdin since it is not seekable. - * \param write_callback See FLAC__StreamDecoderWriteCallback. This - * pointer must not be \c NULL. - * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This - * pointer may be \c NULL if the callback is not - * desired. - * \param error_callback See FLAC__StreamDecoderErrorCallback. This - * pointer must not be \c NULL. - * \param client_data This value will be supplied to callbacks in their - * \a client_data argument. - * \assert - * \code decoder != NULL \endcode - * \code file != NULL \endcode - * \retval FLAC__StreamDecoderInitStatus - * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; - * see FLAC__StreamDecoderInitStatus for the meanings of other return values. - */ -FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE( - FLAC__StreamDecoder *decoder, - FILE *file, - FLAC__StreamDecoderWriteCallback write_callback, - FLAC__StreamDecoderMetadataCallback metadata_callback, - FLAC__StreamDecoderErrorCallback error_callback, - void *client_data -); - -/** Initialize the decoder instance to decode native FLAC files. - * - * This flavor of initialization sets up the decoder to decode from a plain - * native FLAC file. If POSIX fopen() semantics are not sufficient, (for - * example, with Unicode filenames on Windows), you must use - * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream() - * and provide callbacks for the I/O. - * - * This function should be called after FLAC__stream_decoder_new() and - * FLAC__stream_decoder_set_*() but before any of the - * FLAC__stream_decoder_process_*() functions. Will set and return the - * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA - * if initialization succeeded. - * - * \param decoder An uninitialized decoder instance. - * \param filename The name of the file to decode from. The file will - * be opened with fopen(). Use \c NULL to decode from - * \c stdin. Note that \c stdin is not seekable. - * \param write_callback See FLAC__StreamDecoderWriteCallback. This - * pointer must not be \c NULL. - * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This - * pointer may be \c NULL if the callback is not - * desired. - * \param error_callback See FLAC__StreamDecoderErrorCallback. This - * pointer must not be \c NULL. - * \param client_data This value will be supplied to callbacks in their - * \a client_data argument. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__StreamDecoderInitStatus - * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; - * see FLAC__StreamDecoderInitStatus for the meanings of other return values. - */ -FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file( - FLAC__StreamDecoder *decoder, - const char *filename, - FLAC__StreamDecoderWriteCallback write_callback, - FLAC__StreamDecoderMetadataCallback metadata_callback, - FLAC__StreamDecoderErrorCallback error_callback, - void *client_data -); - -/** Initialize the decoder instance to decode Ogg FLAC files. - * - * This flavor of initialization sets up the decoder to decode from a plain - * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for - * example, with Unicode filenames on Windows), you must use - * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream() - * and provide callbacks for the I/O. - * - * This function should be called after FLAC__stream_decoder_new() and - * FLAC__stream_decoder_set_*() but before any of the - * FLAC__stream_decoder_process_*() functions. Will set and return the - * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA - * if initialization succeeded. - * - * \note Support for Ogg FLAC in the library is optional. If this - * library has been built without support for Ogg FLAC, this function - * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER. - * - * \param decoder An uninitialized decoder instance. - * \param filename The name of the file to decode from. The file will - * be opened with fopen(). Use \c NULL to decode from - * \c stdin. Note that \c stdin is not seekable. - * \param write_callback See FLAC__StreamDecoderWriteCallback. This - * pointer must not be \c NULL. - * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This - * pointer may be \c NULL if the callback is not - * desired. - * \param error_callback See FLAC__StreamDecoderErrorCallback. This - * pointer must not be \c NULL. - * \param client_data This value will be supplied to callbacks in their - * \a client_data argument. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__StreamDecoderInitStatus - * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful; - * see FLAC__StreamDecoderInitStatus for the meanings of other return values. - */ -FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file( - FLAC__StreamDecoder *decoder, - const char *filename, - FLAC__StreamDecoderWriteCallback write_callback, - FLAC__StreamDecoderMetadataCallback metadata_callback, - FLAC__StreamDecoderErrorCallback error_callback, - void *client_data -); - -/** Finish the decoding process. - * Flushes the decoding buffer, releases resources, resets the decoder - * settings to their defaults, and returns the decoder state to - * FLAC__STREAM_DECODER_UNINITIALIZED. - * - * In the event of a prematurely-terminated decode, it is not strictly - * necessary to call this immediately before FLAC__stream_decoder_delete() - * but it is good practice to match every FLAC__stream_decoder_init_*() - * with a FLAC__stream_decoder_finish(). - * - * \param decoder An uninitialized decoder instance. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c false if MD5 checking is on AND a STREAMINFO block was available - * AND the MD5 signature in the STREAMINFO block was non-zero AND the - * signature does not match the one computed by the decoder; else - * \c true. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder); - -/** Flush the stream input. - * The decoder's input buffer will be cleared and the state set to - * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn - * off MD5 checking. - * - * \param decoder A decoder instance. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c true if successful, else \c false if a memory allocation - * error occurs (in which case the state will be set to - * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR). - */ -FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder); - -/** Reset the decoding process. - * The decoder's input buffer will be cleared and the state set to - * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to - * FLAC__stream_decoder_finish() except that the settings are - * preserved; there is no need to call FLAC__stream_decoder_init_*() - * before decoding again. MD5 checking will be restored to its original - * setting. - * - * If the decoder is seekable, or was initialized with - * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(), - * the decoder will also attempt to seek to the beginning of the file. - * If this rewind fails, this function will return \c false. It follows - * that FLAC__stream_decoder_reset() cannot be used when decoding from - * \c stdin. - * - * If the decoder was initialized with FLAC__stream_encoder_init*_stream() - * and is not seekable (i.e. no seek callback was provided or the seek - * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it - * is the duty of the client to start feeding data from the beginning of - * the stream on the next FLAC__stream_decoder_process_*() call. - * - * \param decoder A decoder instance. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c true if successful, else \c false if a memory allocation occurs - * (in which case the state will be set to - * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error - * occurs (the state will be unchanged). - */ -FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder); - -/** Decode one metadata block or audio frame. - * This version instructs the decoder to decode a either a single metadata - * block or a single frame and stop, unless the callbacks return a fatal - * error or the read callback returns - * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM. - * - * As the decoder needs more input it will call the read callback. - * Depending on what was decoded, the metadata or write callback will be - * called with the decoded metadata block or audio frame. - * - * Unless there is a fatal read error or end of stream, this function - * will return once one whole frame is decoded. In other words, if the - * stream is not synchronized or points to a corrupt frame header, the - * decoder will continue to try and resync until it gets to a valid - * frame, then decode one frame, then return. If the decoder points to - * a frame whose frame CRC in the frame footer does not match the - * computed frame CRC, this function will issue a - * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the - * error callback, and return, having decoded one complete, although - * corrupt, frame. (Such corrupted frames are sent as silence of the - * correct length to the write callback.) - * - * \param decoder An initialized decoder instance. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c false if any fatal read, write, or memory allocation error - * occurred (meaning decoding must stop), else \c true; for more - * information about the decoder, check the decoder state with - * FLAC__stream_decoder_get_state(). - */ -FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder); - -/** Decode until the end of the metadata. - * This version instructs the decoder to decode from the current position - * and continue until all the metadata has been read, or until the - * callbacks return a fatal error or the read callback returns - * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM. - * - * As the decoder needs more input it will call the read callback. - * As each metadata block is decoded, the metadata callback will be called - * with the decoded metadata. - * - * \param decoder An initialized decoder instance. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c false if any fatal read, write, or memory allocation error - * occurred (meaning decoding must stop), else \c true; for more - * information about the decoder, check the decoder state with - * FLAC__stream_decoder_get_state(). - */ -FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder); - -/** Decode until the end of the stream. - * This version instructs the decoder to decode from the current position - * and continue until the end of stream (the read callback returns - * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the - * callbacks return a fatal error. - * - * As the decoder needs more input it will call the read callback. - * As each metadata block and frame is decoded, the metadata or write - * callback will be called with the decoded metadata or frame. - * - * \param decoder An initialized decoder instance. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c false if any fatal read, write, or memory allocation error - * occurred (meaning decoding must stop), else \c true; for more - * information about the decoder, check the decoder state with - * FLAC__stream_decoder_get_state(). - */ -FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder); - -/** Skip one audio frame. - * This version instructs the decoder to 'skip' a single frame and stop, - * unless the callbacks return a fatal error or the read callback returns - * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM. - * - * The decoding flow is the same as what occurs when - * FLAC__stream_decoder_process_single() is called to process an audio - * frame, except that this function does not decode the parsed data into - * PCM or call the write callback. The integrity of the frame is still - * checked the same way as in the other process functions. - * - * This function will return once one whole frame is skipped, in the - * same way that FLAC__stream_decoder_process_single() will return once - * one whole frame is decoded. - * - * This function can be used in more quickly determining FLAC frame - * boundaries when decoding of the actual data is not needed, for - * example when an application is separating a FLAC stream into frames - * for editing or storing in a container. To do this, the application - * can use FLAC__stream_decoder_skip_single_frame() to quickly advance - * to the next frame, then use - * FLAC__stream_decoder_get_decode_position() to find the new frame - * boundary. - * - * This function should only be called when the stream has advanced - * past all the metadata, otherwise it will return \c false. - * - * \param decoder An initialized decoder instance not in a metadata - * state. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c false if any fatal read, write, or memory allocation error - * occurred (meaning decoding must stop), or if the decoder - * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or - * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more - * information about the decoder, check the decoder state with - * FLAC__stream_decoder_get_state(). - */ -FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder); - -/** Flush the input and seek to an absolute sample. - * Decoding will resume at the given sample. Note that because of - * this, the next write callback may contain a partial block. The - * client must support seeking the input or this function will fail - * and return \c false. Furthermore, if the decoder state is - * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed - * with FLAC__stream_decoder_flush() or reset with - * FLAC__stream_decoder_reset() before decoding can continue. - * - * \param decoder A decoder instance. - * \param sample The target sample number to seek to. - * \assert - * \code decoder != NULL \endcode - * \retval FLAC__bool - * \c true if successful, else \c false. - */ -FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample); - -/* \} */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libs/include/FLAC/stream_encoder.h b/libs/include/FLAC/stream_encoder.h deleted file mode 100644 index d154ac43..00000000 --- a/libs/include/FLAC/stream_encoder.h +++ /dev/null @@ -1,1790 +0,0 @@ -/* libFLAC - Free Lossless Audio Codec library - * Copyright (C) 2000-2009 Josh Coalson - * Copyright (C) 2011-2016 Xiph.Org Foundation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of the Xiph.org Foundation nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FLAC__STREAM_ENCODER_H -#define FLAC__STREAM_ENCODER_H - -#include /* for FILE */ -#include "export.h" -#include "format.h" -#include "stream_decoder.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -/** \file include/FLAC/stream_encoder.h - * - * \brief - * This module contains the functions which implement the stream - * encoder. - * - * See the detailed documentation in the - * \link flac_stream_encoder stream encoder \endlink module. - */ - -/** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces - * \ingroup flac - * - * \brief - * This module describes the encoder layers provided by libFLAC. - * - * The stream encoder can be used to encode complete streams either to the - * client via callbacks, or directly to a file, depending on how it is - * initialized. When encoding via callbacks, the client provides a write - * callback which will be called whenever FLAC data is ready to be written. - * If the client also supplies a seek callback, the encoder will also - * automatically handle the writing back of metadata discovered while - * encoding, like stream info, seek points offsets, etc. When encoding to - * a file, the client needs only supply a filename or open \c FILE* and an - * optional progress callback for periodic notification of progress; the - * write and seek callbacks are supplied internally. For more info see the - * \link flac_stream_encoder stream encoder \endlink module. - */ - -/** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface - * \ingroup flac_encoder - * - * \brief - * This module contains the functions which implement the stream - * encoder. - * - * The stream encoder can encode to native FLAC, and optionally Ogg FLAC - * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files. - * - * The basic usage of this encoder is as follows: - * - The program creates an instance of an encoder using - * FLAC__stream_encoder_new(). - * - The program overrides the default settings using - * FLAC__stream_encoder_set_*() functions. At a minimum, the following - * functions should be called: - * - FLAC__stream_encoder_set_channels() - * - FLAC__stream_encoder_set_bits_per_sample() - * - FLAC__stream_encoder_set_sample_rate() - * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC) - * - FLAC__stream_encoder_set_total_samples_estimate() (if known) - * - If the application wants to control the compression level or set its own - * metadata, then the following should also be called: - * - FLAC__stream_encoder_set_compression_level() - * - FLAC__stream_encoder_set_verify() - * - FLAC__stream_encoder_set_metadata() - * - The rest of the set functions should only be called if the client needs - * exact control over how the audio is compressed; thorough understanding - * of the FLAC format is necessary to achieve good results. - * - The program initializes the instance to validate the settings and - * prepare for encoding using - * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE() - * or FLAC__stream_encoder_init_file() for native FLAC - * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE() - * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC - * - The program calls FLAC__stream_encoder_process() or - * FLAC__stream_encoder_process_interleaved() to encode data, which - * subsequently calls the callbacks when there is encoder data ready - * to be written. - * - The program finishes the encoding with FLAC__stream_encoder_finish(), - * which causes the encoder to encode any data still in its input pipe, - * update the metadata with the final encoding statistics if output - * seeking is possible, and finally reset the encoder to the - * uninitialized state. - * - The instance may be used again or deleted with - * FLAC__stream_encoder_delete(). - * - * In more detail, the stream encoder functions similarly to the - * \link flac_stream_decoder stream decoder \endlink, but has fewer - * callbacks and more options. Typically the client will create a new - * instance by calling FLAC__stream_encoder_new(), then set the necessary - * parameters with FLAC__stream_encoder_set_*(), and initialize it by - * calling one of the FLAC__stream_encoder_init_*() functions. - * - * Unlike the decoders, the stream encoder has many options that can - * affect the speed and compression ratio. When setting these parameters - * you should have some basic knowledge of the format (see the - * user-level documentation - * or the formal description). The - * FLAC__stream_encoder_set_*() functions themselves do not validate the - * values as many are interdependent. The FLAC__stream_encoder_init_*() - * functions will do this, so make sure to pay attention to the state - * returned by FLAC__stream_encoder_init_*() to make sure that it is - * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set - * before FLAC__stream_encoder_init_*() will take on the defaults from - * the constructor. - * - * There are three initialization functions for native FLAC, one for - * setting up the encoder to encode FLAC data to the client via - * callbacks, and two for encoding directly to a file. - * - * For encoding via callbacks, use FLAC__stream_encoder_init_stream(). - * You must also supply a write callback which will be called anytime - * there is raw encoded data to write. If the client can seek the output - * it is best to also supply seek and tell callbacks, as this allows the - * encoder to go back after encoding is finished to write back - * information that was collected while encoding, like seek point offsets, - * frame sizes, etc. - * - * For encoding directly to a file, use FLAC__stream_encoder_init_FILE() - * or FLAC__stream_encoder_init_file(). Then you must only supply a - * filename or open \c FILE*; the encoder will handle all the callbacks - * internally. You may also supply a progress callback for periodic - * notification of the encoding progress. - * - * There are three similarly-named init functions for encoding to Ogg - * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the - * library has been built with Ogg support. - * - * The call to FLAC__stream_encoder_init_*() currently will also immediately - * call the write callback several times, once with the \c fLaC signature, - * and once for each encoded metadata block. Note that for Ogg FLAC - * encoding you will usually get at least twice the number of callbacks than - * with native FLAC, one for the Ogg page header and one for the page body. - * - * After initializing the instance, the client may feed audio data to the - * encoder in one of two ways: - * - * - Channel separate, through FLAC__stream_encoder_process() - The client - * will pass an array of pointers to buffers, one for each channel, to - * the encoder, each of the same length. The samples need not be - * block-aligned, but each channel should have the same number of samples. - * - Channel interleaved, through - * FLAC__stream_encoder_process_interleaved() - The client will pass a single - * pointer to data that is channel-interleaved (i.e. channel0_sample0, - * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...). - * Again, the samples need not be block-aligned but they must be - * sample-aligned, i.e. the first value should be channel0_sample0 and - * the last value channelN_sampleM. - * - * Note that for either process call, each sample in the buffers should be a - * signed integer, right-justified to the resolution set by - * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution - * is 16 bits per sample, the samples should all be in the range [-32768,32767]. - * - * When the client is finished encoding data, it calls - * FLAC__stream_encoder_finish(), which causes the encoder to encode any - * data still in its input pipe, and call the metadata callback with the - * final encoding statistics. Then the instance may be deleted with - * FLAC__stream_encoder_delete() or initialized again to encode another - * stream. - * - * For programs that write their own metadata, but that do not know the - * actual metadata until after encoding, it is advantageous to instruct - * the encoder to write a PADDING block of the correct size, so that - * instead of rewriting the whole stream after encoding, the program can - * just overwrite the PADDING block. If only the maximum size of the - * metadata is known, the program can write a slightly larger padding - * block, then split it after encoding. - * - * Make sure you understand how lengths are calculated. All FLAC metadata - * blocks have a 4 byte header which contains the type and length. This - * length does not include the 4 bytes of the header. See the format page - * for the specification of metadata blocks and their lengths. - * - * \note - * If you are writing the FLAC data to a file via callbacks, make sure it - * is open for update (e.g. mode "w+" for stdio streams). This is because - * after the first encoding pass, the encoder will try to seek back to the - * beginning of the stream, to the STREAMINFO block, to write some data - * there. (If using FLAC__stream_encoder_init*_file() or - * FLAC__stream_encoder_init*_FILE(), the file is managed internally.) - * - * \note - * The "set" functions may only be called when the encoder is in the - * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after - * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but - * before FLAC__stream_encoder_init_*(). If this is the case they will - * return \c true, otherwise \c false. - * - * \note - * FLAC__stream_encoder_finish() resets all settings to the constructor - * defaults. - * - * \{ - */ - - -/** State values for a FLAC__StreamEncoder. - * - * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state(). - * - * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK - * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and - * must be deleted with FLAC__stream_encoder_delete(). - */ -typedef enum { - - FLAC__STREAM_ENCODER_OK = 0, - /**< The encoder is in the normal OK state and samples can be processed. */ - - FLAC__STREAM_ENCODER_UNINITIALIZED, - /**< The encoder is in the uninitialized state; one of the - * FLAC__stream_encoder_init_*() functions must be called before samples - * can be processed. - */ - - FLAC__STREAM_ENCODER_OGG_ERROR, - /**< An error occurred in the underlying Ogg layer. */ - - FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR, - /**< An error occurred in the underlying verify stream decoder; - * check FLAC__stream_encoder_get_verify_decoder_state(). - */ - - FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA, - /**< The verify decoder detected a mismatch between the original - * audio signal and the decoded audio signal. - */ - - FLAC__STREAM_ENCODER_CLIENT_ERROR, - /**< One of the callbacks returned a fatal error. */ - - FLAC__STREAM_ENCODER_IO_ERROR, - /**< An I/O error occurred while opening/reading/writing a file. - * Check \c errno. - */ - - FLAC__STREAM_ENCODER_FRAMING_ERROR, - /**< An error occurred while writing the stream; usually, the - * write_callback returned an error. - */ - - FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR - /**< Memory allocation failed. */ - -} FLAC__StreamEncoderState; - -/** Maps a FLAC__StreamEncoderState to a C string. - * - * Using a FLAC__StreamEncoderState as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamEncoderStateString[]; - - -/** Possible return values for the FLAC__stream_encoder_init_*() functions. - */ -typedef enum { - - FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0, - /**< Initialization was successful. */ - - FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR, - /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */ - - FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER, - /**< The library was not compiled with support for the given container - * format. - */ - - FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS, - /**< A required callback was not supplied. */ - - FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS, - /**< The encoder has an invalid setting for number of channels. */ - - FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE, - /**< The encoder has an invalid setting for bits-per-sample. - * FLAC supports 4-32 bps but the reference encoder currently supports - * only up to 24 bps. - */ - - FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE, - /**< The encoder has an invalid setting for the input sample rate. */ - - FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE, - /**< The encoder has an invalid setting for the block size. */ - - FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER, - /**< The encoder has an invalid setting for the maximum LPC order. */ - - FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION, - /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */ - - FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER, - /**< The specified block size is less than the maximum LPC order. */ - - FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE, - /**< The encoder is bound to the Subset but other settings violate it. */ - - FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA, - /**< The metadata input to the encoder is invalid, in one of the following ways: - * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0 - * - One of the metadata blocks contains an undefined type - * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal() - * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal() - * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block - */ - - FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED - /**< FLAC__stream_encoder_init_*() was called when the encoder was - * already initialized, usually because - * FLAC__stream_encoder_finish() was not called. - */ - -} FLAC__StreamEncoderInitStatus; - -/** Maps a FLAC__StreamEncoderInitStatus to a C string. - * - * Using a FLAC__StreamEncoderInitStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[]; - - -/** Return values for the FLAC__StreamEncoder read callback. - */ -typedef enum { - - FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE, - /**< The read was OK and decoding can continue. */ - - FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM, - /**< The read was attempted at the end of the stream. */ - - FLAC__STREAM_ENCODER_READ_STATUS_ABORT, - /**< An unrecoverable error occurred. */ - - FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED - /**< Client does not support reading back from the output. */ - -} FLAC__StreamEncoderReadStatus; - -/** Maps a FLAC__StreamEncoderReadStatus to a C string. - * - * Using a FLAC__StreamEncoderReadStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[]; - - -/** Return values for the FLAC__StreamEncoder write callback. - */ -typedef enum { - - FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0, - /**< The write was OK and encoding can continue. */ - - FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR - /**< An unrecoverable error occurred. The encoder will return from the process call. */ - -} FLAC__StreamEncoderWriteStatus; - -/** Maps a FLAC__StreamEncoderWriteStatus to a C string. - * - * Using a FLAC__StreamEncoderWriteStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[]; - - -/** Return values for the FLAC__StreamEncoder seek callback. - */ -typedef enum { - - FLAC__STREAM_ENCODER_SEEK_STATUS_OK, - /**< The seek was OK and encoding can continue. */ - - FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR, - /**< An unrecoverable error occurred. */ - - FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED - /**< Client does not support seeking. */ - -} FLAC__StreamEncoderSeekStatus; - -/** Maps a FLAC__StreamEncoderSeekStatus to a C string. - * - * Using a FLAC__StreamEncoderSeekStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[]; - - -/** Return values for the FLAC__StreamEncoder tell callback. - */ -typedef enum { - - FLAC__STREAM_ENCODER_TELL_STATUS_OK, - /**< The tell was OK and encoding can continue. */ - - FLAC__STREAM_ENCODER_TELL_STATUS_ERROR, - /**< An unrecoverable error occurred. */ - - FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED - /**< Client does not support seeking. */ - -} FLAC__StreamEncoderTellStatus; - -/** Maps a FLAC__StreamEncoderTellStatus to a C string. - * - * Using a FLAC__StreamEncoderTellStatus as the index to this array - * will give the string equivalent. The contents should not be modified. - */ -extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[]; - - -/*********************************************************************** - * - * class FLAC__StreamEncoder - * - ***********************************************************************/ - -struct FLAC__StreamEncoderProtected; -struct FLAC__StreamEncoderPrivate; -/** The opaque structure definition for the stream encoder type. - * See the \link flac_stream_encoder stream encoder module \endlink - * for a detailed description. - */ -typedef struct { - struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */ - struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */ -} FLAC__StreamEncoder; - -/** Signature for the read callback. - * - * A function pointer matching this signature must be passed to - * FLAC__stream_encoder_init_ogg_stream() if seeking is supported. - * The supplied function will be called when the encoder needs to read back - * encoded data. This happens during the metadata callback, when the encoder - * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered - * while encoding. The address of the buffer to be filled is supplied, along - * with the number of bytes the buffer can hold. The callback may choose to - * supply less data and modify the byte count but must be careful not to - * overflow the buffer. The callback then returns a status code chosen from - * FLAC__StreamEncoderReadStatus. - * - * Here is an example of a read callback for stdio streams: - * \code - * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data) - * { - * FILE *file = ((MyClientData*)client_data)->file; - * if(*bytes > 0) { - * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file); - * if(ferror(file)) - * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT; - * else if(*bytes == 0) - * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM; - * else - * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE; - * } - * else - * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT; - * } - * \endcode - * - * \note In general, FLAC__StreamEncoder functions which change the - * state should not be called on the \a encoder while in the callback. - * - * \param encoder The encoder instance calling the callback. - * \param buffer A pointer to a location for the callee to store - * data to be encoded. - * \param bytes A pointer to the size of the buffer. On entry - * to the callback, it contains the maximum number - * of bytes that may be stored in \a buffer. The - * callee must set it to the actual number of bytes - * stored (0 in case of error or end-of-stream) before - * returning. - * \param client_data The callee's client data set through - * FLAC__stream_encoder_set_client_data(). - * \retval FLAC__StreamEncoderReadStatus - * The callee's return status. - */ -typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data); - -/** Signature for the write callback. - * - * A function pointer matching this signature must be passed to - * FLAC__stream_encoder_init*_stream(). The supplied function will be called - * by the encoder anytime there is raw encoded data ready to write. It may - * include metadata mixed with encoded audio frames and the data is not - * guaranteed to be aligned on frame or metadata block boundaries. - * - * The only duty of the callback is to write out the \a bytes worth of data - * in \a buffer to the current position in the output stream. The arguments - * \a samples and \a current_frame are purely informational. If \a samples - * is greater than \c 0, then \a current_frame will hold the current frame - * number that is being written; otherwise it indicates that the write - * callback is being called to write metadata. - * - * \note - * Unlike when writing to native FLAC, when writing to Ogg FLAC the - * write callback will be called twice when writing each audio - * frame; once for the page header, and once for the page body. - * When writing the page header, the \a samples argument to the - * write callback will be \c 0. - * - * \note In general, FLAC__StreamEncoder functions which change the - * state should not be called on the \a encoder while in the callback. - * - * \param encoder The encoder instance calling the callback. - * \param buffer An array of encoded data of length \a bytes. - * \param bytes The byte length of \a buffer. - * \param samples The number of samples encoded by \a buffer. - * \c 0 has a special meaning; see above. - * \param current_frame The number of the current frame being encoded. - * \param client_data The callee's client data set through - * FLAC__stream_encoder_init_*(). - * \retval FLAC__StreamEncoderWriteStatus - * The callee's return status. - */ -typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, uint32_t samples, uint32_t current_frame, void *client_data); - -/** Signature for the seek callback. - * - * A function pointer matching this signature may be passed to - * FLAC__stream_encoder_init*_stream(). The supplied function will be called - * when the encoder needs to seek the output stream. The encoder will pass - * the absolute byte offset to seek to, 0 meaning the beginning of the stream. - * - * Here is an example of a seek callback for stdio streams: - * \code - * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data) - * { - * FILE *file = ((MyClientData*)client_data)->file; - * if(file == stdin) - * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED; - * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0) - * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR; - * else - * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK; - * } - * \endcode - * - * \note In general, FLAC__StreamEncoder functions which change the - * state should not be called on the \a encoder while in the callback. - * - * \param encoder The encoder instance calling the callback. - * \param absolute_byte_offset The offset from the beginning of the stream - * to seek to. - * \param client_data The callee's client data set through - * FLAC__stream_encoder_init_*(). - * \retval FLAC__StreamEncoderSeekStatus - * The callee's return status. - */ -typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data); - -/** Signature for the tell callback. - * - * A function pointer matching this signature may be passed to - * FLAC__stream_encoder_init*_stream(). The supplied function will be called - * when the encoder needs to know the current position of the output stream. - * - * \warning - * The callback must return the true current byte offset of the output to - * which the encoder is writing. If you are buffering the output, make - * sure and take this into account. If you are writing directly to a - * FILE* from your write callback, ftell() is sufficient. If you are - * writing directly to a file descriptor from your write callback, you - * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to - * these points to rewrite metadata after encoding. - * - * Here is an example of a tell callback for stdio streams: - * \code - * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data) - * { - * FILE *file = ((MyClientData*)client_data)->file; - * off_t pos; - * if(file == stdin) - * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED; - * else if((pos = ftello(file)) < 0) - * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR; - * else { - * *absolute_byte_offset = (FLAC__uint64)pos; - * return FLAC__STREAM_ENCODER_TELL_STATUS_OK; - * } - * } - * \endcode - * - * \note In general, FLAC__StreamEncoder functions which change the - * state should not be called on the \a encoder while in the callback. - * - * \param encoder The encoder instance calling the callback. - * \param absolute_byte_offset The address at which to store the current - * position of the output. - * \param client_data The callee's client data set through - * FLAC__stream_encoder_init_*(). - * \retval FLAC__StreamEncoderTellStatus - * The callee's return status. - */ -typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data); - -/** Signature for the metadata callback. - * - * A function pointer matching this signature may be passed to - * FLAC__stream_encoder_init*_stream(). The supplied function will be called - * once at the end of encoding with the populated STREAMINFO structure. This - * is so the client can seek back to the beginning of the file and write the - * STREAMINFO block with the correct statistics after encoding (like - * minimum/maximum frame size and total samples). - * - * \note In general, FLAC__StreamEncoder functions which change the - * state should not be called on the \a encoder while in the callback. - * - * \param encoder The encoder instance calling the callback. - * \param metadata The final populated STREAMINFO block. - * \param client_data The callee's client data set through - * FLAC__stream_encoder_init_*(). - */ -typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data); - -/** Signature for the progress callback. - * - * A function pointer matching this signature may be passed to - * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE(). - * The supplied function will be called when the encoder has finished - * writing a frame. The \c total_frames_estimate argument to the - * callback will be based on the value from - * FLAC__stream_encoder_set_total_samples_estimate(). - * - * \note In general, FLAC__StreamEncoder functions which change the - * state should not be called on the \a encoder while in the callback. - * - * \param encoder The encoder instance calling the callback. - * \param bytes_written Bytes written so far. - * \param samples_written Samples written so far. - * \param frames_written Frames written so far. - * \param total_frames_estimate The estimate of the total number of - * frames to be written. - * \param client_data The callee's client data set through - * FLAC__stream_encoder_init_*(). - */ -typedef void (*FLAC__StreamEncoderProgressCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, uint32_t frames_written, uint32_t total_frames_estimate, void *client_data); - - -/*********************************************************************** - * - * Class constructor/destructor - * - ***********************************************************************/ - -/** Create a new stream encoder instance. The instance is created with - * default settings; see the individual FLAC__stream_encoder_set_*() - * functions for each setting's default. - * - * \retval FLAC__StreamEncoder* - * \c NULL if there was an error allocating memory, else the new instance. - */ -FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void); - -/** Free an encoder instance. Deletes the object pointed to by \a encoder. - * - * \param encoder A pointer to an existing encoder. - * \assert - * \code encoder != NULL \endcode - */ -FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder); - - -/*********************************************************************** - * - * Public class method prototypes - * - ***********************************************************************/ - -/** Set the serial number for the FLAC stream to use in the Ogg container. - * - * \note - * This does not need to be set for native FLAC encoding. - * - * \note - * It is recommended to set a serial number explicitly as the default of '0' - * may collide with other streams. - * - * \default \c 0 - * \param encoder An encoder instance to set. - * \param serial_number See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number); - -/** Set the "verify" flag. If \c true, the encoder will verify it's own - * encoded output by feeding it through an internal decoder and comparing - * the original signal against the decoded signal. If a mismatch occurs, - * the process call will return \c false. Note that this will slow the - * encoding process by the extra time required for decoding and comparison. - * - * \default \c false - * \param encoder An encoder instance to set. - * \param value Flag value (see above). - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value); - -/** Set the Subset flag. If \c true, - * the encoder will comply with the Subset and will check the - * settings during FLAC__stream_encoder_init_*() to see if all settings - * comply. If \c false, the settings may take advantage of the full - * range that the format allows. - * - * Make sure you know what it entails before setting this to \c false. - * - * \default \c true - * \param encoder An encoder instance to set. - * \param value Flag value (see above). - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value); - -/** Set the number of channels to be encoded. - * - * \default \c 2 - * \param encoder An encoder instance to set. - * \param value See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, uint32_t value); - -/** Set the sample resolution of the input to be encoded. - * - * \warning - * Do not feed the encoder data that is wider than the value you - * set here or you will generate an invalid stream. - * - * \default \c 16 - * \param encoder An encoder instance to set. - * \param value See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, uint32_t value); - -/** Set the sample rate (in Hz) of the input to be encoded. - * - * \default \c 44100 - * \param encoder An encoder instance to set. - * \param value See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, uint32_t value); - -/** Set the compression level - * - * The compression level is roughly proportional to the amount of effort - * the encoder expends to compress the file. A higher level usually - * means more computation but higher compression. The default level is - * suitable for most applications. - * - * Currently the levels range from \c 0 (fastest, least compression) to - * \c 8 (slowest, most compression). A value larger than \c 8 will be - * treated as \c 8. - * - * This function automatically calls the following other \c _set_ - * functions with appropriate values, so the client does not need to - * unless it specifically wants to override them: - * - FLAC__stream_encoder_set_do_mid_side_stereo() - * - FLAC__stream_encoder_set_loose_mid_side_stereo() - * - FLAC__stream_encoder_set_apodization() - * - FLAC__stream_encoder_set_max_lpc_order() - * - FLAC__stream_encoder_set_qlp_coeff_precision() - * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search() - * - FLAC__stream_encoder_set_do_escape_coding() - * - FLAC__stream_encoder_set_do_exhaustive_model_search() - * - FLAC__stream_encoder_set_min_residual_partition_order() - * - FLAC__stream_encoder_set_max_residual_partition_order() - * - FLAC__stream_encoder_set_rice_parameter_search_dist() - * - * The actual values set for each level are: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
leveldo mid-side stereoloose mid-side stereoapodizationmax lpc orderqlp coeff precisionqlp coeff prec searchescape codingexhaustive model searchmin residual partition ordermax residual partition orderrice parameter search dist
0 false false tukey(0.5) 0 0 false false false 0 3 0
1 true true tukey(0.5) 0 0 false false false 0 3 0
2 true false tukey(0.5) 0 0 false false false 0 3 0
3 false false tukey(0.5) 6 0 false false false 0 4 0
4 true true tukey(0.5) 8 0 false false false 0 4 0
5 true false tukey(0.5) 8 0 false false false 0 5 0
6 true false tukey(0.5);partial_tukey(2) 8 0 false false false 0 6 0
7 true false tukey(0.5);partial_tukey(2) 12 0 false false false 0 6 0
8 true false tukey(0.5);partial_tukey(2);punchout_tukey(3) 12 0 false false false 0 6 0
- * - * \default \c 5 - * \param encoder An encoder instance to set. - * \param value See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, uint32_t value); - -/** Set the blocksize to use while encoding. - * - * The number of samples to use per frame. Use \c 0 to let the encoder - * estimate a blocksize; this is usually best. - * - * \default \c 0 - * \param encoder An encoder instance to set. - * \param value See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, uint32_t value); - -/** Set to \c true to enable mid-side encoding on stereo input. The - * number of channels must be 2 for this to have any effect. Set to - * \c false to use only independent channel coding. - * - * \default \c true - * \param encoder An encoder instance to set. - * \param value Flag value (see above). - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value); - -/** Set to \c true to enable adaptive switching between mid-side and - * left-right encoding on stereo input. Set to \c false to use - * exhaustive searching. Setting this to \c true requires - * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to - * \c true in order to have any effect. - * - * \default \c false - * \param encoder An encoder instance to set. - * \param value Flag value (see above). - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value); - -/** Sets the apodization function(s) the encoder will use when windowing - * audio data for LPC analysis. - * - * The \a specification is a plain ASCII string which specifies exactly - * which functions to use. There may be more than one (up to 32), - * separated by \c ';' characters. Some functions take one or more - * comma-separated arguments in parentheses. - * - * The available functions are \c bartlett, \c bartlett_hann, - * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop, - * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall, - * \c rectangle, \c triangle, \c tukey(P), \c partial_tukey(n[/ov[/P]]), - * \c punchout_tukey(n[/ov[/P]]), \c welch. - * - * For \c gauss(STDDEV), STDDEV specifies the standard deviation - * (0blocksize / (2 ^ order). - * - * Set both min and max values to \c 0 to force a single context, - * whose Rice parameter is based on the residual signal variance. - * Otherwise, set a min and max order, and the encoder will search - * all orders, using the mean of each context for its Rice parameter, - * and use the best. - * - * \default \c 0 - * \param encoder An encoder instance to set. - * \param value See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, uint32_t value); - -/** Set the maximum partition order to search when coding the residual. - * This is used in tandem with - * FLAC__stream_encoder_set_min_residual_partition_order(). - * - * The partition order determines the context size in the residual. - * The context size will be approximately blocksize / (2 ^ order). - * - * Set both min and max values to \c 0 to force a single context, - * whose Rice parameter is based on the residual signal variance. - * Otherwise, set a min and max order, and the encoder will search - * all orders, using the mean of each context for its Rice parameter, - * and use the best. - * - * \default \c 5 - * \param encoder An encoder instance to set. - * \param value See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, uint32_t value); - -/** Deprecated. Setting this value has no effect. - * - * \default \c 0 - * \param encoder An encoder instance to set. - * \param value See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, uint32_t value); - -/** Set an estimate of the total samples that will be encoded. - * This is merely an estimate and may be set to \c 0 if unknown. - * This value will be written to the STREAMINFO block before encoding, - * and can remove the need for the caller to rewrite the value later - * if the value is known before encoding. - * - * \default \c 0 - * \param encoder An encoder instance to set. - * \param value See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value); - -/** Set the metadata blocks to be emitted to the stream before encoding. - * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an - * array of pointers to metadata blocks. The array is non-const since - * the encoder may need to change the \a is_last flag inside them, and - * in some cases update seek point offsets. Otherwise, the encoder will - * not modify or free the blocks. It is up to the caller to free the - * metadata blocks after encoding finishes. - * - * \note - * The encoder stores only copies of the pointers in the \a metadata array; - * the metadata blocks themselves must survive at least until after - * FLAC__stream_encoder_finish() returns. Do not free the blocks until then. - * - * \note - * The STREAMINFO block is always written and no STREAMINFO block may - * occur in the supplied array. - * - * \note - * By default the encoder does not create a SEEKTABLE. If one is supplied - * in the \a metadata array, but the client has specified that it does not - * support seeking, then the SEEKTABLE will be written verbatim. However - * by itself this is not very useful as the client will not know the stream - * offsets for the seekpoints ahead of time. In order to get a proper - * seektable the client must support seeking. See next note. - * - * \note - * SEEKTABLE blocks are handled specially. Since you will not know - * the values for the seek point stream offsets, you should pass in - * a SEEKTABLE 'template', that is, a SEEKTABLE object with the - * required sample numbers (or placeholder points), with \c 0 for the - * \a frame_samples and \a stream_offset fields for each point. If the - * client has specified that it supports seeking by providing a seek - * callback to FLAC__stream_encoder_init_stream() or both seek AND read - * callback to FLAC__stream_encoder_init_ogg_stream() (or by using - * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()), - * then while it is encoding the encoder will fill the stream offsets in - * for you and when encoding is finished, it will seek back and write the - * real values into the SEEKTABLE block in the stream. There are helper - * routines for manipulating seektable template blocks; see metadata.h: - * FLAC__metadata_object_seektable_template_*(). If the client does - * not support seeking, the SEEKTABLE will have inaccurate offsets which - * will slow down or remove the ability to seek in the FLAC stream. - * - * \note - * The encoder instance \b will modify the first \c SEEKTABLE block - * as it transforms the template to a valid seektable while encoding, - * but it is still up to the caller to free all metadata blocks after - * encoding. - * - * \note - * A VORBIS_COMMENT block may be supplied. The vendor string in it - * will be ignored. libFLAC will use it's own vendor string. libFLAC - * will not modify the passed-in VORBIS_COMMENT's vendor string, it - * will simply write it's own into the stream. If no VORBIS_COMMENT - * block is present in the \a metadata array, libFLAC will write an - * empty one, containing only the vendor string. - * - * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be - * the second metadata block of the stream. The encoder already supplies - * the STREAMINFO block automatically. If \a metadata does not contain a - * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if - * \a metadata does contain a VORBIS_COMMENT block and it is not the - * first, the init function will reorder \a metadata by moving the - * VORBIS_COMMENT block to the front; the relative ordering of the other - * blocks will remain as they were. - * - * \note The Ogg FLAC mapping limits the number of metadata blocks per - * stream to \c 65535. If \a num_blocks exceeds this the function will - * return \c false. - * - * \default \c NULL, 0 - * \param encoder An encoder instance to set. - * \param metadata See above. - * \param num_blocks See above. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * \c false if the encoder is already initialized, else \c true. - * \c false if the encoder is already initialized, or if - * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, uint32_t num_blocks); - -/** Get the current encoder state. - * - * \param encoder An encoder instance to query. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__StreamEncoderState - * The current encoder state. - */ -FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder); - -/** Get the state of the verify stream decoder. - * Useful when the stream encoder state is - * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. - * - * \param encoder An encoder instance to query. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__StreamDecoderState - * The verify stream decoder state. - */ -FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder); - -/** Get the current encoder state as a C string. - * This version automatically resolves - * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the - * verify decoder's state. - * - * \param encoder A encoder instance to query. - * \assert - * \code encoder != NULL \endcode - * \retval const char * - * The encoder state as a C string. Do not modify the contents. - */ -FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder); - -/** Get relevant values about the nature of a verify decoder error. - * Useful when the stream encoder state is - * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should - * be addresses in which the stats will be returned, or NULL if value - * is not desired. - * - * \param encoder An encoder instance to query. - * \param absolute_sample The absolute sample number of the mismatch. - * \param frame_number The number of the frame in which the mismatch occurred. - * \param channel The channel in which the mismatch occurred. - * \param sample The number of the sample (relative to the frame) in - * which the mismatch occurred. - * \param expected The expected value for the sample in question. - * \param got The actual value returned by the decoder. - * \assert - * \code encoder != NULL \endcode - */ -FLAC_API void FLAC__stream_encoder_get_verify_decoder_error_stats(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_sample, uint32_t *frame_number, uint32_t *channel, uint32_t *sample, FLAC__int32 *expected, FLAC__int32 *got); - -/** Get the "verify" flag. - * - * \param encoder An encoder instance to query. - * \assert - * \code encoder != NULL \endcode - * \retval FLAC__bool - * See FLAC__stream_encoder_set_verify(). - */ -FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder); - -/** Get the frame header. - * - * \param encoder An initialized encoder instance in the OK state. - * \param buffer An array of pointers to each channel's signal. - * \param samples The number of samples in one channel. - * \assert - * \code encoder != NULL \endcode - * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode - * \retval FLAC__bool - * \c true if successful, else \c false; in this case, check the - * encoder state with FLAC__stream_encoder_get_state() to see what - * went wrong. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], uint32_t samples); - -/** Submit data for encoding. - * This version allows you to supply the input data where the channels - * are interleaved into a single array (i.e. channel0_sample0, - * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...). - * The samples need not be block-aligned but they must be - * sample-aligned, i.e. the first value should be channel0_sample0 - * and the last value channelN_sampleM. Each sample should be a signed - * integer, right-justified to the resolution set by - * FLAC__stream_encoder_set_bits_per_sample(). For example, if the - * resolution is 16 bits per sample, the samples should all be in the - * range [-32768,32767]. - * - * For applications where channel order is important, channels must - * follow the order as described in the - * frame header. - * - * \param encoder An initialized encoder instance in the OK state. - * \param buffer An array of channel-interleaved data (see above). - * \param samples The number of samples in one channel, the same as for - * FLAC__stream_encoder_process(). For example, if - * encoding two channels, \c 1000 \a samples corresponds - * to a \a buffer of 2000 values. - * \assert - * \code encoder != NULL \endcode - * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode - * \retval FLAC__bool - * \c true if successful, else \c false; in this case, check the - * encoder state with FLAC__stream_encoder_get_state() to see what - * went wrong. - */ -FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], uint32_t samples); - -/* \} */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libs/include/dr_wav.h b/libs/include/dr_wav.h index 469f1dcf..952e6cff 100644 --- a/libs/include/dr_wav.h +++ b/libs/include/dr_wav.h @@ -1,6 +1,6 @@ /* WAV audio loader and writer. Choice of public domain or MIT-0. See license statements at the end of this file. -dr_wav - v0.13.6 - 2022-04-10 +dr_wav - v0.14.0 - TBD David Reid - mackron@gmail.com @@ -79,7 +79,9 @@ dr_wav can also be used to output WAV files. This does not currently support com drwav_uint64 framesWritten = drwav_write_pcm_frames(pWav, frameCount, pSamples); ``` -dr_wav has seamless support the Sony Wave64 format. The decoder will automatically detect it and it should Just Work without any manual intervention. +Note that writing to AIFF or RIFX is not supported. + +dr_wav has support for decoding from a number of different encapsulation formats. See below for details. Build Options @@ -92,24 +94,44 @@ Build Options #define DR_WAV_NO_STDIO Disables APIs that initialize a decoder from a file such as `drwav_init_file()`, `drwav_init_file_write()`, etc. +#define DR_WAV_NO_WCHAR + Disables all functions ending with `_w`. Use this if your compiler does not provide wchar.h. Not required if DR_WAV_NO_STDIO is also defined. + + +Supported Encapsulations +======================== +- RIFF (Regular WAV) +- RIFX (Big-Endian) +- AIFF (Does not currently support ADPCM) +- RF64 +- W64 + +Note that AIFF and RIFX do not support write mode, nor do they support reading of metadata. + + +Supported Encodings +=================== +- Unsigned 8-bit PCM +- Signed 12-bit PCM +- Signed 16-bit PCM +- Signed 24-bit PCM +- Signed 32-bit PCM +- IEEE 32-bit floating point +- IEEE 64-bit floating point +- A-law and u-law +- Microsoft ADPCM +- IMA ADPCM (DVI, format code 0x11) + +8-bit PCM encodings are always assumed to be unsigned. Signed 8-bit encoding can only be read with `drwav_read_raw()`. + +Note that ADPCM is not currently supported with AIFF. Contributions welcome. Notes ===== - Samples are always interleaved. - The default read function does not do any data conversion. Use `drwav_read_pcm_frames_f32()`, `drwav_read_pcm_frames_s32()` and `drwav_read_pcm_frames_s16()` - to read and convert audio data to 32-bit floating point, signed 32-bit integer and signed 16-bit integer samples respectively. Tested and supported internal - formats include the following: - - Unsigned 8-bit PCM - - Signed 12-bit PCM - - Signed 16-bit PCM - - Signed 24-bit PCM - - Signed 32-bit PCM - - IEEE 32-bit floating point - - IEEE 64-bit floating point - - A-law and u-law - - Microsoft ADPCM - - IMA ADPCM (DVI, format code 0x11) + to read and convert audio data to 32-bit floating point, signed 32-bit integer and signed 16-bit integer samples respectively. - dr_wav will try to read the WAV file as best it can, even if it's not strictly conformant to the WAV format. */ @@ -124,13 +146,13 @@ extern "C" { #define DRWAV_XSTRINGIFY(x) DRWAV_STRINGIFY(x) #define DRWAV_VERSION_MAJOR 0 -#define DRWAV_VERSION_MINOR 13 -#define DRWAV_VERSION_REVISION 6 +#define DRWAV_VERSION_MINOR 14 +#define DRWAV_VERSION_REVISION 0 #define DRWAV_VERSION_STRING DRWAV_XSTRINGIFY(DRWAV_VERSION_MAJOR) "." DRWAV_XSTRINGIFY(DRWAV_VERSION_MINOR) "." DRWAV_XSTRINGIFY(DRWAV_VERSION_REVISION) #include /* For size_t. */ -/* Sized types. */ +/* Sized Types */ typedef signed char drwav_int8; typedef unsigned char drwav_uint8; typedef signed short drwav_int16; @@ -154,7 +176,7 @@ typedef unsigned int drwav_uint32; #pragma GCC diagnostic pop #endif #endif -#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__powerpc64__) +#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC) || defined(__powerpc64__) typedef drwav_uint64 drwav_uintptr; #else typedef drwav_uint32 drwav_uintptr; @@ -163,7 +185,9 @@ typedef drwav_uint8 drwav_bool8; typedef drwav_uint32 drwav_bool32; #define DRWAV_TRUE 1 #define DRWAV_FALSE 0 +/* End Sized Types */ +/* Decorations */ #if !defined(DRWAV_API) #if defined(DRWAV_DLL) #if defined(_WIN32) @@ -193,7 +217,9 @@ typedef drwav_uint32 drwav_bool32; #define DRWAV_PRIVATE static #endif #endif +/* End Decorations */ +/* Result Codes */ typedef drwav_int32 drwav_result; #define DRWAV_SUCCESS 0 #define DRWAV_ERROR -1 /* A generic error. */ @@ -249,6 +275,7 @@ typedef drwav_int32 drwav_result; #define DRWAV_CANCELLED -51 #define DRWAV_MEMORY_ALREADY_MAPPED -52 #define DRWAV_AT_END -53 +/* End Result Codes */ /* Common data formats. */ #define DR_WAVE_FORMAT_PCM 0x1 @@ -261,10 +288,21 @@ typedef drwav_int32 drwav_result; /* Flags to pass into drwav_init_ex(), etc. */ #define DRWAV_SEQUENTIAL 0x00000001 +#define DRWAV_WITH_METADATA 0x00000002 DRWAV_API void drwav_version(drwav_uint32* pMajor, drwav_uint32* pMinor, drwav_uint32* pRevision); DRWAV_API const char* drwav_version_string(void); +/* Allocation Callbacks */ +typedef struct +{ + void* pUserData; + void* (* onMalloc)(size_t sz, void* pUserData); + void* (* onRealloc)(void* p, size_t sz, void* pUserData); + void (* onFree)(void* p, void* pUserData); +} drwav_allocation_callbacks; +/* End Allocation Callbacks */ + typedef enum { drwav_seek_origin_start, @@ -274,8 +312,10 @@ typedef enum typedef enum { drwav_container_riff, + drwav_container_rifx, drwav_container_w64, - drwav_container_rf64 + drwav_container_rf64, + drwav_container_aiff } drwav_container; typedef struct @@ -406,13 +446,6 @@ The read pointer will be sitting on the first byte after the chunk's header. You */ typedef drwav_uint64 (* drwav_chunk_proc)(void* pChunkUserData, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pReadSeekUserData, const drwav_chunk_header* pChunkHeader, drwav_container container, const drwav_fmt* pFMT); -typedef struct -{ - void* pUserData; - void* (* onMalloc)(size_t sz, void* pUserData); - void* (* onRealloc)(void* p, size_t sz, void* pUserData); - void (* onFree)(void* p, void* pUserData); -} drwav_allocation_callbacks; /* Structure for internal use. Only used for loaders opened with drwav_init_memory(). */ typedef struct @@ -522,11 +555,11 @@ typedef struct /* See drwav_smpl_loop_type. */ drwav_uint32 type; - /* The byte offset of the first sample to be played in the loop. */ - drwav_uint32 firstSampleByteOffset; + /* The offset of the first sample to be played in the loop. */ + drwav_uint32 firstSampleOffset; - /* The byte offset into the audio data of the last sample to be played in the loop. */ - drwav_uint32 lastSampleByteOffset; + /* The offset into the audio data of the last sample to be played in the loop. */ + drwav_uint32 lastSampleOffset; /* A value to represent that playback should occur at a point between samples. This value ranges from 0 to UINT32_MAX. Where a value of 0 means no fraction, and a value of (UINT32_MAX / 2) would mean half a sample. */ drwav_uint32 sampleFraction; @@ -604,8 +637,8 @@ typedef struct /* Set to 0 for uncompressed formats. Else the last byte in compressed wave data where decompression can begin to find the value of the corresponding sample value. */ drwav_uint32 blockStart; - /* For uncompressed formats this is the byte offset of the cue point into the audio data. For compressed formats this is relative to the block specified with blockStart. */ - drwav_uint32 sampleByteOffset; + /* For uncompressed formats this is the offset of the cue point into the audio data. For compressed formats this is relative to the block specified with blockStart. */ + drwav_uint32 sampleOffset; } drwav_cue_point; typedef struct @@ -866,9 +899,6 @@ typedef struct drwav_bool32 isSequentialWrite; - /* A bit-field of drwav_metadata_type values, only bits set in this variable are parsed and saved */ - drwav_metadata_type allowedMetadataTypes; - /* A array of metadata. This is valid after the *init_with_metadata call returns. It will be valid until drwav_uninit() is called. You can take ownership of this data with drwav_take_ownership_of_metadata(). */ drwav_metadata* pMetadata; drwav_uint32 metadataCount; @@ -899,6 +929,13 @@ typedef struct drwav_int32 cachedFrames[16]; /* Samples are stored in this cache during decoding. */ drwav_uint32 cachedFrameCount; } ima; + + /* AIFF specific data. */ + struct + { + drwav_bool8 isLE; /* Will be set to true if the audio data is little-endian encoded. */ + drwav_bool8 isUnsigned; /* Only used for 8-bit samples. When set to true, will be treated as unsigned. */ + } aiff; } drwav; @@ -1297,14 +1334,21 @@ DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b); #ifndef dr_wav_c #define dr_wav_c +#ifdef __MRC__ +/* MrC currently doesn't compile dr_wav correctly with any optimizations enabled. */ +#pragma options opt off +#endif + #include #include #include /* For INT_MAX */ #ifndef DR_WAV_NO_STDIO #include +#ifndef DR_WAV_NO_WCHAR #include #endif +#endif /* Standard library stuff. */ #ifndef DRWAV_ASSERT @@ -1337,17 +1381,19 @@ DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b); #define drwav_clamp(x, lo, hi) (drwav_max((lo), drwav_min((hi), (x)))) #define drwav_offset_ptr(p, offset) (((drwav_uint8*)(p)) + (offset)) -#define DRWAV_MAX_SIMD_VECTOR_SIZE 64 /* 64 for AVX-512 in the future. */ +#define DRWAV_MAX_SIMD_VECTOR_SIZE 32 -/* CPU architecture. */ -#if defined(__x86_64__) || defined(_M_X64) +/* Architecture Detection */ +#if defined(__x86_64__) || (defined(_M_X64) && !defined(_M_ARM64EC)) #define DRWAV_X64 #elif defined(__i386) || defined(_M_IX86) #define DRWAV_X86 #elif defined(__arm__) || defined(_M_ARM) #define DRWAV_ARM #endif +/* End Architecture Detection */ +/* Inline */ #ifdef _MSC_VER #define DRWAV_INLINE __forceinline #elif defined(__GNUC__) @@ -1374,7 +1420,9 @@ DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b); #else #define DRWAV_INLINE #endif +/* End Inline */ +/* SIZE_MAX */ #if defined(SIZE_MAX) #define DRWAV_SIZE_MAX SIZE_MAX #else @@ -1384,6 +1432,11 @@ DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b); #define DRWAV_SIZE_MAX 0xFFFFFFFF #endif #endif +/* End SIZE_MAX */ + +/* Weird bit manipulation is for C89 compatibility (no direct support for 64-bit integers). */ +#define DRWAV_INT64_MIN ((drwav_int64) ((drwav_uint64)0x80000000 << 32)) +#define DRWAV_INT64_MAX ((drwav_int64)(((drwav_uint64)0x7FFFFFFF << 32) | 0xFFFFFFFF)) #if defined(_MSC_VER) && _MSC_VER >= 1400 #define DRWAV_HAS_BYTESWAP16_INTRINSIC @@ -1593,69 +1646,65 @@ static DRWAV_INLINE void drwav__bswap_samples_s32(drwav_int32* pSamples, drwav_u } -static DRWAV_INLINE float drwav__bswap_f32(float n) +static DRWAV_INLINE drwav_int64 drwav__bswap_s64(drwav_int64 n) { - union { - drwav_uint32 i; - float f; - } x; - x.f = n; - x.i = drwav__bswap32(x.i); - - return x.f; + return (drwav_int64)drwav__bswap64((drwav_uint64)n); } -static DRWAV_INLINE void drwav__bswap_samples_f32(float* pSamples, drwav_uint64 sampleCount) +static DRWAV_INLINE void drwav__bswap_samples_s64(drwav_int64* pSamples, drwav_uint64 sampleCount) { drwav_uint64 iSample; for (iSample = 0; iSample < sampleCount; iSample += 1) { - pSamples[iSample] = drwav__bswap_f32(pSamples[iSample]); + pSamples[iSample] = drwav__bswap_s64(pSamples[iSample]); } } -static DRWAV_INLINE double drwav__bswap_f64(double n) +static DRWAV_INLINE float drwav__bswap_f32(float n) { union { - drwav_uint64 i; - double f; + drwav_uint32 i; + float f; } x; x.f = n; - x.i = drwav__bswap64(x.i); + x.i = drwav__bswap32(x.i); return x.f; } -static DRWAV_INLINE void drwav__bswap_samples_f64(double* pSamples, drwav_uint64 sampleCount) +static DRWAV_INLINE void drwav__bswap_samples_f32(float* pSamples, drwav_uint64 sampleCount) { drwav_uint64 iSample; for (iSample = 0; iSample < sampleCount; iSample += 1) { - pSamples[iSample] = drwav__bswap_f64(pSamples[iSample]); + pSamples[iSample] = drwav__bswap_f32(pSamples[iSample]); } } -static DRWAV_INLINE void drwav__bswap_samples_pcm(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample) +static DRWAV_INLINE void drwav__bswap_samples(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample) { - /* Assumes integer PCM. Floating point PCM is done in drwav__bswap_samples_ieee(). */ switch (bytesPerSample) { - case 1: /* u8 */ + case 1: { - /* no-op. */ + /* No-op. */ } break; - case 2: /* s16, s12 (loosely packed) */ + case 2: { drwav__bswap_samples_s16((drwav_int16*)pSamples, sampleCount); } break; - case 3: /* s24 */ + case 3: { drwav__bswap_samples_s24((drwav_uint8*)pSamples, sampleCount); } break; - case 4: /* s32 */ + case 4: { drwav__bswap_samples_s32((drwav_int32*)pSamples, sampleCount); } break; + case 8: + { + drwav__bswap_samples_s64((drwav_int64*)pSamples, sampleCount); + } break; default: { /* Unsupported format. */ @@ -1664,59 +1713,91 @@ static DRWAV_INLINE void drwav__bswap_samples_pcm(void* pSamples, drwav_uint64 s } } -static DRWAV_INLINE void drwav__bswap_samples_ieee(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample) + + +DRWAV_PRIVATE DRWAV_INLINE drwav_bool32 drwav_is_container_be(drwav_container container) { - switch (bytesPerSample) - { - #if 0 /* Contributions welcome for f16 support. */ - case 2: /* f16 */ - { - drwav__bswap_samples_f16((drwav_float16*)pSamples, sampleCount); - } break; - #endif - case 4: /* f32 */ - { - drwav__bswap_samples_f32((float*)pSamples, sampleCount); - } break; - case 8: /* f64 */ - { - drwav__bswap_samples_f64((double*)pSamples, sampleCount); - } break; - default: - { - /* Unsupported format. */ - DRWAV_ASSERT(DRWAV_FALSE); - } break; + if (container == drwav_container_rifx || container == drwav_container_aiff) { + return DRWAV_TRUE; + } else { + return DRWAV_FALSE; } } -static DRWAV_INLINE void drwav__bswap_samples(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample, drwav_uint16 format) + +DRWAV_PRIVATE DRWAV_INLINE drwav_uint16 drwav_bytes_to_u16_le(const drwav_uint8* data) { - switch (format) - { - case DR_WAVE_FORMAT_PCM: - { - drwav__bswap_samples_pcm(pSamples, sampleCount, bytesPerSample); - } break; + return ((drwav_uint16)data[0] << 0) | ((drwav_uint16)data[1] << 8); +} - case DR_WAVE_FORMAT_IEEE_FLOAT: - { - drwav__bswap_samples_ieee(pSamples, sampleCount, bytesPerSample); - } break; +DRWAV_PRIVATE DRWAV_INLINE drwav_uint16 drwav_bytes_to_u16_be(const drwav_uint8* data) +{ + return ((drwav_uint16)data[1] << 0) | ((drwav_uint16)data[0] << 8); +} - case DR_WAVE_FORMAT_ALAW: - case DR_WAVE_FORMAT_MULAW: - { - drwav__bswap_samples_s16((drwav_int16*)pSamples, sampleCount); - } break; +DRWAV_PRIVATE DRWAV_INLINE drwav_uint16 drwav_bytes_to_u16_ex(const drwav_uint8* data, drwav_container container) +{ + if (drwav_is_container_be(container)) { + return drwav_bytes_to_u16_be(data); + } else { + return drwav_bytes_to_u16_le(data); + } +} - case DR_WAVE_FORMAT_ADPCM: - case DR_WAVE_FORMAT_DVI_ADPCM: - default: - { - /* Unsupported format. */ - DRWAV_ASSERT(DRWAV_FALSE); - } break; + +DRWAV_PRIVATE DRWAV_INLINE drwav_uint32 drwav_bytes_to_u32_le(const drwav_uint8* data) +{ + return ((drwav_uint32)data[0] << 0) | ((drwav_uint32)data[1] << 8) | ((drwav_uint32)data[2] << 16) | ((drwav_uint32)data[3] << 24); +} + +DRWAV_PRIVATE DRWAV_INLINE drwav_uint32 drwav_bytes_to_u32_be(const drwav_uint8* data) +{ + return ((drwav_uint32)data[3] << 0) | ((drwav_uint32)data[2] << 8) | ((drwav_uint32)data[1] << 16) | ((drwav_uint32)data[0] << 24); +} + +DRWAV_PRIVATE DRWAV_INLINE drwav_uint32 drwav_bytes_to_u32_ex(const drwav_uint8* data, drwav_container container) +{ + if (drwav_is_container_be(container)) { + return drwav_bytes_to_u32_be(data); + } else { + return drwav_bytes_to_u32_le(data); + } +} + + + +DRWAV_PRIVATE drwav_int64 drwav_aiff_extented_to_s64(const drwav_uint8* data) +{ + drwav_uint32 exponent = ((drwav_uint32)data[0] << 8) | data[1]; + drwav_uint64 hi = ((drwav_uint64)data[2] << 24) | ((drwav_uint64)data[3] << 16) | ((drwav_uint64)data[4] << 8) | ((drwav_uint64)data[5] << 0); + drwav_uint64 lo = ((drwav_uint64)data[6] << 24) | ((drwav_uint64)data[7] << 16) | ((drwav_uint64)data[8] << 8) | ((drwav_uint64)data[9] << 0); + drwav_uint64 significand = (hi << 32) | lo; + int sign = exponent >> 15; + + /* Remove sign bit. */ + exponent &= 0x7FFF; + + /* Special cases. */ + if (exponent == 0 && significand == 0) { + return 0; + } else if (exponent == 0x7FFF) { + return sign ? DRWAV_INT64_MIN : DRWAV_INT64_MAX; /* Infinite. */ + } + + exponent -= 16383; + + if (exponent > 63) { + return sign ? DRWAV_INT64_MIN : DRWAV_INT64_MAX; /* Too big for a 64-bit integer. */ + } else if (exponent < 1) { + return 0; /* Number is less than 1, so rounds down to 0. */ + } + + significand >>= (63 - exponent); + + if (sign) { + return -(drwav_int64)significand; + } else { + return (drwav_int64)significand; } } @@ -1840,7 +1921,7 @@ DRWAV_PRIVATE drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_d DRWAV_PRIVATE drwav_result drwav__read_chunk_header(drwav_read_proc onRead, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_chunk_header* pHeaderOut) { - if (container == drwav_container_riff || container == drwav_container_rf64) { + if (container == drwav_container_riff || container == drwav_container_rifx || container == drwav_container_rf64 || container == drwav_container_aiff) { drwav_uint8 sizeInBytes[4]; if (onRead(pUserData, pHeaderOut->id.fourcc, 4) != 4) { @@ -1851,10 +1932,11 @@ DRWAV_PRIVATE drwav_result drwav__read_chunk_header(drwav_read_proc onRead, void return DRWAV_INVALID_FILE; } - pHeaderOut->sizeInBytes = drwav_bytes_to_u32(sizeInBytes); + pHeaderOut->sizeInBytes = drwav_bytes_to_u32_ex(sizeInBytes, container); pHeaderOut->paddingSize = drwav__chunk_padding_size_riff(pHeaderOut->sizeInBytes); + *pRunningBytesReadOut += 8; - } else { + } else if (container == drwav_container_w64) { drwav_uint8 sizeInBytes[8]; if (onRead(pUserData, pHeaderOut->id.guid, 16) != 16) { @@ -1868,6 +1950,8 @@ DRWAV_PRIVATE drwav_result drwav__read_chunk_header(drwav_read_proc onRead, void pHeaderOut->sizeInBytes = drwav_bytes_to_u64(sizeInBytes) - 24; /* <-- Subtract 24 because w64 includes the size of the header. */ pHeaderOut->paddingSize = drwav__chunk_padding_size_w64(pHeaderOut->sizeInBytes); *pRunningBytesReadOut += 24; + } else { + return DRWAV_INVALID_FILE; } return DRWAV_SUCCESS; @@ -1921,115 +2005,6 @@ DRWAV_PRIVATE drwav_bool32 drwav__seek_from_start(drwav_seek_proc onSeek, drwav_ } -DRWAV_PRIVATE drwav_bool32 drwav__read_fmt(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_fmt* fmtOut) -{ - drwav_chunk_header header; - drwav_uint8 fmt[16]; - - if (drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header) != DRWAV_SUCCESS) { - return DRWAV_FALSE; - } - - - /* Skip non-fmt chunks. */ - while (((container == drwav_container_riff || container == drwav_container_rf64) && !drwav_fourcc_equal(header.id.fourcc, "fmt ")) || (container == drwav_container_w64 && !drwav_guid_equal(header.id.guid, drwavGUID_W64_FMT))) { - if (!drwav__seek_forward(onSeek, header.sizeInBytes + header.paddingSize, pUserData)) { - return DRWAV_FALSE; - } - *pRunningBytesReadOut += header.sizeInBytes + header.paddingSize; - - /* Try the next header. */ - if (drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header) != DRWAV_SUCCESS) { - return DRWAV_FALSE; - } - } - - - /* Validation. */ - if (container == drwav_container_riff || container == drwav_container_rf64) { - if (!drwav_fourcc_equal(header.id.fourcc, "fmt ")) { - return DRWAV_FALSE; - } - } else { - if (!drwav_guid_equal(header.id.guid, drwavGUID_W64_FMT)) { - return DRWAV_FALSE; - } - } - - - if (onRead(pUserData, fmt, sizeof(fmt)) != sizeof(fmt)) { - return DRWAV_FALSE; - } - *pRunningBytesReadOut += sizeof(fmt); - - fmtOut->formatTag = drwav_bytes_to_u16(fmt + 0); - fmtOut->channels = drwav_bytes_to_u16(fmt + 2); - fmtOut->sampleRate = drwav_bytes_to_u32(fmt + 4); - fmtOut->avgBytesPerSec = drwav_bytes_to_u32(fmt + 8); - fmtOut->blockAlign = drwav_bytes_to_u16(fmt + 12); - fmtOut->bitsPerSample = drwav_bytes_to_u16(fmt + 14); - - fmtOut->extendedSize = 0; - fmtOut->validBitsPerSample = 0; - fmtOut->channelMask = 0; - DRWAV_ZERO_MEMORY(fmtOut->subFormat, sizeof(fmtOut->subFormat)); - - if (header.sizeInBytes > 16) { - drwav_uint8 fmt_cbSize[2]; - int bytesReadSoFar = 0; - - if (onRead(pUserData, fmt_cbSize, sizeof(fmt_cbSize)) != sizeof(fmt_cbSize)) { - return DRWAV_FALSE; /* Expecting more data. */ - } - *pRunningBytesReadOut += sizeof(fmt_cbSize); - - bytesReadSoFar = 18; - - fmtOut->extendedSize = drwav_bytes_to_u16(fmt_cbSize); - if (fmtOut->extendedSize > 0) { - /* Simple validation. */ - if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) { - if (fmtOut->extendedSize != 22) { - return DRWAV_FALSE; - } - } - - if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) { - drwav_uint8 fmtext[22]; - if (onRead(pUserData, fmtext, fmtOut->extendedSize) != fmtOut->extendedSize) { - return DRWAV_FALSE; /* Expecting more data. */ - } - - fmtOut->validBitsPerSample = drwav_bytes_to_u16(fmtext + 0); - fmtOut->channelMask = drwav_bytes_to_u32(fmtext + 2); - drwav_bytes_to_guid(fmtext + 6, fmtOut->subFormat); - } else { - if (!onSeek(pUserData, fmtOut->extendedSize, drwav_seek_origin_current)) { - return DRWAV_FALSE; - } - } - *pRunningBytesReadOut += fmtOut->extendedSize; - - bytesReadSoFar += fmtOut->extendedSize; - } - - /* Seek past any leftover bytes. For w64 the leftover will be defined based on the chunk size. */ - if (!onSeek(pUserData, (int)(header.sizeInBytes - bytesReadSoFar), drwav_seek_origin_current)) { - return DRWAV_FALSE; - } - *pRunningBytesReadOut += (header.sizeInBytes - bytesReadSoFar); - } - - if (header.paddingSize > 0) { - if (!onSeek(pUserData, header.paddingSize, drwav_seek_origin_current)) { - return DRWAV_FALSE; - } - *pRunningBytesReadOut += header.paddingSize; - } - - return DRWAV_TRUE; -} - DRWAV_PRIVATE size_t drwav__on_read(drwav_read_proc onRead, void* pUserData, void* pBufferOut, size_t bytesToRead, drwav_uint64* pCursor) { @@ -2121,7 +2096,7 @@ DRWAV_PRIVATE drwav_uint8* drwav__metadata_get_memory(drwav__metadata_parser* pP pParser->pDataCursor += align - modulo; } } - + pResult = pParser->pDataCursor; /* @@ -2154,7 +2129,7 @@ DRWAV_PRIVATE drwav_result drwav__metadata_alloc(drwav__metadata_parser* pParser /* We don't need to worry about specifying an alignment here because malloc always returns something - of suitable alignment. This also means than pParser->pMetadata is all that we need to store in order + of suitable alignment. This also means pParser->pMetadata is all that we need to store in order for us to free when we are done. */ pParser->pMetadata = (drwav_metadata*)drwav__metadata_get_memory(pParser, sizeof(drwav_metadata) * pParser->metadataCount, 1); @@ -2177,12 +2152,18 @@ DRWAV_PRIVATE drwav_uint64 drwav__read_smpl_to_metadata_obj(drwav__metadata_pars { drwav_uint8 smplHeaderData[DRWAV_SMPL_BYTES]; drwav_uint64 totalBytesRead = 0; - size_t bytesJustRead = drwav__metadata_parser_read(pParser, smplHeaderData, sizeof(smplHeaderData), &totalBytesRead); + size_t bytesJustRead; + + if (pMetadata == NULL) { + return 0; + } + + bytesJustRead = drwav__metadata_parser_read(pParser, smplHeaderData, sizeof(smplHeaderData), &totalBytesRead); DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read); DRWAV_ASSERT(pChunkHeader != NULL); - if (bytesJustRead == sizeof(smplHeaderData)) { + if (pMetadata != NULL && bytesJustRead == sizeof(smplHeaderData)) { drwav_uint32 iSampleLoop; pMetadata->type = drwav_metadata_type_smpl; @@ -2208,12 +2189,12 @@ DRWAV_PRIVATE drwav_uint64 drwav__read_smpl_to_metadata_obj(drwav__metadata_pars bytesJustRead = drwav__metadata_parser_read(pParser, smplLoopData, sizeof(smplLoopData), &totalBytesRead); if (bytesJustRead == sizeof(smplLoopData)) { - pMetadata->data.smpl.pLoops[iSampleLoop].cuePointId = drwav_bytes_to_u32(smplLoopData + 0); - pMetadata->data.smpl.pLoops[iSampleLoop].type = drwav_bytes_to_u32(smplLoopData + 4); - pMetadata->data.smpl.pLoops[iSampleLoop].firstSampleByteOffset = drwav_bytes_to_u32(smplLoopData + 8); - pMetadata->data.smpl.pLoops[iSampleLoop].lastSampleByteOffset = drwav_bytes_to_u32(smplLoopData + 12); - pMetadata->data.smpl.pLoops[iSampleLoop].sampleFraction = drwav_bytes_to_u32(smplLoopData + 16); - pMetadata->data.smpl.pLoops[iSampleLoop].playCount = drwav_bytes_to_u32(smplLoopData + 20); + pMetadata->data.smpl.pLoops[iSampleLoop].cuePointId = drwav_bytes_to_u32(smplLoopData + 0); + pMetadata->data.smpl.pLoops[iSampleLoop].type = drwav_bytes_to_u32(smplLoopData + 4); + pMetadata->data.smpl.pLoops[iSampleLoop].firstSampleOffset = drwav_bytes_to_u32(smplLoopData + 8); + pMetadata->data.smpl.pLoops[iSampleLoop].lastSampleOffset = drwav_bytes_to_u32(smplLoopData + 12); + pMetadata->data.smpl.pLoops[iSampleLoop].sampleFraction = drwav_bytes_to_u32(smplLoopData + 16); + pMetadata->data.smpl.pLoops[iSampleLoop].playCount = drwav_bytes_to_u32(smplLoopData + 20); } else { break; } @@ -2235,7 +2216,13 @@ DRWAV_PRIVATE drwav_uint64 drwav__read_cue_to_metadata_obj(drwav__metadata_parse { drwav_uint8 cueHeaderSectionData[DRWAV_CUE_BYTES]; drwav_uint64 totalBytesRead = 0; - size_t bytesJustRead = drwav__metadata_parser_read(pParser, cueHeaderSectionData, sizeof(cueHeaderSectionData), &totalBytesRead); + size_t bytesJustRead; + + if (pMetadata == NULL) { + return 0; + } + + bytesJustRead = drwav__metadata_parser_read(pParser, cueHeaderSectionData, sizeof(cueHeaderSectionData), &totalBytesRead); DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read); @@ -2267,7 +2254,7 @@ DRWAV_PRIVATE drwav_uint64 drwav__read_cue_to_metadata_obj(drwav__metadata_parse pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[3] = cuePointData[11]; pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart = drwav_bytes_to_u32(cuePointData + 12); pMetadata->data.cue.pCuePoints[iCuePoint].blockStart = drwav_bytes_to_u32(cuePointData + 16); - pMetadata->data.cue.pCuePoints[iCuePoint].sampleByteOffset = drwav_bytes_to_u32(cuePointData + 20); + pMetadata->data.cue.pCuePoints[iCuePoint].sampleOffset = drwav_bytes_to_u32(cuePointData + 20); } else { break; } @@ -2282,7 +2269,13 @@ DRWAV_PRIVATE drwav_uint64 drwav__read_cue_to_metadata_obj(drwav__metadata_parse DRWAV_PRIVATE drwav_uint64 drwav__read_inst_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata) { drwav_uint8 instData[DRWAV_INST_BYTES]; - drwav_uint64 bytesRead = drwav__metadata_parser_read(pParser, instData, sizeof(instData), NULL); + drwav_uint64 bytesRead; + + if (pMetadata == NULL) { + return 0; + } + + bytesRead = drwav__metadata_parser_read(pParser, instData, sizeof(instData), NULL); DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read); @@ -2303,7 +2296,13 @@ DRWAV_PRIVATE drwav_uint64 drwav__read_inst_to_metadata_obj(drwav__metadata_pars DRWAV_PRIVATE drwav_uint64 drwav__read_acid_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata) { drwav_uint8 acidData[DRWAV_ACID_BYTES]; - drwav_uint64 bytesRead = drwav__metadata_parser_read(pParser, acidData, sizeof(acidData), NULL); + drwav_uint64 bytesRead; + + if (pMetadata == NULL) { + return 0; + } + + bytesRead = drwav__metadata_parser_read(pParser, acidData, sizeof(acidData), NULL); DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read); @@ -2408,7 +2407,7 @@ DRWAV_PRIVATE drwav_result drwav_buffer_reader_read(drwav_buffer_reader* pReader size_t bytesRemaining; DRWAV_ASSERT(pReader != NULL); - + if (pBytesRead != NULL) { *pBytesRead = 0; } @@ -2488,7 +2487,7 @@ DRWAV_PRIVATE drwav_uint64 drwav__read_bext_to_metadata_obj(drwav__metadata_pars size_t bytesRead = drwav__metadata_parser_read(pParser, bextData, sizeof(bextData), NULL); DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read); - + if (bytesRead == sizeof(bextData)) { drwav_buffer_reader reader; drwav_uint32 timeReferenceLow; @@ -2550,7 +2549,7 @@ DRWAV_PRIVATE drwav_uint64 drwav__read_list_label_or_note_to_metadata_obj(drwav_ drwav_uint64 totalBytesRead = 0; size_t bytesJustRead = drwav__metadata_parser_read(pParser, cueIDBuffer, sizeof(cueIDBuffer), &totalBytesRead); - DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read); + DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read); if (bytesJustRead == sizeof(cueIDBuffer)) { drwav_uint32 sizeIncludingNullTerminator; @@ -2653,7 +2652,7 @@ DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_unknown_chunk(drwav__metadata return 0; } - if (drwav_fourcc_equal(pChunkId, "data") || drwav_fourcc_equal(pChunkId, "fmt") || drwav_fourcc_equal(pChunkId, "fact")) { + if (drwav_fourcc_equal(pChunkId, "data") || drwav_fourcc_equal(pChunkId, "fmt ") || drwav_fourcc_equal(pChunkId, "fact")) { return 0; } @@ -2722,7 +2721,7 @@ DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_chunk(drwav__metadata_parser* } } else { /* Loop count in header does not match the size of the chunk. */ - } + } } } else { bytesRead = drwav__read_smpl_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]); @@ -3008,20 +3007,25 @@ DRWAV_PRIVATE drwav_bool32 drwav_preinit(drwav* pWav, drwav_read_proc onRead, dr DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags) { /* This function assumes drwav_preinit() has been called beforehand. */ - + drwav_result result; drwav_uint64 cursor; /* <-- Keeps track of the byte position so we can seek to specific locations. */ drwav_bool32 sequential; drwav_uint8 riff[4]; drwav_fmt fmt; unsigned short translatedFormatTag; - drwav_bool32 foundDataChunk; - drwav_uint64 dataChunkSize = 0; /* <-- Important! Don't explicitly set this to 0 anywhere else. Calculation of the size of the data chunk is performed in different paths depending on the container. */ + drwav_uint64 dataChunkSize = 0; /* <-- Important! Don't explicitly set this to 0 anywhere else. Calculation of the size of the data chunk is performed in different paths depending on the container. */ drwav_uint64 sampleCountFromFactChunk = 0; /* Same as dataChunkSize - make sure this is the only place this is initialized to 0. */ - drwav_uint64 chunkSize; + drwav_uint64 metadataStartPos; drwav__metadata_parser metadataParser; + drwav_bool8 isProcessingMetadata = DRWAV_FALSE; + drwav_bool8 foundChunk_fmt = DRWAV_FALSE; + drwav_bool8 foundChunk_data = DRWAV_FALSE; + drwav_bool8 isAIFCFormType = DRWAV_FALSE; /* Only used with AIFF. */ + drwav_uint64 aiffFrameCount = 0; cursor = 0; sequential = (flags & DRWAV_SEQUENTIAL) != 0; + DRWAV_ZERO_OBJECT(&fmt); /* The first 4 bytes should be the RIFF identifier. */ if (drwav__on_read(pWav->onRead, pWav->pUserData, riff, sizeof(riff), &cursor) != sizeof(riff)) { @@ -3034,6 +3038,8 @@ DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc on */ if (drwav_fourcc_equal(riff, "RIFF")) { pWav->container = drwav_container_riff; + } else if (drwav_fourcc_equal(riff, "RIFX")) { + pWav->container = drwav_container_rifx; } else if (drwav_fourcc_equal(riff, "riff")) { int i; drwav_uint8 riff2[12]; @@ -3052,28 +3058,37 @@ DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc on } } else if (drwav_fourcc_equal(riff, "RF64")) { pWav->container = drwav_container_rf64; + } else if (drwav_fourcc_equal(riff, "FORM")) { + pWav->container = drwav_container_aiff; } else { return DRWAV_FALSE; /* Unknown or unsupported container. */ } - if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64) { + if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx || pWav->container == drwav_container_rf64) { drwav_uint8 chunkSizeBytes[4]; drwav_uint8 wave[4]; - /* RIFF/WAVE */ if (drwav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) { return DRWAV_FALSE; } - if (pWav->container == drwav_container_riff) { - if (drwav_bytes_to_u32(chunkSizeBytes) < 36) { - return DRWAV_FALSE; /* Chunk size should always be at least 36 bytes. */ + if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx) { + if (drwav_bytes_to_u32_ex(chunkSizeBytes, pWav->container) < 36) { + /* + I've had a report of a WAV file failing to load when the size of the WAVE chunk is not encoded + and is instead just set to 0. I'm going to relax the validation here to allow these files to + load. Considering the chunk size isn't actually used this should be safe. With this change my + test suite still passes. + */ + /*return DRWAV_FALSE;*/ /* Chunk size should always be at least 36 bytes. */ } - } else { - if (drwav_bytes_to_u32(chunkSizeBytes) != 0xFFFFFFFF) { + } else if (pWav->container == drwav_container_rf64) { + if (drwav_bytes_to_u32_le(chunkSizeBytes) != 0xFFFFFFFF) { return DRWAV_FALSE; /* Chunk size should always be set to -1/0xFFFFFFFF for RF64. The actual size is retrieved later. */ } + } else { + return DRWAV_FALSE; /* Should never hit this. */ } if (drwav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) { @@ -3083,11 +3098,10 @@ DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc on if (!drwav_fourcc_equal(wave, "WAVE")) { return DRWAV_FALSE; /* Expecting "WAVE". */ } - } else { + } else if (pWav->container == drwav_container_w64) { drwav_uint8 chunkSizeBytes[8]; drwav_uint8 wave[16]; - /* W64 */ if (drwav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) { return DRWAV_FALSE; } @@ -3103,6 +3117,31 @@ DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc on if (!drwav_guid_equal(wave, drwavGUID_W64_WAVE)) { return DRWAV_FALSE; } + } else if (pWav->container == drwav_container_aiff) { + drwav_uint8 chunkSizeBytes[4]; + drwav_uint8 aiff[4]; + + if (drwav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) { + return DRWAV_FALSE; + } + + if (drwav_bytes_to_u32_be(chunkSizeBytes) < 18) { + return DRWAV_FALSE; + } + + if (drwav__on_read(pWav->onRead, pWav->pUserData, aiff, sizeof(aiff), &cursor) != sizeof(aiff)) { + return DRWAV_FALSE; + } + + if (drwav_fourcc_equal(aiff, "AIFF")) { + isAIFCFormType = DRWAV_FALSE; + } else if (drwav_fourcc_equal(aiff, "AIFC")) { + isAIFCFormType = DRWAV_TRUE; + } else { + return DRWAV_FALSE; /* Expecting "AIFF" or "AIFC". */ + } + } else { + return DRWAV_FALSE; } @@ -3111,7 +3150,7 @@ DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc on drwav_uint8 sizeBytes[8]; drwav_uint64 bytesRemainingInChunk; drwav_chunk_header header; - drwav_result result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header); + result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header); if (result != DRWAV_SUCCESS) { return DRWAV_FALSE; } @@ -3154,196 +3193,435 @@ DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc on } - /* The next bytes should be the "fmt " chunk. */ - if (!drwav__read_fmt(pWav->onRead, pWav->onSeek, pWav->pUserData, pWav->container, &cursor, &fmt)) { - return DRWAV_FALSE; /* Failed to read the "fmt " chunk. */ + metadataStartPos = cursor; + + /* + Whether or not we are processing metadata controls how we load. We can load more efficiently when + metadata is not being processed, but we also cannot process metadata for Wave64 because I have not + been able to test it. If someone is able to test this and provide a patch I'm happy to enable it. + + Seqential mode cannot support metadata because it involves seeking backwards. + */ + isProcessingMetadata = !sequential && ((flags & DRWAV_WITH_METADATA) != 0); + + /* Don't allow processing of metadata with untested containers. */ + if (pWav->container != drwav_container_riff && pWav->container != drwav_container_rf64) { + isProcessingMetadata = DRWAV_FALSE; } - /* Basic validation. */ - if ((fmt.sampleRate == 0 || fmt.sampleRate > DRWAV_MAX_SAMPLE_RATE) || - (fmt.channels == 0 || fmt.channels > DRWAV_MAX_CHANNELS) || - (fmt.bitsPerSample == 0 || fmt.bitsPerSample > DRWAV_MAX_BITS_PER_SAMPLE) || - fmt.blockAlign == 0) { - return DRWAV_FALSE; /* Probably an invalid WAV file. */ + DRWAV_ZERO_MEMORY(&metadataParser, sizeof(metadataParser)); + if (isProcessingMetadata) { + metadataParser.onRead = pWav->onRead; + metadataParser.onSeek = pWav->onSeek; + metadataParser.pReadSeekUserData = pWav->pUserData; + metadataParser.stage = drwav__metadata_parser_stage_count; } - /* Translate the internal format. */ - translatedFormatTag = fmt.formatTag; - if (translatedFormatTag == DR_WAVE_FORMAT_EXTENSIBLE) { - translatedFormatTag = drwav_bytes_to_u16(fmt.subFormat + 0); - } + /* + From here on out, chunks might be in any order. In order to robustly handle metadata we'll need + to loop through every chunk and handle them as we find them. In sequential mode we need to get + out of the loop as soon as we find the data chunk because we won't be able to seek back. + */ + for (;;) { /* For each chunk... */ + drwav_chunk_header header; + drwav_uint64 chunkSize; + + result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header); + if (result != DRWAV_SUCCESS) { + break; + } + + chunkSize = header.sizeInBytes; + + + /* + Always tell the caller about this chunk. We cannot do this in sequential mode because the + callback is allowed to read from the file, in which case we'll need to rewind. + */ + if (!sequential && onChunk != NULL) { + drwav_uint64 callbackBytesRead = onChunk(pChunkUserData, pWav->onRead, pWav->onSeek, pWav->pUserData, &header, pWav->container, &fmt); + + /* + dr_wav may need to read the contents of the chunk, so we now need to seek back to the position before + we called the callback. + */ + if (callbackBytesRead > 0) { + if (drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData) == DRWAV_FALSE) { + return DRWAV_FALSE; + } + } + } + + + /* Explicitly handle known chunks first. */ + + /* "fmt " */ + if (((pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx || pWav->container == drwav_container_rf64) && drwav_fourcc_equal(header.id.fourcc, "fmt ")) || + ((pWav->container == drwav_container_w64) && drwav_guid_equal(header.id.guid, drwavGUID_W64_FMT))) { + drwav_uint8 fmtData[16]; + + foundChunk_fmt = DRWAV_TRUE; + + if (pWav->onRead(pWav->pUserData, fmtData, sizeof(fmtData)) != sizeof(fmtData)) { + return DRWAV_FALSE; + } + cursor += sizeof(fmtData); + + fmt.formatTag = drwav_bytes_to_u16_ex(fmtData + 0, pWav->container); + fmt.channels = drwav_bytes_to_u16_ex(fmtData + 2, pWav->container); + fmt.sampleRate = drwav_bytes_to_u32_ex(fmtData + 4, pWav->container); + fmt.avgBytesPerSec = drwav_bytes_to_u32_ex(fmtData + 8, pWav->container); + fmt.blockAlign = drwav_bytes_to_u16_ex(fmtData + 12, pWav->container); + fmt.bitsPerSample = drwav_bytes_to_u16_ex(fmtData + 14, pWav->container); + + fmt.extendedSize = 0; + fmt.validBitsPerSample = 0; + fmt.channelMask = 0; + DRWAV_ZERO_MEMORY(fmt.subFormat, sizeof(fmt.subFormat)); + + if (header.sizeInBytes > 16) { + drwav_uint8 fmt_cbSize[2]; + int bytesReadSoFar = 0; + + if (pWav->onRead(pWav->pUserData, fmt_cbSize, sizeof(fmt_cbSize)) != sizeof(fmt_cbSize)) { + return DRWAV_FALSE; /* Expecting more data. */ + } + cursor += sizeof(fmt_cbSize); + + bytesReadSoFar = 18; + + fmt.extendedSize = drwav_bytes_to_u16_ex(fmt_cbSize, pWav->container); + if (fmt.extendedSize > 0) { + /* Simple validation. */ + if (fmt.formatTag == DR_WAVE_FORMAT_EXTENSIBLE) { + if (fmt.extendedSize != 22) { + return DRWAV_FALSE; + } + } + + if (fmt.formatTag == DR_WAVE_FORMAT_EXTENSIBLE) { + drwav_uint8 fmtext[22]; + + if (pWav->onRead(pWav->pUserData, fmtext, fmt.extendedSize) != fmt.extendedSize) { + return DRWAV_FALSE; /* Expecting more data. */ + } + + fmt.validBitsPerSample = drwav_bytes_to_u16_ex(fmtext + 0, pWav->container); + fmt.channelMask = drwav_bytes_to_u32_ex(fmtext + 2, pWav->container); + drwav_bytes_to_guid(fmtext + 6, fmt.subFormat); + } else { + if (pWav->onSeek(pWav->pUserData, fmt.extendedSize, drwav_seek_origin_current) == DRWAV_FALSE) { + return DRWAV_FALSE; + } + } + cursor += fmt.extendedSize; + + bytesReadSoFar += fmt.extendedSize; + } + + /* Seek past any leftover bytes. For w64 the leftover will be defined based on the chunk size. */ + if (pWav->onSeek(pWav->pUserData, (int)(header.sizeInBytes - bytesReadSoFar), drwav_seek_origin_current) == DRWAV_FALSE) { + return DRWAV_FALSE; + } + cursor += (header.sizeInBytes - bytesReadSoFar); + } + + if (header.paddingSize > 0) { + if (drwav__seek_forward(pWav->onSeek, header.paddingSize, pWav->pUserData) == DRWAV_FALSE) { + break; + } + cursor += header.paddingSize; + } + + /* Go to the next chunk. Don't include this chunk in metadata. */ + continue; + } + + /* "data" */ + if (((pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx || pWav->container == drwav_container_rf64) && drwav_fourcc_equal(header.id.fourcc, "data")) || + ((pWav->container == drwav_container_w64) && drwav_guid_equal(header.id.guid, drwavGUID_W64_DATA))) { + foundChunk_data = DRWAV_TRUE; + + pWav->dataChunkDataPos = cursor; + + if (pWav->container != drwav_container_rf64) { /* The data chunk size for RF64 will always be set to 0xFFFFFFFF here. It was set to it's true value earlier. */ + dataChunkSize = chunkSize; + } + + /* If we're running in sequential mode, or we're not reading metadata, we have enough now that we can get out of the loop. */ + if (sequential || !isProcessingMetadata) { + break; /* No need to keep reading beyond the data chunk. */ + } else { + chunkSize += header.paddingSize; /* <-- Make sure we seek past the padding. */ + if (drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == DRWAV_FALSE) { + break; + } + cursor += chunkSize; + + continue; /* There may be some more metadata to read. */ + } + } + + /* "fact". This is optional. Can use this to get the sample count which is useful for compressed formats. For RF64 we retrieved the sample count from the ds64 chunk earlier. */ + if (((pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx || pWav->container == drwav_container_rf64) && drwav_fourcc_equal(header.id.fourcc, "fact")) || + ((pWav->container == drwav_container_w64) && drwav_guid_equal(header.id.guid, drwavGUID_W64_FACT))) { + if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx) { + drwav_uint8 sampleCount[4]; + if (drwav__on_read(pWav->onRead, pWav->pUserData, &sampleCount, 4, &cursor) != 4) { + return DRWAV_FALSE; + } + + chunkSize -= 4; + + /* + The sample count in the "fact" chunk is either unreliable, or I'm not understanding it properly. For now I am only enabling this + for Microsoft ADPCM formats. + */ + if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) { + sampleCountFromFactChunk = drwav_bytes_to_u32_ex(sampleCount, pWav->container); + } else { + sampleCountFromFactChunk = 0; + } + } else if (pWav->container == drwav_container_w64) { + if (drwav__on_read(pWav->onRead, pWav->pUserData, &sampleCountFromFactChunk, 8, &cursor) != 8) { + return DRWAV_FALSE; + } + + chunkSize -= 8; + } else if (pWav->container == drwav_container_rf64) { + /* We retrieved the sample count from the ds64 chunk earlier so no need to do that here. */ + } + + /* Seek to the next chunk in preparation for the next iteration. */ + chunkSize += header.paddingSize; /* <-- Make sure we seek past the padding. */ + if (drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == DRWAV_FALSE) { + break; + } + cursor += chunkSize; + + continue; + } - DRWAV_ZERO_MEMORY(&metadataParser, sizeof(metadataParser)); - /* Not tested on W64. */ - if (!sequential && pWav->allowedMetadataTypes != drwav_metadata_type_none && (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64)) { - drwav_uint64 cursorForMetadata = cursor; + /* "COMM". AIFF/AIFC only. */ + if (pWav->container == drwav_container_aiff && drwav_fourcc_equal(header.id.fourcc, "COMM")) { + drwav_uint8 commData[24]; + drwav_uint32 commDataBytesToRead; + drwav_uint16 channels; + drwav_uint32 frameCount; + drwav_uint16 sampleSizeInBits; + drwav_int64 sampleRate; + drwav_uint16 compressionFormat; - metadataParser.onRead = pWav->onRead; - metadataParser.onSeek = pWav->onSeek; - metadataParser.pReadSeekUserData = pWav->pUserData; - metadataParser.stage = drwav__metadata_parser_stage_count; + foundChunk_fmt = DRWAV_TRUE; - for (;;) { - drwav_result result; - drwav_uint64 bytesRead; - drwav_uint64 remainingBytes; - drwav_chunk_header header; - - result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursorForMetadata, &header); - if (result != DRWAV_SUCCESS) { - break; + if (isAIFCFormType) { + commDataBytesToRead = 24; + if (header.sizeInBytes < commDataBytesToRead) { + return DRWAV_FALSE; /* Invalid COMM chunk. */ + } + } else { + commDataBytesToRead = 18; + if (header.sizeInBytes != commDataBytesToRead) { + return DRWAV_FALSE; /* INVALID COMM chunk. */ + } } - bytesRead = drwav__metadata_process_chunk(&metadataParser, &header, pWav->allowedMetadataTypes); - DRWAV_ASSERT(bytesRead <= header.sizeInBytes); - - remainingBytes = header.sizeInBytes - bytesRead + header.paddingSize; - if (!drwav__seek_forward(pWav->onSeek, remainingBytes, pWav->pUserData)) { - break; + if (drwav__on_read(pWav->onRead, pWav->pUserData, commData, commDataBytesToRead, &cursor) != commDataBytesToRead) { + return DRWAV_FALSE; } - cursorForMetadata += remainingBytes; - } - if (!drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData)) { - return DRWAV_FALSE; - } - drwav__metadata_alloc(&metadataParser, &pWav->allocationCallbacks); - metadataParser.stage = drwav__metadata_parser_stage_read; - } + channels = drwav_bytes_to_u16_ex (commData + 0, pWav->container); + frameCount = drwav_bytes_to_u32_ex (commData + 2, pWav->container); + sampleSizeInBits = drwav_bytes_to_u16_ex (commData + 6, pWav->container); + sampleRate = drwav_aiff_extented_to_s64(commData + 8); - /* - We need to enumerate over each chunk for two reasons: - 1) The "data" chunk may not be the next one - 2) We may want to report each chunk back to the client + if (sampleRate < 0 || sampleRate > 0xFFFFFFFF) { + return DRWAV_FALSE; /* Invalid sample rate. */ + } - In order to correctly report each chunk back to the client we will need to keep looping until the end of the file. - */ - foundDataChunk = DRWAV_FALSE; + if (isAIFCFormType) { + const drwav_uint8* type = commData + 18; - /* The next chunk we care about is the "data" chunk. This is not necessarily the next chunk so we'll need to loop. */ - for (;;) { - drwav_chunk_header header; - drwav_result result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header); - if (result != DRWAV_SUCCESS) { - if (!foundDataChunk) { - return DRWAV_FALSE; + if (drwav_fourcc_equal(type, "NONE")) { + compressionFormat = DR_WAVE_FORMAT_PCM; /* PCM, big-endian. */ + } else if (drwav_fourcc_equal(type, "raw ")) { + compressionFormat = DR_WAVE_FORMAT_PCM; + + /* In my testing, it looks like when the "raw " compression type is used, 8-bit samples should be considered unsigned. */ + if (sampleSizeInBits == 8) { + pWav->aiff.isUnsigned = DRWAV_TRUE; + } + } else if (drwav_fourcc_equal(type, "sowt")) { + compressionFormat = DR_WAVE_FORMAT_PCM; /* PCM, little-endian. */ + pWav->aiff.isLE = DRWAV_TRUE; + } else if (drwav_fourcc_equal(type, "fl32") || drwav_fourcc_equal(type, "fl64") || drwav_fourcc_equal(type, "FL32") || drwav_fourcc_equal(type, "FL64")) { + compressionFormat = DR_WAVE_FORMAT_IEEE_FLOAT; + } else if (drwav_fourcc_equal(type, "alaw") || drwav_fourcc_equal(type, "ALAW")) { + compressionFormat = DR_WAVE_FORMAT_ALAW; + } else if (drwav_fourcc_equal(type, "ulaw") || drwav_fourcc_equal(type, "ULAW")) { + compressionFormat = DR_WAVE_FORMAT_MULAW; + } else if (drwav_fourcc_equal(type, "ima4")) { + compressionFormat = DR_WAVE_FORMAT_DVI_ADPCM; + sampleSizeInBits = 4; + + /* + I haven't been able to figure out how to get correct decoding for IMA ADPCM. Until this is figured out + we'll need to abort when we encounter such an encoding. Advice welcome! + */ + (void)compressionFormat; + (void)sampleSizeInBits; + + return DRWAV_FALSE; + } else { + return DRWAV_FALSE; /* Unknown or unsupported compression format. Need to abort. */ + } } else { - break; /* Probably at the end of the file. Get out of the loop. */ + compressionFormat = DR_WAVE_FORMAT_PCM; /* It's a standard AIFF form which is always compressed. */ } - } - /* Tell the client about this chunk. */ - if (!sequential && onChunk != NULL) { - drwav_uint64 callbackBytesRead = onChunk(pChunkUserData, pWav->onRead, pWav->onSeek, pWav->pUserData, &header, pWav->container, &fmt); + /* With AIFF we want to use the explicitly defined frame count rather than deriving it from the size of the chunk. */ + aiffFrameCount = frameCount; + + /* We should now have enough information to fill out our fmt structure. */ + fmt.formatTag = compressionFormat; + fmt.channels = channels; + fmt.sampleRate = (drwav_uint32)sampleRate; + fmt.bitsPerSample = sampleSizeInBits; + fmt.blockAlign = (drwav_uint16)(fmt.channels * fmt.bitsPerSample / 8); + fmt.avgBytesPerSec = fmt.blockAlign * fmt.sampleRate; + + if (fmt.blockAlign == 0 && compressionFormat == DR_WAVE_FORMAT_DVI_ADPCM) { + fmt.blockAlign = 34 * fmt.channels; + } /* - dr_wav may need to read the contents of the chunk, so we now need to seek back to the position before - we called the callback. + Weird one. I've seen some alaw and ulaw encoded files that for some reason set the bits per sample to 16 when + it should be 8. To get this working I need to explicitly check for this and change it. */ - if (callbackBytesRead > 0) { - if (!drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData)) { - return DRWAV_FALSE; + if (compressionFormat == DR_WAVE_FORMAT_ALAW || compressionFormat == DR_WAVE_FORMAT_MULAW) { + if (fmt.bitsPerSample > 8) { + fmt.bitsPerSample = 8; + fmt.blockAlign = fmt.channels; } } - } - if (!sequential && pWav->allowedMetadataTypes != drwav_metadata_type_none && (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64)) { - drwav_uint64 bytesRead = drwav__metadata_process_chunk(&metadataParser, &header, pWav->allowedMetadataTypes); + /* In AIFF, samples are padded to 8 byte boundaries. We need to round up our bits per sample here. */ + fmt.bitsPerSample += (fmt.bitsPerSample & 7); + - if (bytesRead > 0) { - if (!drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData)) { + /* If the form type is AIFC there will be some additional data in the chunk. We need to seek past it. */ + if (isAIFCFormType) { + if (drwav__seek_forward(pWav->onSeek, (chunkSize - commDataBytesToRead), pWav->pUserData) == DRWAV_FALSE) { return DRWAV_FALSE; } + cursor += (chunkSize - commDataBytesToRead); } + + /* Don't fall through or else we'll end up treating this chunk as metadata which is incorrect. */ + continue; } - if (!foundDataChunk) { - pWav->dataChunkDataPos = cursor; - } + /* "SSND". AIFF/AIFC only. This is the AIFF equivalent of the "data" chunk. */ + if (pWav->container == drwav_container_aiff && drwav_fourcc_equal(header.id.fourcc, "SSND")) { + drwav_uint8 offsetAndBlockSizeData[8]; + drwav_uint32 offset; - chunkSize = header.sizeInBytes; - if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64) { - if (drwav_fourcc_equal(header.id.fourcc, "data")) { - foundDataChunk = DRWAV_TRUE; - if (pWav->container != drwav_container_rf64) { /* The data chunk size for RF64 will always be set to 0xFFFFFFFF here. It was set to it's true value earlier. */ - dataChunkSize = chunkSize; - } + foundChunk_data = DRWAV_TRUE; + + if (drwav__on_read(pWav->onRead, pWav->pUserData, offsetAndBlockSizeData, sizeof(offsetAndBlockSizeData), &cursor) != sizeof(offsetAndBlockSizeData)) { + return DRWAV_FALSE; } - } else { - if (drwav_guid_equal(header.id.guid, drwavGUID_W64_DATA)) { - foundDataChunk = DRWAV_TRUE; - dataChunkSize = chunkSize; + + /* The position of the audio data starts at an offset. */ + offset = drwav_bytes_to_u32_ex(offsetAndBlockSizeData + 0, pWav->container); + pWav->dataChunkDataPos = cursor + offset; + + /* The data chunk size needs to be reduced by the offset or else seeking will break. */ + dataChunkSize = chunkSize; + if (dataChunkSize > offset) { + dataChunkSize -= offset; + } else { + dataChunkSize = 0; } - } - /* - If at this point we have found the data chunk and we're running in sequential mode, we need to break out of this loop. The reason for - this is that we would otherwise require a backwards seek which sequential mode forbids. - */ - if (foundDataChunk && sequential) { - break; - } + if (sequential) { + if (foundChunk_fmt) { /* <-- Name is misleading, but will be set to true if the COMM chunk has been parsed. */ + /* + Getting here means we're opening in sequential mode and we've found the SSND (data) and COMM (fmt) chunks. We need + to get out of the loop here or else we'll end up going past the data chunk and will have no way of getting back to + it since we're not allowed to seek backwards. + + One subtle detail here is that there is an offset with the SSND chunk. We need to make sure we seek past this offset + so we're left sitting on the first byte of actual audio data. + */ + if (drwav__seek_forward(pWav->onSeek, offset, pWav->pUserData) == DRWAV_FALSE) { + return DRWAV_FALSE; + } + cursor += offset; - /* Optional. Get the total sample count from the FACT chunk. This is useful for compressed formats. */ - if (pWav->container == drwav_container_riff) { - if (drwav_fourcc_equal(header.id.fourcc, "fact")) { - drwav_uint32 sampleCount; - if (drwav__on_read(pWav->onRead, pWav->pUserData, &sampleCount, 4, &cursor) != 4) { - return DRWAV_FALSE; + break; + } else { + /* + Getting here means the COMM chunk was not found. In sequential mode, if we haven't yet found the COMM chunk + we'll need to abort because we can't be doing a backwards seek back to the SSND chunk in order to read the + data. For this reason, this configuration of AIFF files are not supported with sequential mode. + */ + return DRWAV_FALSE; } - chunkSize -= 4; + } else { + chunkSize += header.paddingSize; /* <-- Make sure we seek past the padding. */ + chunkSize -= sizeof(offsetAndBlockSizeData); /* <-- This was read earlier. */ - if (!foundDataChunk) { - pWav->dataChunkDataPos = cursor; + if (drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == DRWAV_FALSE) { + break; } + cursor += chunkSize; - /* - The sample count in the "fact" chunk is either unreliable, or I'm not understanding it properly. For now I am only enabling this - for Microsoft ADPCM formats. - */ - if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) { - sampleCountFromFactChunk = sampleCount; - } else { - sampleCountFromFactChunk = 0; - } + continue; /* There may be some more metadata to read. */ } - } else if (pWav->container == drwav_container_w64) { - if (drwav_guid_equal(header.id.guid, drwavGUID_W64_FACT)) { - if (drwav__on_read(pWav->onRead, pWav->pUserData, &sampleCountFromFactChunk, 8, &cursor) != 8) { - return DRWAV_FALSE; - } - chunkSize -= 8; + } - if (!foundDataChunk) { - pWav->dataChunkDataPos = cursor; - } + + /* Getting here means it's not a chunk that we care about internally, but might need to be handled as metadata by the caller. */ + if (isProcessingMetadata) { + drwav__metadata_process_chunk(&metadataParser, &header, drwav_metadata_type_all_including_unknown); + + /* Go back to the start of the chunk so we can normalize the position of the cursor. */ + if (drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData) == DRWAV_FALSE) { + break; /* Failed to seek. Can't reliable read the remaining chunks. Get out. */ } - } else if (pWav->container == drwav_container_rf64) { - /* We retrieved the sample count from the ds64 chunk earlier so no need to do that here. */ } - /* Make sure we seek past the padding. */ - chunkSize += header.paddingSize; - if (!drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData)) { + + /* Make sure we skip past the content of this chunk before we go to the next one. */ + chunkSize += header.paddingSize; /* <-- Make sure we seek past the padding. */ + if (drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == DRWAV_FALSE) { break; } cursor += chunkSize; + } - if (!foundDataChunk) { - pWav->dataChunkDataPos = cursor; - } + /* There's some mandatory chunks that must exist. If they were not found in the iteration above we must abort. */ + if (!foundChunk_fmt || !foundChunk_data) { + return DRWAV_FALSE; } - pWav->pMetadata = metadataParser.pMetadata; - pWav->metadataCount = metadataParser.metadataCount; + /* Basic validation. */ + if ((fmt.sampleRate == 0 || fmt.sampleRate > DRWAV_MAX_SAMPLE_RATE ) || + (fmt.channels == 0 || fmt.channels > DRWAV_MAX_CHANNELS ) || + (fmt.bitsPerSample == 0 || fmt.bitsPerSample > DRWAV_MAX_BITS_PER_SAMPLE) || + fmt.blockAlign == 0) { + return DRWAV_FALSE; /* Probably an invalid WAV file. */ + } - /* If we haven't found a data chunk, return an error. */ - if (!foundDataChunk) { - return DRWAV_FALSE; + /* Translate the internal format. */ + translatedFormatTag = fmt.formatTag; + if (translatedFormatTag == DR_WAVE_FORMAT_EXTENSIBLE) { + translatedFormatTag = drwav_bytes_to_u16_ex(fmt.subFormat + 0, pWav->container); } /* We may have moved passed the data chunk. If so we need to move back. If running in sequential mode we can assume we are already sitting on the data chunk. */ @@ -3355,21 +3633,109 @@ DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc on } + /* + At this point we should have done the initial parsing of each of our chunks, but we now need to + do a second pass to extract the actual contents of the metadata (the first pass just calculated + the length of the memory allocation). + + We only do this if we've actually got metadata to parse. + */ + if (isProcessingMetadata && metadataParser.metadataCount > 0) { + if (drwav__seek_from_start(pWav->onSeek, metadataStartPos, pWav->pUserData) == DRWAV_FALSE) { + return DRWAV_FALSE; + } + + result = drwav__metadata_alloc(&metadataParser, &pWav->allocationCallbacks); + if (result != DRWAV_SUCCESS) { + return DRWAV_FALSE; + } + + metadataParser.stage = drwav__metadata_parser_stage_read; + + for (;;) { + drwav_chunk_header header; + drwav_uint64 metadataBytesRead; + + result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header); + if (result != DRWAV_SUCCESS) { + break; + } + + metadataBytesRead = drwav__metadata_process_chunk(&metadataParser, &header, drwav_metadata_type_all_including_unknown); + + /* Move to the end of the chunk so we can keep iterating. */ + if (drwav__seek_forward(pWav->onSeek, (header.sizeInBytes + header.paddingSize) - metadataBytesRead, pWav->pUserData) == DRWAV_FALSE) { + drwav_free(metadataParser.pMetadata, &pWav->allocationCallbacks); + return DRWAV_FALSE; + } + } + + /* Getting here means we're finished parsing the metadata. */ + pWav->pMetadata = metadataParser.pMetadata; + pWav->metadataCount = metadataParser.metadataCount; + } + + /* At this point we should be sitting on the first byte of the raw audio data. */ + if (drwav__seek_from_start(pWav->onSeek, pWav->dataChunkDataPos, pWav->pUserData) == DRWAV_FALSE) { + drwav_free(pWav->pMetadata, &pWav->allocationCallbacks); + return DRWAV_FALSE; + } + + /* + I've seen a WAV file in the wild where a RIFF-ecapsulated file has the size of it's "RIFF" and + "data" chunks set to 0xFFFFFFFF when the file is definitely not that big. In this case we're + going to have to calculate the size by reading and discarding bytes, and then seeking back. We + cannot do this in sequential mode. We just assume that the rest of the file is audio data. + */ + if (dataChunkSize == 0xFFFFFFFF && (pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx) && pWav->isSequentialWrite == DRWAV_FALSE) { + dataChunkSize = 0; + + for (;;) { + drwav_uint8 temp[4096]; + size_t bytesRead = pWav->onRead(pWav->pUserData, temp, sizeof(temp)); + dataChunkSize += bytesRead; + + if (bytesRead < sizeof(temp)) { + break; + } + } + } pWav->fmt = fmt; pWav->sampleRate = fmt.sampleRate; pWav->channels = fmt.channels; pWav->bitsPerSample = fmt.bitsPerSample; - pWav->bytesRemaining = dataChunkSize; pWav->translatedFormatTag = translatedFormatTag; + + /* + I've had a report where files would start glitching after seeking. The reason for this is the data + chunk is not a clean multiple of the PCM frame size in bytes. Where this becomes a problem is when + seeking, because the number of bytes remaining in the data chunk is used to calculate the current + byte position. If this byte position is not aligned to the number of bytes in a PCM frame, it will + result in the seek not being cleanly positioned at the start of the PCM frame thereby resulting in + all decoded frames after that being corrupted. + + To address this, we need to round the data chunk size down to the nearest multiple of the frame size. + */ + if (!drwav__is_compressed_format_tag(translatedFormatTag)) { + drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame > 0) { + dataChunkSize -= (dataChunkSize % bytesPerFrame); + } + } + + pWav->bytesRemaining = dataChunkSize; pWav->dataChunkDataSize = dataChunkSize; if (sampleCountFromFactChunk != 0) { pWav->totalPCMFrameCount = sampleCountFromFactChunk; + } else if (aiffFrameCount != 0) { + pWav->totalPCMFrameCount = aiffFrameCount; } else { drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav); if (bytesPerFrame == 0) { + drwav_free(pWav->pMetadata, &pWav->allocationCallbacks); return DRWAV_FALSE; /* Invalid file. */ } @@ -3409,12 +3775,14 @@ DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc on /* Some formats only support a certain number of channels. */ if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) { if (pWav->channels > 2) { + drwav_free(pWav->pMetadata, &pWav->allocationCallbacks); return DRWAV_FALSE; } } /* The number of bytes per frame must be known. If not, it's an invalid file and not decodable. */ if (drwav_get_bytes_per_pcm_frame(pWav) == 0) { + drwav_free(pWav->pMetadata, &pWav->allocationCallbacks); return DRWAV_FALSE; } @@ -3460,8 +3828,7 @@ DRWAV_API drwav_bool32 drwav_init_with_metadata(drwav* pWav, drwav_read_proc onR return DRWAV_FALSE; } - pWav->allowedMetadataTypes = drwav_metadata_type_all_including_unknown; /* <-- Needs to be set to tell drwav_init_ex() that we need to process metadata. */ - return drwav_init__internal(pWav, NULL, NULL, flags); + return drwav_init__internal(pWav, NULL, NULL, flags | DRWAV_WITH_METADATA); } DRWAV_API drwav_metadata* drwav_take_ownership_of_metadata(drwav* pWav) @@ -3672,15 +4039,15 @@ DRWAV_PRIVATE size_t drwav__write_or_count_metadata(drwav* pWav, drwav_metadata* for (iLoop = 0; iLoop < pMetadata->data.smpl.sampleLoopCount; ++iLoop) { bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].cuePointId); bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].type); - bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].firstSampleByteOffset); - bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].lastSampleByteOffset); + bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].firstSampleOffset); + bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].lastSampleOffset); bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].sampleFraction); bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].playCount); } if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) { - bytesWritten += drwav__write(pWav, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes); - } + bytesWritten += drwav__write_or_count(pWav, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes); + } } break; case drwav_metadata_type_inst: @@ -3713,7 +4080,7 @@ DRWAV_PRIVATE size_t drwav__write_or_count_metadata(drwav* pWav, drwav_metadata* bytesWritten += drwav__write_or_count(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId, 4); bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart); bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].blockStart); - bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].sampleByteOffset); + bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].sampleOffset); } } break; @@ -3872,7 +4239,7 @@ DRWAV_PRIVATE size_t drwav__write_or_count_metadata(drwav* pWav, drwav_metadata* if (pMetadata->data.labelOrNote.stringLength > 0) { chunkSize += pMetadata->data.labelOrNote.stringLength + 1; - } + } } break; case drwav_metadata_type_list_labelled_cue_region: @@ -4124,6 +4491,8 @@ DRWAV_PRIVATE drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_d runningPos += drwav__write(pWav, "RF64", 4); runningPos += drwav__write_u32ne_to_le(pWav, 0xFFFFFFFF); /* Always 0xFFFFFFFF for RF64. Set to a proper value in the "ds64" chunk. */ runningPos += drwav__write(pWav, "WAVE", 4); + } else { + return DRWAV_FALSE; /* Container not supported for writing. */ } @@ -4257,6 +4626,7 @@ DRWAV_API drwav_uint64 drwav_target_write_size_bytes(const drwav_data_format* pF #ifndef DR_WAV_NO_STDIO +/* Errno */ /* drwav_result_from_errno() is only used for fopen() and wfopen() so putting it inside DR_WAV_NO_STDIO for now. If something else needs this later we can move it out. */ #include DRWAV_PRIVATE drwav_result drwav_result_from_errno(int e) @@ -4378,7 +4748,7 @@ DRWAV_PRIVATE drwav_result drwav_result_from_errno(int e) #ifdef ENOSYS case ENOSYS: return DRWAV_NOT_IMPLEMENTED; #endif - #ifdef ENOTEMPTY + #if defined(ENOTEMPTY) && ENOTEMPTY != EEXIST /* In AIX, ENOTEMPTY and EEXIST use the same value. */ case ENOTEMPTY: return DRWAV_DIRECTORY_NOT_EMPTY; #endif #ifdef ELOOP @@ -4660,7 +5030,9 @@ DRWAV_PRIVATE drwav_result drwav_result_from_errno(int e) default: return DRWAV_ERROR; } } +/* End Errno */ +/* fopen */ DRWAV_PRIVATE drwav_result drwav_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode) { #if defined(_MSC_VER) && _MSC_VER >= 1400 @@ -4721,6 +5093,7 @@ fallback, so if you notice your compiler not detecting this properly I'm happy t #endif #endif +#ifndef DR_WAV_NO_WCHAR DRWAV_PRIVATE drwav_result drwav_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drwav_allocation_callbacks* pAllocationCallbacks) { if (ppFile != NULL) { @@ -4748,11 +5121,24 @@ DRWAV_PRIVATE drwav_result drwav_wfopen(FILE** ppFile, const wchar_t* pFilePath, (void)pAllocationCallbacks; } #else - /* - Use fopen() on anything other than Windows. Requires a conversion. This is annoying because fopen() is locale specific. The only real way I can - think of to do this is with wcsrtombs(). Note that wcstombs() is apparently not thread-safe because it uses a static global mbstate_t object for - maintaining state. I've checked this with -std=c89 and it works, but if somebody get's a compiler error I'll look into improving compatibility. + /* + Use fopen() on anything other than Windows. Requires a conversion. This is annoying because + fopen() is locale specific. The only real way I can think of to do this is with wcsrtombs(). Note + that wcstombs() is apparently not thread-safe because it uses a static global mbstate_t object for + maintaining state. I've checked this with -std=c89 and it works, but if somebody get's a compiler + error I'll look into improving compatibility. */ + + /* + Some compilers don't support wchar_t or wcsrtombs() which we're using below. In this case we just + need to abort with an error. If you encounter a compiler lacking such support, add it to this list + and submit a bug report and it'll be added to the library upstream. + */ + #if defined(__DJGPP__) + { + /* Nothing to do here. This will fall through to the error check below. */ + } + #else { mbstate_t mbs; size_t lenMB; @@ -4794,6 +5180,7 @@ DRWAV_PRIVATE drwav_result drwav_wfopen(FILE** ppFile, const wchar_t* pFilePath, drwav__free_from_callbacks(pFilePathMB, pAllocationCallbacks); } + #endif if (*ppFile == NULL) { return DRWAV_ERROR; @@ -4802,6 +5189,8 @@ DRWAV_PRIVATE drwav_result drwav_wfopen(FILE** ppFile, const wchar_t* pFilePath, return DRWAV_SUCCESS; } +#endif +/* End fopen */ DRWAV_PRIVATE size_t drwav__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead) @@ -4825,7 +5214,7 @@ DRWAV_API drwav_bool32 drwav_init_file(drwav* pWav, const char* filename, const } -DRWAV_PRIVATE drwav_bool32 drwav_init_file__internal_FILE(drwav* pWav, FILE* pFile, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, drwav_metadata_type allowedMetadataTypes, const drwav_allocation_callbacks* pAllocationCallbacks) +DRWAV_PRIVATE drwav_bool32 drwav_init_file__internal_FILE(drwav* pWav, FILE* pFile, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks) { drwav_bool32 result; @@ -4834,8 +5223,6 @@ DRWAV_PRIVATE drwav_bool32 drwav_init_file__internal_FILE(drwav* pWav, FILE* pFi fclose(pFile); return result; } - - pWav->allowedMetadataTypes = allowedMetadataTypes; result = drwav_init__internal(pWav, onChunk, pChunkUserData, flags); if (result != DRWAV_TRUE) { @@ -4854,9 +5241,10 @@ DRWAV_API drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drw } /* This takes ownership of the FILE* object. */ - return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, drwav_metadata_type_none, pAllocationCallbacks); + return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, pAllocationCallbacks); } +#ifndef DR_WAV_NO_WCHAR DRWAV_API drwav_bool32 drwav_init_file_w(drwav* pWav, const wchar_t* filename, const drwav_allocation_callbacks* pAllocationCallbacks) { return drwav_init_file_ex_w(pWav, filename, NULL, NULL, 0, pAllocationCallbacks); @@ -4870,8 +5258,9 @@ DRWAV_API drwav_bool32 drwav_init_file_ex_w(drwav* pWav, const wchar_t* filename } /* This takes ownership of the FILE* object. */ - return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, drwav_metadata_type_none, pAllocationCallbacks); + return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, pAllocationCallbacks); } +#endif DRWAV_API drwav_bool32 drwav_init_file_with_metadata(drwav* pWav, const char* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks) { @@ -4881,9 +5270,10 @@ DRWAV_API drwav_bool32 drwav_init_file_with_metadata(drwav* pWav, const char* fi } /* This takes ownership of the FILE* object. */ - return drwav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags, drwav_metadata_type_all_including_unknown, pAllocationCallbacks); + return drwav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags | DRWAV_WITH_METADATA, pAllocationCallbacks); } +#ifndef DR_WAV_NO_WCHAR DRWAV_API drwav_bool32 drwav_init_file_with_metadata_w(drwav* pWav, const wchar_t* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks) { FILE* pFile; @@ -4892,8 +5282,9 @@ DRWAV_API drwav_bool32 drwav_init_file_with_metadata_w(drwav* pWav, const wchar_ } /* This takes ownership of the FILE* object. */ - return drwav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags, drwav_metadata_type_all_including_unknown, pAllocationCallbacks); + return drwav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags | DRWAV_WITH_METADATA, pAllocationCallbacks); } +#endif DRWAV_PRIVATE drwav_bool32 drwav_init_file_write__internal_FILE(drwav* pWav, FILE* pFile, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks) @@ -4926,6 +5317,7 @@ DRWAV_PRIVATE drwav_bool32 drwav_init_file_write__internal(drwav* pWav, const ch return drwav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks); } +#ifndef DR_WAV_NO_WCHAR DRWAV_PRIVATE drwav_bool32 drwav_init_file_write_w__internal(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks) { FILE* pFile; @@ -4936,6 +5328,7 @@ DRWAV_PRIVATE drwav_bool32 drwav_init_file_write_w__internal(drwav* pWav, const /* This takes ownership of the FILE* object. */ return drwav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks); } +#endif DRWAV_API drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks) { @@ -4956,6 +5349,7 @@ DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames(drwav* pWav, return drwav_init_file_write_sequential(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks); } +#ifndef DR_WAV_NO_WCHAR DRWAV_API drwav_bool32 drwav_init_file_write_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks) { return drwav_init_file_write_w__internal(pWav, filename, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks); @@ -4974,6 +5368,7 @@ DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames_w(drwav* pWav return drwav_init_file_write_sequential_w(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks); } +#endif #endif /* DR_WAV_NO_STDIO */ @@ -5132,9 +5527,7 @@ DRWAV_API drwav_bool32 drwav_init_memory_with_metadata(drwav* pWav, const void* pWav->memoryStream.dataSize = dataSize; pWav->memoryStream.currentReadPos = 0; - pWav->allowedMetadataTypes = drwav_metadata_type_all_including_unknown; - - return drwav_init__internal(pWav, NULL, NULL, flags); + return drwav_init__internal(pWav, NULL, NULL, flags | DRWAV_WITH_METADATA); } @@ -5263,9 +5656,7 @@ DRWAV_API drwav_result drwav_uninit(drwav* pWav) } } } else { - if (pWav->pMetadata != NULL) { - pWav->allocationCallbacks.onFree(pWav->pMetadata, pWav->allocationCallbacks.pUserData); - } + drwav_free(pWav->pMetadata, &pWav->allocationCallbacks); } #ifndef DR_WAV_NO_STDIO @@ -5353,6 +5744,7 @@ DRWAV_API drwav_uint64 drwav_read_pcm_frames_le(drwav* pWav, drwav_uint64 frames { drwav_uint32 bytesPerFrame; drwav_uint64 bytesToRead; /* Intentionally uint64 instead of size_t so we can do a check that we're not reading too much on 32-bit builds. */ + drwav_uint64 framesRemainingInFile; if (pWav == NULL || framesToRead == 0) { return 0; @@ -5363,6 +5755,11 @@ DRWAV_API drwav_uint64 drwav_read_pcm_frames_le(drwav* pWav, drwav_uint64 frames return 0; } + framesRemainingInFile = pWav->totalPCMFrameCount - pWav->readCursorInPCMFrames; + if (framesToRead > framesRemainingInFile) { + framesToRead = framesRemainingInFile; + } + bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav); if (bytesPerFrame == 0) { return 0; @@ -5395,7 +5792,7 @@ DRWAV_API drwav_uint64 drwav_read_pcm_frames_be(drwav* pWav, drwav_uint64 frames return 0; /* Could not get the bytes per frame which means bytes per sample cannot be determined and we don't know how to byte swap. */ } - drwav__bswap_samples(pBufferOut, framesRead*pWav->channels, bytesPerFrame/pWav->channels, pWav->translatedFormatTag); + drwav__bswap_samples(pBufferOut, framesRead*pWav->channels, bytesPerFrame/pWav->channels); } return framesRead; @@ -5403,11 +5800,50 @@ DRWAV_API drwav_uint64 drwav_read_pcm_frames_be(drwav* pWav, drwav_uint64 frames DRWAV_API drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut) { + drwav_uint64 framesRead = 0; + + if (drwav_is_container_be(pWav->container)) { + /* + Special case for AIFF. AIFF is a big-endian encoded format, but it supports a format that is + PCM in little-endian encoding. In this case, we fall through this branch and treate it as + little-endian. + */ + if (pWav->container != drwav_container_aiff || pWav->aiff.isLE == DRWAV_FALSE) { + if (drwav__is_little_endian()) { + framesRead = drwav_read_pcm_frames_be(pWav, framesToRead, pBufferOut); + } else { + framesRead = drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut); + } + + goto post_process; + } + } + + /* Getting here means the data should be considered little-endian. */ if (drwav__is_little_endian()) { - return drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut); + framesRead = drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut); } else { - return drwav_read_pcm_frames_be(pWav, framesToRead, pBufferOut); + framesRead = drwav_read_pcm_frames_be(pWav, framesToRead, pBufferOut); + } + + /* + Here is where we check if we need to do a signed/unsigned conversion for AIFF. The reason we need to do this + is because dr_wav always assumes an 8-bit sample is unsigned, whereas AIFF can have signed 8-bit formats. + */ + post_process: + { + if (pWav->container == drwav_container_aiff && pWav->bitsPerSample == 8 && pWav->aiff.isUnsigned == DRWAV_FALSE) { + if (pBufferOut != NULL) { + drwav_uint64 iSample; + + for (iSample = 0; iSample < framesRead * pWav->channels; iSample += 1) { + ((drwav_uint8*)pBufferOut)[iSample] += 128; + } + } + } } + + return framesRead; } @@ -5518,7 +5954,7 @@ DRWAV_API drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetF } totalSizeInBytes = pWav->totalPCMFrameCount * bytesPerFrame; - DRWAV_ASSERT(totalSizeInBytes >= pWav->bytesRemaining); + /*DRWAV_ASSERT(totalSizeInBytes >= pWav->bytesRemaining);*/ currentBytePos = totalSizeInBytes - pWav->bytesRemaining; targetBytePos = targetFrameIndex * bytesPerFrame; @@ -5680,7 +6116,7 @@ DRWAV_API drwav_uint64 drwav_write_pcm_frames_be(drwav* pWav, drwav_uint64 frame } DRWAV_COPY_MEMORY(temp, pRunningData, (size_t)bytesToWriteThisIteration); - drwav__bswap_samples(temp, sampleCount, bytesPerSample, pWav->translatedFormatTag); + drwav__bswap_samples(temp, sampleCount, bytesPerSample); bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, temp); if (bytesJustWritten == 0) { @@ -5709,6 +6145,13 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav { drwav_uint64 totalFramesRead = 0; + static drwav_int32 adaptationTable[] = { + 230, 230, 230, 230, 307, 409, 512, 614, + 768, 614, 512, 409, 307, 230, 230, 230 + }; + static drwav_int32 coeff1Table[] = { 256, 512, 0, 192, 240, 460, 392 }; + static drwav_int32 coeff2Table[] = { 0, -256, 0, 64, 0, -208, -232 }; + DRWAV_ASSERT(pWav != NULL); DRWAV_ASSERT(framesToRead > 0); @@ -5734,6 +6177,11 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][0]; pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[0][1]; pWav->msadpcm.cachedFrameCount = 2; + + /* The predictor is used as an index into coeff1Table so we'll need to validate to ensure it never overflows. */ + if (pWav->msadpcm.predictor[0] >= drwav_countof(coeff1Table)) { + return totalFramesRead; /* Invalid file. */ + } } else { /* Stereo. */ drwav_uint8 header[14]; @@ -5756,6 +6204,11 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][1]; pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[1][1]; pWav->msadpcm.cachedFrameCount = 2; + + /* The predictor is used as an index into coeff1Table so we'll need to validate to ensure it never overflows. */ + if (pWav->msadpcm.predictor[0] >= drwav_countof(coeff1Table) || pWav->msadpcm.predictor[1] >= drwav_countof(coeff2Table)) { + return totalFramesRead; /* Invalid file. */ + } } } @@ -5789,13 +6242,6 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav if (pWav->msadpcm.bytesRemainingInBlock == 0) { continue; } else { - static drwav_int32 adaptationTable[] = { - 230, 230, 230, 230, 307, 409, 512, 614, - 768, 614, 512, 409, 307, 230, 230, 230 - }; - static drwav_int32 coeff1Table[] = { 256, 512, 0, 192, 240, 460, 392 }; - static drwav_int32 coeff2Table[] = { 0, -256, 0, 64, 0, -208, -232 }; - drwav_uint8 nibbles; drwav_int32 nibble0; drwav_int32 nibble1; @@ -5933,7 +6379,7 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__ima(drwav* pWav, drwav_uin return totalFramesRead; /* Invalid data. */ } - pWav->ima.predictor[0] = drwav_bytes_to_s16(header + 0); + pWav->ima.predictor[0] = (drwav_int16)drwav_bytes_to_u16(header + 0); pWav->ima.stepIndex[0] = drwav_clamp(header[2], 0, (drwav_int32)drwav_countof(stepTable)-1); /* Clamp not necessary because we checked above, but adding here to silence a static analysis warning. */ pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[0]; pWav->ima.cachedFrameCount = 1; @@ -6307,6 +6753,23 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__alaw(drwav* pWav, drwav_ui drwav_alaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead); + /* + For some reason libsndfile seems to be returning samples of the opposite sign for a-law, but only + with AIFF files. For WAV files it seems to be the same as dr_wav. This is resulting in dr_wav's + automated tests failing. I'm not sure which is correct, but will assume dr_wav. If we're enforcing + libsndfile compatibility we'll swap the signs here. + */ + #ifdef DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == drwav_container_aiff) { + drwav_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; framesToRead -= framesRead; totalFramesRead += framesRead; @@ -6357,6 +6820,21 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__mulaw(drwav* pWav, drwav_u drwav_mulaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead); + /* + Just like with alaw, for some reason the signs between libsndfile and dr_wav are opposite. We just need to + swap the sign if we're compiling with libsndfile compatiblity so our automated tests don't fail. + */ + #ifdef DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == drwav_container_aiff) { + drwav_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; framesToRead -= framesRead; totalFramesRead += framesRead; @@ -6509,7 +6987,6 @@ DRWAV_API void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, siz } - DRWAV_PRIVATE void drwav__pcm_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample) { unsigned int i; @@ -6743,6 +7220,17 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__alaw(drwav* pWav, drwav_ui drwav_alaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead); + #ifdef DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == drwav_container_aiff) { + drwav_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; framesToRead -= framesRead; totalFramesRead += framesRead; @@ -6789,6 +7277,17 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__mulaw(drwav* pWav, drwav_u drwav_mulaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead); + #ifdef DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == drwav_container_aiff) { + drwav_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; framesToRead -= framesRead; totalFramesRead += framesRead; @@ -7200,6 +7699,17 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__alaw(drwav* pWav, drwav_ui drwav_alaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead); + #ifdef DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == drwav_container_aiff) { + drwav_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; framesToRead -= framesRead; totalFramesRead += framesRead; @@ -7246,6 +7756,17 @@ DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__mulaw(drwav* pWav, drwav_u drwav_mulaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead); + #ifdef DR_WAV_LIBSNDFILE_COMPAT + { + if (pWav->container == drwav_container_aiff) { + drwav_uint64 iSample; + for (iSample = 0; iSample < samplesRead; iSample += 1) { + pBufferOut[iSample] = -pBufferOut[iSample]; + } + } + } + #endif + pBufferOut += samplesRead; framesToRead -= framesRead; totalFramesRead += framesRead; @@ -7366,7 +7887,7 @@ DRWAV_API void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t samp } for (i = 0; i < sampleCount; ++i) { - *pOut++ = (drwav_int32)(2147483648.0 * pIn[i]); + *pOut++ = (drwav_int32)(2147483648.0f * pIn[i]); } } @@ -7667,6 +8188,7 @@ DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filen } +#ifndef DR_WAV_NO_WCHAR DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks) { drwav wav; @@ -7729,7 +8251,8 @@ DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32_w(const wchar_t* return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut); } -#endif +#endif /* DR_WAV_NO_WCHAR */ +#endif /* DR_WAV_NO_STDIO */ DRWAV_API drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks) { @@ -7817,7 +8340,7 @@ DRWAV_API drwav_int16 drwav_bytes_to_s16(const drwav_uint8* data) DRWAV_API drwav_uint32 drwav_bytes_to_u32(const drwav_uint8* data) { - return ((drwav_uint32)data[0] << 0) | ((drwav_uint32)data[1] << 8) | ((drwav_uint32)data[2] << 16) | ((drwav_uint32)data[3] << 24); + return drwav_bytes_to_u32_le(data); } DRWAV_API float drwav_bytes_to_f32(const drwav_uint8* data) @@ -7870,12 +8393,62 @@ DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b) a[3] == b[3]; } +#ifdef __MRC__ +/* Undo the pragma at the beginning of this file. */ +#pragma options opt reset +#endif + #endif /* dr_wav_c */ #endif /* DR_WAV_IMPLEMENTATION */ /* REVISION HISTORY ================ +v0.14.0 - TBD + - API CHANGE: The `firstSampleByteOffset`, `lastSampleByteOffset` and `sampleByteOffset` members of `drwav_cue_point` have been renamed to `firstSampleOffset`, `lastSampleOffset` and `sampleOffset`, respectively. + - Fix a static analysis warning. + - Fix compilation for AIX OS. + +v0.13.17 - 2024-12-17 + - Fix a possible crash when reading from MS-ADPCM encoded files. + - Improve detection of ARM64EC + +v0.13.16 - 2024-02-27 + - Fix a Wdouble-promotion warning. + +v0.13.15 - 2024-01-23 + - Relax some unnecessary validation that prevented some files from loading. + +v0.13.14 - 2023-12-02 + - Fix a warning about an unused variable. + +v0.13.13 - 2023-11-02 + - Fix a warning when compiling with Clang. + +v0.13.12 - 2023-08-07 + - Fix a possible crash in drwav_read_pcm_frames(). + +v0.13.11 - 2023-07-07 + - AIFF compatibility improvements. + +v0.13.10 - 2023-05-29 + - Fix a bug where drwav_init_with_metadata() does not decode any frames after initializtion. + +v0.13.9 - 2023-05-22 + - Add support for AIFF decoding (writing and metadata not supported). + - Add support for RIFX decoding (writing and metadata not supported). + - Fix a bug where metadata is not processed if it's located before the "fmt " chunk. + - Add a workaround for a type of malformed WAV file where the size of the "RIFF" and "data" chunks + are incorrectly set to 0xFFFFFFFF. + +v0.13.8 - 2023-03-25 + - Fix a possible null pointer dereference. + - Fix a crash when loading files with badly formed metadata. + +v0.13.7 - 2022-09-17 + - Fix compilation with DJGPP. + - Add support for disabling wchar_t with DR_WAV_NO_WCHAR. + v0.13.6 - 2022-04-10 - Fix compilation error on older versions of GCC. - Remove some dependencies on the standard library. @@ -8286,7 +8859,7 @@ For more information, please refer to =============================================================================== ALTERNATIVE 2 - MIT No Attribution =============================================================================== -Copyright 2020 David Reid +Copyright 2023 David Reid Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in diff --git a/libs/include/fmt123.h b/libs/include/fmt123.h deleted file mode 100644 index cc30a066..00000000 --- a/libs/include/fmt123.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - libmpg123: MPEG Audio Decoder library - - separate header just for audio format definitions not tied to - library code - - copyright 1995-2015 by the mpg123 project - free software under the terms of the LGPL 2.1 - see COPYING and AUTHORS files in distribution or http://mpg123.org -*/ - -#ifndef MPG123_ENC_H -#define MPG123_ENC_H - -/** \file fmt123.h Audio format definitions. */ - -/** \defgroup mpg123_enc mpg123 PCM sample encodings - * These are definitions for audio formats used by libmpg123 and - * libout123. - * - * @{ - */ - -/** An enum over all sample types possibly known to mpg123. - * The values are designed as bit flags to allow bitmasking for encoding - * families. - * This is also why the enum is not used as type for actual encoding variables, - * plain integers (at least 16 bit, 15 bit being used) cover the possible - * combinations of these flags. - * - * Note that (your build of) libmpg123 does not necessarily support all these. - * Usually, you can expect the 8bit encodings and signed 16 bit. - * Also 32bit float will be usual beginning with mpg123-1.7.0 . - * What you should bear in mind is that (SSE, etc) optimized routines may be - * absent for some formats. We do have SSE for 16, 32 bit and float, though. - * 24 bit integer is done via postprocessing of 32 bit output -- just cutting - * the last byte, no rounding, even. If you want better, do it yourself. - * - * All formats are in native byte order. If you need different endinaness, you - * can simply postprocess the output buffers (libmpg123 wouldn't do anything - * else). The macro MPG123_SAMPLESIZE() can be helpful there. - */ -enum mpg123_enc_enum -{ -/* 0000 0000 0000 1111 Some 8 bit integer encoding. */ - MPG123_ENC_8 = 0x00f -/* 0000 0000 0100 0000 Some 16 bit integer encoding. */ -, MPG123_ENC_16 = 0x040 -/* 0100 0000 0000 0000 Some 24 bit integer encoding. */ -, MPG123_ENC_24 = 0x4000 -/* 0000 0001 0000 0000 Some 32 bit integer encoding. */ -, MPG123_ENC_32 = 0x100 -/* 0000 0000 1000 0000 Some signed integer encoding. */ -, MPG123_ENC_SIGNED = 0x080 -/* 0000 1110 0000 0000 Some float encoding. */ -, MPG123_ENC_FLOAT = 0xe00 -/* 0000 0000 1101 0000 signed 16 bit */ -, MPG123_ENC_SIGNED_16 = (MPG123_ENC_16|MPG123_ENC_SIGNED|0x10) -/* 0000 0000 0110 0000 unsigned 16 bit */ -, MPG123_ENC_UNSIGNED_16 = (MPG123_ENC_16|0x20) -/* 0000 0000 0000 0001 unsigned 8 bit */ -, MPG123_ENC_UNSIGNED_8 = 0x01 -/* 0000 0000 1000 0010 signed 8 bit */ -, MPG123_ENC_SIGNED_8 = (MPG123_ENC_SIGNED|0x02) -/* 0000 0000 0000 0100 ulaw 8 bit */ -, MPG123_ENC_ULAW_8 = 0x04 -/* 0000 0000 0000 1000 alaw 8 bit */ -, MPG123_ENC_ALAW_8 = 0x08 -/* 0001 0001 1000 0000 signed 32 bit */ -, MPG123_ENC_SIGNED_32 = MPG123_ENC_32|MPG123_ENC_SIGNED|0x1000 -/* 0010 0001 0000 0000 unsigned 32 bit */ -, MPG123_ENC_UNSIGNED_32 = MPG123_ENC_32|0x2000 -/* 0101 0000 1000 0000 signed 24 bit */ -, MPG123_ENC_SIGNED_24 = MPG123_ENC_24|MPG123_ENC_SIGNED|0x1000 -/* 0110 0000 0000 0000 unsigned 24 bit */ -, MPG123_ENC_UNSIGNED_24 = MPG123_ENC_24|0x2000 -/* 0000 0010 0000 0000 32bit float */ -, MPG123_ENC_FLOAT_32 = 0x200 -/* 0000 0100 0000 0000 64bit float */ -, MPG123_ENC_FLOAT_64 = 0x400 -/* Any possibly known encoding from the list above. */ -, MPG123_ENC_ANY = ( MPG123_ENC_SIGNED_16 | MPG123_ENC_UNSIGNED_16 - | MPG123_ENC_UNSIGNED_8 | MPG123_ENC_SIGNED_8 - | MPG123_ENC_ULAW_8 | MPG123_ENC_ALAW_8 - | MPG123_ENC_SIGNED_32 | MPG123_ENC_UNSIGNED_32 - | MPG123_ENC_SIGNED_24 | MPG123_ENC_UNSIGNED_24 - | MPG123_ENC_FLOAT_32 | MPG123_ENC_FLOAT_64 ) -}; - -/** Get size of one PCM sample with given encoding. - * This is included both in libmpg123 and libout123. Both offer - * an API function to provide the macro results from library - * compile-time, not that of you application. This most likely - * does not matter as I do not expect any fresh PCM sample - * encoding to appear. But who knows? Perhaps the encoding type - * will be abused for funny things in future, not even plain PCM. - * And, by the way: Thomas really likes the ?: operator. - * \param enc the encoding (mpg123_enc_enum value) - * \return size of one sample in bytes - */ -#define MPG123_SAMPLESIZE(enc) ( \ - (enc) & MPG123_ENC_8 \ - ? 1 \ - : ( (enc) & MPG123_ENC_16 \ - ? 2 \ - : ( (enc) & MPG123_ENC_24 \ - ? 3 \ - : ( ( (enc) & MPG123_ENC_32 \ - || (enc) == MPG123_ENC_FLOAT_32 ) \ - ? 4 \ - : ( (enc) == MPG123_ENC_FLOAT_64 \ - ? 8 \ - : 0 \ -) ) ) ) ) - -/** Structure defining an audio format. - * Providing the members as individual function arguments to define a certain - * output format is easy enough. This struct makes is more comfortable to deal - * with a list of formats. - * Negative values for the members might be used to communicate use of default - * values. - */ -struct mpg123_fmt -{ - long rate; /**< sampling rate in Hz */ - int channels; /**< channel count */ - /** encoding code, can be single value or bitwise or of members of - * mpg123_enc_enum */ - int encoding; -}; - -/* @} */ - -#endif - diff --git a/libs/include/libpng/png.h b/libs/include/libpng/png.h deleted file mode 100644 index 139eb0dc..00000000 --- a/libs/include/libpng/png.h +++ /dev/null @@ -1,3247 +0,0 @@ - -/* png.h - header file for PNG reference library - * - * libpng version 1.6.37 - April 14, 2019 - * - * Copyright (c) 2018-2019 Cosmin Truta - * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson - * Copyright (c) 1996-1997 Andreas Dilger - * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. - * - * This code is released under the libpng license. (See LICENSE, below.) - * - * Authors and maintainers: - * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat - * libpng versions 0.89, June 1996, through 0.96, May 1997: Andreas Dilger - * libpng versions 0.97, January 1998, through 1.6.35, July 2018: - * Glenn Randers-Pehrson - * libpng versions 1.6.36, December 2018, through 1.6.37, April 2019: - * Cosmin Truta - * See also "Contributing Authors", below. - */ - -/* - * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE - * ========================================= - * - * PNG Reference Library License version 2 - * --------------------------------------- - * - * * Copyright (c) 1995-2019 The PNG Reference Library Authors. - * * Copyright (c) 2018-2019 Cosmin Truta. - * * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. - * * Copyright (c) 1996-1997 Andreas Dilger. - * * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. - * - * The software is supplied "as is", without warranty of any kind, - * express or implied, including, without limitation, the warranties - * of merchantability, fitness for a particular purpose, title, and - * non-infringement. In no event shall the Copyright owners, or - * anyone distributing the software, be liable for any damages or - * other liability, whether in contract, tort or otherwise, arising - * from, out of, or in connection with the software, or the use or - * other dealings in the software, even if advised of the possibility - * of such damage. - * - * Permission is hereby granted to use, copy, modify, and distribute - * this software, or portions hereof, for any purpose, without fee, - * subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you - * must not claim that you wrote the original software. If you - * use this software in a product, an acknowledgment in the product - * documentation would be appreciated, but is not required. - * - * 2. Altered source versions must be plainly marked as such, and must - * not be misrepresented as being the original software. - * - * 3. This Copyright notice may not be removed or altered from any - * source or altered source distribution. - * - * - * PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35) - * ----------------------------------------------------------------------- - * - * libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are - * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are - * derived from libpng-1.0.6, and are distributed according to the same - * disclaimer and license as libpng-1.0.6 with the following individuals - * added to the list of Contributing Authors: - * - * Simon-Pierre Cadieux - * Eric S. Raymond - * Mans Rullgard - * Cosmin Truta - * Gilles Vollant - * James Yu - * Mandar Sahastrabuddhe - * Google Inc. - * Vadim Barkov - * - * and with the following additions to the disclaimer: - * - * There is no warranty against interference with your enjoyment of - * the library or against infringement. There is no warranty that our - * efforts or the library will fulfill any of your particular purposes - * or needs. This library is provided with all faults, and the entire - * risk of satisfactory quality, performance, accuracy, and effort is - * with the user. - * - * Some files in the "contrib" directory and some configure-generated - * files that are distributed with libpng have other copyright owners, and - * are released under other open source licenses. - * - * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are - * Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from - * libpng-0.96, and are distributed according to the same disclaimer and - * license as libpng-0.96, with the following individuals added to the - * list of Contributing Authors: - * - * Tom Lane - * Glenn Randers-Pehrson - * Willem van Schaik - * - * libpng versions 0.89, June 1996, through 0.96, May 1997, are - * Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88, - * and are distributed according to the same disclaimer and license as - * libpng-0.88, with the following individuals added to the list of - * Contributing Authors: - * - * John Bowler - * Kevin Bracey - * Sam Bushell - * Magnus Holmgren - * Greg Roelofs - * Tom Tanner - * - * Some files in the "scripts" directory have other copyright owners, - * but are released under this license. - * - * libpng versions 0.5, May 1995, through 0.88, January 1996, are - * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. - * - * For the purposes of this copyright and license, "Contributing Authors" - * is defined as the following set of individuals: - * - * Andreas Dilger - * Dave Martindale - * Guy Eric Schalnat - * Paul Schmidt - * Tim Wegner - * - * The PNG Reference Library is supplied "AS IS". The Contributing - * Authors and Group 42, Inc. disclaim all warranties, expressed or - * implied, including, without limitation, the warranties of - * merchantability and of fitness for any purpose. The Contributing - * Authors and Group 42, Inc. assume no liability for direct, indirect, - * incidental, special, exemplary, or consequential damages, which may - * result from the use of the PNG Reference Library, even if advised of - * the possibility of such damage. - * - * Permission is hereby granted to use, copy, modify, and distribute this - * source code, or portions hereof, for any purpose, without fee, subject - * to the following restrictions: - * - * 1. The origin of this source code must not be misrepresented. - * - * 2. Altered versions must be plainly marked as such and must not - * be misrepresented as being the original source. - * - * 3. This Copyright notice may not be removed or altered from any - * source or altered source distribution. - * - * The Contributing Authors and Group 42, Inc. specifically permit, - * without fee, and encourage the use of this source code as a component - * to supporting the PNG file format in commercial products. If you use - * this source code in a product, acknowledgment is not required but would - * be appreciated. - * - * END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE. - * - * TRADEMARK - * ========= - * - * The name "libpng" has not been registered by the Copyright owners - * as a trademark in any jurisdiction. However, because libpng has - * been distributed and maintained world-wide, continually since 1995, - * the Copyright owners claim "common-law trademark protection" in any - * jurisdiction where common-law trademark is recognized. - */ - -/* - * A "png_get_copyright" function is available, for convenient use in "about" - * boxes and the like: - * - * printf("%s", png_get_copyright(NULL)); - * - * Also, the PNG logo (in PNG format, of course) is supplied in the - * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31). - */ - -/* - * The contributing authors would like to thank all those who helped - * with testing, bug fixes, and patience. This wouldn't have been - * possible without all of you. - * - * Thanks to Frank J. T. Wojcik for helping with the documentation. - */ - -/* Note about libpng version numbers: - * - * Due to various miscommunications, unforeseen code incompatibilities - * and occasional factors outside the authors' control, version numbering - * on the library has not always been consistent and straightforward. - * The following table summarizes matters since version 0.89c, which was - * the first widely used release: - * - * source png.h png.h shared-lib - * version string int version - * ------- ------ ----- ---------- - * 0.89c "1.0 beta 3" 0.89 89 1.0.89 - * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90] - * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95] - * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96] - * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97] - * 0.97c 0.97 97 2.0.97 - * 0.98 0.98 98 2.0.98 - * 0.99 0.99 98 2.0.99 - * 0.99a-m 0.99 99 2.0.99 - * 1.00 1.00 100 2.1.0 [100 should be 10000] - * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000] - * 1.0.1 png.h string is 10001 2.1.0 - * 1.0.1a-e identical to the 10002 from here on, the shared library - * 1.0.2 source version) 10002 is 2.V where V is the source code - * 1.0.2a-b 10003 version, except as noted. - * 1.0.3 10003 - * 1.0.3a-d 10004 - * 1.0.4 10004 - * 1.0.4a-f 10005 - * 1.0.5 (+ 2 patches) 10005 - * 1.0.5a-d 10006 - * 1.0.5e-r 10100 (not source compatible) - * 1.0.5s-v 10006 (not binary compatible) - * 1.0.6 (+ 3 patches) 10006 (still binary incompatible) - * 1.0.6d-f 10007 (still binary incompatible) - * 1.0.6g 10007 - * 1.0.6h 10007 10.6h (testing xy.z so-numbering) - * 1.0.6i 10007 10.6i - * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0) - * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible) - * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible) - * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible) - * 1.0.7 1 10007 (still compatible) - * ... - * 1.0.69 10 10069 10.so.0.69[.0] - * ... - * 1.2.59 13 10259 12.so.0.59[.0] - * ... - * 1.4.20 14 10420 14.so.0.20[.0] - * ... - * 1.5.30 15 10530 15.so.15.30[.0] - * ... - * 1.6.37 16 10637 16.so.16.37[.0] - * - * Henceforth the source version will match the shared-library major and - * minor numbers; the shared-library major version number will be used for - * changes in backward compatibility, as it is intended. - * The PNG_LIBPNG_VER macro, which is not used within libpng but is - * available for applications, is an unsigned integer of the form XYYZZ - * corresponding to the source version X.Y.Z (leading zeros in Y and Z). - * Beta versions were given the previous public release number plus a - * letter, until version 1.0.6j; from then on they were given the upcoming - * public release number plus "betaNN" or "rcNN". - * - * Binary incompatibility exists only when applications make direct access - * to the info_ptr or png_ptr members through png.h, and the compiled - * application is loaded with a different version of the library. - * - * DLLNUM will change each time there are forward or backward changes - * in binary compatibility (e.g., when a new feature is added). - * - * See libpng.txt or libpng.3 for more information. The PNG specification - * is available as a W3C Recommendation and as an ISO/IEC Standard; see - * - */ - -#ifndef PNG_H -#define PNG_H - -/* This is not the place to learn how to use libpng. The file libpng-manual.txt - * describes how to use libpng, and the file example.c summarizes it - * with some code on which to build. This file is useful for looking - * at the actual function definitions and structure components. If that - * file has been stripped from your copy of libpng, you can find it at - * - * - * If you just need to read a PNG file and don't want to read the documentation - * skip to the end of this file and read the section entitled 'simplified API'. - */ - -/* Version information for png.h - this should match the version in png.c */ -#define PNG_LIBPNG_VER_STRING "1.6.37" -#define PNG_HEADER_VERSION_STRING " libpng version 1.6.37 - April 14, 2019\n" - -#define PNG_LIBPNG_VER_SONUM 16 -#define PNG_LIBPNG_VER_DLLNUM 16 - -/* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */ -#define PNG_LIBPNG_VER_MAJOR 1 -#define PNG_LIBPNG_VER_MINOR 6 -#define PNG_LIBPNG_VER_RELEASE 37 - -/* This should be zero for a public release, or non-zero for a - * development version. [Deprecated] - */ -#define PNG_LIBPNG_VER_BUILD 0 - -/* Release Status */ -#define PNG_LIBPNG_BUILD_ALPHA 1 -#define PNG_LIBPNG_BUILD_BETA 2 -#define PNG_LIBPNG_BUILD_RC 3 -#define PNG_LIBPNG_BUILD_STABLE 4 -#define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7 - -/* Release-Specific Flags */ -#define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with - PNG_LIBPNG_BUILD_STABLE only */ -#define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with - PNG_LIBPNG_BUILD_SPECIAL */ -#define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with - PNG_LIBPNG_BUILD_PRIVATE */ - -#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE - -/* Careful here. At one time, Guy wanted to use 082, but that - * would be octal. We must not include leading zeros. - * Versions 0.7 through 1.0.0 were in the range 0 to 100 here - * (only version 1.0.0 was mis-numbered 100 instead of 10000). - * From version 1.0.1 it is: - * XXYYZZ, where XX=major, YY=minor, ZZ=release - */ -#define PNG_LIBPNG_VER 10637 /* 1.6.37 */ - -/* Library configuration: these options cannot be changed after - * the library has been built. - */ -#ifndef PNGLCONF_H -/* If pnglibconf.h is missing, you can - * copy scripts/pnglibconf.h.prebuilt to pnglibconf.h - */ -# include "pnglibconf.h" -#endif - -#ifndef PNG_VERSION_INFO_ONLY -/* Machine specific configuration. */ -# include "pngconf.h" -#endif - -/* - * Added at libpng-1.2.8 - * - * Ref MSDN: Private as priority over Special - * VS_FF_PRIVATEBUILD File *was not* built using standard release - * procedures. If this value is given, the StringFileInfo block must - * contain a PrivateBuild string. - * - * VS_FF_SPECIALBUILD File *was* built by the original company using - * standard release procedures but is a variation of the standard - * file of the same version number. If this value is given, the - * StringFileInfo block must contain a SpecialBuild string. - */ - -#ifdef PNG_USER_PRIVATEBUILD /* From pnglibconf.h */ -# define PNG_LIBPNG_BUILD_TYPE \ - (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE) -#else -# ifdef PNG_LIBPNG_SPECIALBUILD -# define PNG_LIBPNG_BUILD_TYPE \ - (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL) -# else -# define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE) -# endif -#endif - -#ifndef PNG_VERSION_INFO_ONLY - -/* Inhibit C++ name-mangling for libpng functions but not for system calls. */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Version information for C files, stored in png.c. This had better match - * the version above. - */ -#define png_libpng_ver png_get_header_ver(NULL) - -/* This file is arranged in several sections: - * - * 1. [omitted] - * 2. Any configuration options that can be specified by for the application - * code when it is built. (Build time configuration is in pnglibconf.h) - * 3. Type definitions (base types are defined in pngconf.h), structure - * definitions. - * 4. Exported library functions. - * 5. Simplified API. - * 6. Implementation options. - * - * The library source code has additional files (principally pngpriv.h) that - * allow configuration of the library. - */ - -/* Section 1: [omitted] */ - -/* Section 2: run time configuration - * See pnglibconf.h for build time configuration - * - * Run time configuration allows the application to choose between - * implementations of certain arithmetic APIs. The default is set - * at build time and recorded in pnglibconf.h, but it is safe to - * override these (and only these) settings. Note that this won't - * change what the library does, only application code, and the - * settings can (and probably should) be made on a per-file basis - * by setting the #defines before including png.h - * - * Use macros to read integers from PNG data or use the exported - * functions? - * PNG_USE_READ_MACROS: use the macros (see below) Note that - * the macros evaluate their argument multiple times. - * PNG_NO_USE_READ_MACROS: call the relevant library function. - * - * Use the alternative algorithm for compositing alpha samples that - * does not use division? - * PNG_READ_COMPOSITE_NODIV_SUPPORTED: use the 'no division' - * algorithm. - * PNG_NO_READ_COMPOSITE_NODIV: use the 'division' algorithm. - * - * How to handle benign errors if PNG_ALLOW_BENIGN_ERRORS is - * false? - * PNG_ALLOW_BENIGN_ERRORS: map calls to the benign error - * APIs to png_warning. - * Otherwise the calls are mapped to png_error. - */ - -/* Section 3: type definitions, including structures and compile time - * constants. - * See pngconf.h for base types that vary by machine/system - */ - -/* This triggers a compiler error in png.c, if png.c and png.h - * do not agree upon the version number. - */ -typedef char* png_libpng_version_1_6_37; - -/* Basic control structions. Read libpng-manual.txt or libpng.3 for more info. - * - * png_struct is the cache of information used while reading or writing a single - * PNG file. One of these is always required, although the simplified API - * (below) hides the creation and destruction of it. - */ -typedef struct png_struct_def png_struct; -typedef const png_struct * png_const_structp; -typedef png_struct * png_structp; -typedef png_struct * * png_structpp; - -/* png_info contains information read from or to be written to a PNG file. One - * or more of these must exist while reading or creating a PNG file. The - * information is not used by libpng during read but is used to control what - * gets written when a PNG file is created. "png_get_" function calls read - * information during read and "png_set_" functions calls write information - * when creating a PNG. - * been moved into a separate header file that is not accessible to - * applications. Read libpng-manual.txt or libpng.3 for more info. - */ -typedef struct png_info_def png_info; -typedef png_info * png_infop; -typedef const png_info * png_const_infop; -typedef png_info * * png_infopp; - -/* Types with names ending 'p' are pointer types. The corresponding types with - * names ending 'rp' are identical pointer types except that the pointer is - * marked 'restrict', which means that it is the only pointer to the object - * passed to the function. Applications should not use the 'restrict' types; - * it is always valid to pass 'p' to a pointer with a function argument of the - * corresponding 'rp' type. Different compilers have different rules with - * regard to type matching in the presence of 'restrict'. For backward - * compatibility libpng callbacks never have 'restrict' in their parameters and, - * consequentially, writing portable application code is extremely difficult if - * an attempt is made to use 'restrict'. - */ -typedef png_struct * PNG_RESTRICT png_structrp; -typedef const png_struct * PNG_RESTRICT png_const_structrp; -typedef png_info * PNG_RESTRICT png_inforp; -typedef const png_info * PNG_RESTRICT png_const_inforp; - -/* Three color definitions. The order of the red, green, and blue, (and the - * exact size) is not important, although the size of the fields need to - * be png_byte or png_uint_16 (as defined below). - */ -typedef struct png_color_struct -{ - png_byte red; - png_byte green; - png_byte blue; -} png_color; -typedef png_color * png_colorp; -typedef const png_color * png_const_colorp; -typedef png_color * * png_colorpp; - -typedef struct png_color_16_struct -{ - png_byte index; /* used for palette files */ - png_uint_16 red; /* for use in red green blue files */ - png_uint_16 green; - png_uint_16 blue; - png_uint_16 gray; /* for use in grayscale files */ -} png_color_16; -typedef png_color_16 * png_color_16p; -typedef const png_color_16 * png_const_color_16p; -typedef png_color_16 * * png_color_16pp; - -typedef struct png_color_8_struct -{ - png_byte red; /* for use in red green blue files */ - png_byte green; - png_byte blue; - png_byte gray; /* for use in grayscale files */ - png_byte alpha; /* for alpha channel files */ -} png_color_8; -typedef png_color_8 * png_color_8p; -typedef const png_color_8 * png_const_color_8p; -typedef png_color_8 * * png_color_8pp; - -/* - * The following two structures are used for the in-core representation - * of sPLT chunks. - */ -typedef struct png_sPLT_entry_struct -{ - png_uint_16 red; - png_uint_16 green; - png_uint_16 blue; - png_uint_16 alpha; - png_uint_16 frequency; -} png_sPLT_entry; -typedef png_sPLT_entry * png_sPLT_entryp; -typedef const png_sPLT_entry * png_const_sPLT_entryp; -typedef png_sPLT_entry * * png_sPLT_entrypp; - -/* When the depth of the sPLT palette is 8 bits, the color and alpha samples - * occupy the LSB of their respective members, and the MSB of each member - * is zero-filled. The frequency member always occupies the full 16 bits. - */ - -typedef struct png_sPLT_struct -{ - png_charp name; /* palette name */ - png_byte depth; /* depth of palette samples */ - png_sPLT_entryp entries; /* palette entries */ - png_int_32 nentries; /* number of palette entries */ -} png_sPLT_t; -typedef png_sPLT_t * png_sPLT_tp; -typedef const png_sPLT_t * png_const_sPLT_tp; -typedef png_sPLT_t * * png_sPLT_tpp; - -#ifdef PNG_TEXT_SUPPORTED -/* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file, - * and whether that contents is compressed or not. The "key" field - * points to a regular zero-terminated C string. The "text" fields can be a - * regular C string, an empty string, or a NULL pointer. - * However, the structure returned by png_get_text() will always contain - * the "text" field as a regular zero-terminated C string (possibly - * empty), never a NULL pointer, so it can be safely used in printf() and - * other string-handling functions. Note that the "itxt_length", "lang", and - * "lang_key" members of the structure only exist when the library is built - * with iTXt chunk support. Prior to libpng-1.4.0 the library was built by - * default without iTXt support. Also note that when iTXt *is* supported, - * the "lang" and "lang_key" fields contain NULL pointers when the - * "compression" field contains * PNG_TEXT_COMPRESSION_NONE or - * PNG_TEXT_COMPRESSION_zTXt. Note that the "compression value" is not the - * same as what appears in the PNG tEXt/zTXt/iTXt chunk's "compression flag" - * which is always 0 or 1, or its "compression method" which is always 0. - */ -typedef struct png_text_struct -{ - int compression; /* compression value: - -1: tEXt, none - 0: zTXt, deflate - 1: iTXt, none - 2: iTXt, deflate */ - png_charp key; /* keyword, 1-79 character description of "text" */ - png_charp text; /* comment, may be an empty string (ie "") - or a NULL pointer */ - size_t text_length; /* length of the text string */ - size_t itxt_length; /* length of the itxt string */ - png_charp lang; /* language code, 0-79 characters - or a NULL pointer */ - png_charp lang_key; /* keyword translated UTF-8 string, 0 or more - chars or a NULL pointer */ -} png_text; -typedef png_text * png_textp; -typedef const png_text * png_const_textp; -typedef png_text * * png_textpp; -#endif - -/* Supported compression types for text in PNG files (tEXt, and zTXt). - * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */ -#define PNG_TEXT_COMPRESSION_NONE_WR -3 -#define PNG_TEXT_COMPRESSION_zTXt_WR -2 -#define PNG_TEXT_COMPRESSION_NONE -1 -#define PNG_TEXT_COMPRESSION_zTXt 0 -#define PNG_ITXT_COMPRESSION_NONE 1 -#define PNG_ITXT_COMPRESSION_zTXt 2 -#define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */ - -/* png_time is a way to hold the time in an machine independent way. - * Two conversions are provided, both from time_t and struct tm. There - * is no portable way to convert to either of these structures, as far - * as I know. If you know of a portable way, send it to me. As a side - * note - PNG has always been Year 2000 compliant! - */ -typedef struct png_time_struct -{ - png_uint_16 year; /* full year, as in, 1995 */ - png_byte month; /* month of year, 1 - 12 */ - png_byte day; /* day of month, 1 - 31 */ - png_byte hour; /* hour of day, 0 - 23 */ - png_byte minute; /* minute of hour, 0 - 59 */ - png_byte second; /* second of minute, 0 - 60 (for leap seconds) */ -} png_time; -typedef png_time * png_timep; -typedef const png_time * png_const_timep; -typedef png_time * * png_timepp; - -#if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) ||\ - defined(PNG_USER_CHUNKS_SUPPORTED) -/* png_unknown_chunk is a structure to hold queued chunks for which there is - * no specific support. The idea is that we can use this to queue - * up private chunks for output even though the library doesn't actually - * know about their semantics. - * - * The data in the structure is set by libpng on read and used on write. - */ -typedef struct png_unknown_chunk_t -{ - png_byte name[5]; /* Textual chunk name with '\0' terminator */ - png_byte *data; /* Data, should not be modified on read! */ - size_t size; - - /* On write 'location' must be set using the flag values listed below. - * Notice that on read it is set by libpng however the values stored have - * more bits set than are listed below. Always treat the value as a - * bitmask. On write set only one bit - setting multiple bits may cause the - * chunk to be written in multiple places. - */ - png_byte location; /* mode of operation at read time */ -} -png_unknown_chunk; - -typedef png_unknown_chunk * png_unknown_chunkp; -typedef const png_unknown_chunk * png_const_unknown_chunkp; -typedef png_unknown_chunk * * png_unknown_chunkpp; -#endif - -/* Flag values for the unknown chunk location byte. */ -#define PNG_HAVE_IHDR 0x01 -#define PNG_HAVE_PLTE 0x02 -#define PNG_AFTER_IDAT 0x08 - -/* Maximum positive integer used in PNG is (2^31)-1 */ -#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL) -#define PNG_UINT_32_MAX ((png_uint_32)(-1)) -#define PNG_SIZE_MAX ((size_t)(-1)) - -/* These are constants for fixed point values encoded in the - * PNG specification manner (x100000) - */ -#define PNG_FP_1 100000 -#define PNG_FP_HALF 50000 -#define PNG_FP_MAX ((png_fixed_point)0x7fffffffL) -#define PNG_FP_MIN (-PNG_FP_MAX) - -/* These describe the color_type field in png_info. */ -/* color type masks */ -#define PNG_COLOR_MASK_PALETTE 1 -#define PNG_COLOR_MASK_COLOR 2 -#define PNG_COLOR_MASK_ALPHA 4 - -/* color types. Note that not all combinations are legal */ -#define PNG_COLOR_TYPE_GRAY 0 -#define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE) -#define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR) -#define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA) -#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA) -/* aliases */ -#define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA -#define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA - -/* This is for compression type. PNG 1.0-1.2 only define the single type. */ -#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */ -#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE - -/* This is for filter type. PNG 1.0-1.2 only define the single type. */ -#define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */ -#define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */ -#define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE - -/* These are for the interlacing type. These values should NOT be changed. */ -#define PNG_INTERLACE_NONE 0 /* Non-interlaced image */ -#define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */ -#define PNG_INTERLACE_LAST 2 /* Not a valid value */ - -/* These are for the oFFs chunk. These values should NOT be changed. */ -#define PNG_OFFSET_PIXEL 0 /* Offset in pixels */ -#define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */ -#define PNG_OFFSET_LAST 2 /* Not a valid value */ - -/* These are for the pCAL chunk. These values should NOT be changed. */ -#define PNG_EQUATION_LINEAR 0 /* Linear transformation */ -#define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */ -#define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */ -#define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */ -#define PNG_EQUATION_LAST 4 /* Not a valid value */ - -/* These are for the sCAL chunk. These values should NOT be changed. */ -#define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */ -#define PNG_SCALE_METER 1 /* meters per pixel */ -#define PNG_SCALE_RADIAN 2 /* radians per pixel */ -#define PNG_SCALE_LAST 3 /* Not a valid value */ - -/* These are for the pHYs chunk. These values should NOT be changed. */ -#define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */ -#define PNG_RESOLUTION_METER 1 /* pixels/meter */ -#define PNG_RESOLUTION_LAST 2 /* Not a valid value */ - -/* These are for the sRGB chunk. These values should NOT be changed. */ -#define PNG_sRGB_INTENT_PERCEPTUAL 0 -#define PNG_sRGB_INTENT_RELATIVE 1 -#define PNG_sRGB_INTENT_SATURATION 2 -#define PNG_sRGB_INTENT_ABSOLUTE 3 -#define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */ - -/* This is for text chunks */ -#define PNG_KEYWORD_MAX_LENGTH 79 - -/* Maximum number of entries in PLTE/sPLT/tRNS arrays */ -#define PNG_MAX_PALETTE_LENGTH 256 - -/* These determine if an ancillary chunk's data has been successfully read - * from the PNG header, or if the application has filled in the corresponding - * data in the info_struct to be written into the output file. The values - * of the PNG_INFO_ defines should NOT be changed. - */ -#define PNG_INFO_gAMA 0x0001U -#define PNG_INFO_sBIT 0x0002U -#define PNG_INFO_cHRM 0x0004U -#define PNG_INFO_PLTE 0x0008U -#define PNG_INFO_tRNS 0x0010U -#define PNG_INFO_bKGD 0x0020U -#define PNG_INFO_hIST 0x0040U -#define PNG_INFO_pHYs 0x0080U -#define PNG_INFO_oFFs 0x0100U -#define PNG_INFO_tIME 0x0200U -#define PNG_INFO_pCAL 0x0400U -#define PNG_INFO_sRGB 0x0800U /* GR-P, 0.96a */ -#define PNG_INFO_iCCP 0x1000U /* ESR, 1.0.6 */ -#define PNG_INFO_sPLT 0x2000U /* ESR, 1.0.6 */ -#define PNG_INFO_sCAL 0x4000U /* ESR, 1.0.6 */ -#define PNG_INFO_IDAT 0x8000U /* ESR, 1.0.6 */ -#define PNG_INFO_eXIf 0x10000U /* GR-P, 1.6.31 */ - -/* This is used for the transformation routines, as some of them - * change these values for the row. It also should enable using - * the routines for other purposes. - */ -typedef struct png_row_info_struct -{ - png_uint_32 width; /* width of row */ - size_t rowbytes; /* number of bytes in row */ - png_byte color_type; /* color type of row */ - png_byte bit_depth; /* bit depth of row */ - png_byte channels; /* number of channels (1, 2, 3, or 4) */ - png_byte pixel_depth; /* bits per pixel (depth * channels) */ -} png_row_info; - -typedef png_row_info * png_row_infop; -typedef png_row_info * * png_row_infopp; - -/* These are the function types for the I/O functions and for the functions - * that allow the user to override the default I/O functions with his or her - * own. The png_error_ptr type should match that of user-supplied warning - * and error functions, while the png_rw_ptr type should match that of the - * user read/write data functions. Note that the 'write' function must not - * modify the buffer it is passed. The 'read' function, on the other hand, is - * expected to return the read data in the buffer. - */ -typedef PNG_CALLBACK(void, *png_error_ptr, (png_structp, png_const_charp)); -typedef PNG_CALLBACK(void, *png_rw_ptr, (png_structp, png_bytep, size_t)); -typedef PNG_CALLBACK(void, *png_flush_ptr, (png_structp)); -typedef PNG_CALLBACK(void, *png_read_status_ptr, (png_structp, png_uint_32, - int)); -typedef PNG_CALLBACK(void, *png_write_status_ptr, (png_structp, png_uint_32, - int)); - -#ifdef PNG_PROGRESSIVE_READ_SUPPORTED -typedef PNG_CALLBACK(void, *png_progressive_info_ptr, (png_structp, png_infop)); -typedef PNG_CALLBACK(void, *png_progressive_end_ptr, (png_structp, png_infop)); - -/* The following callback receives png_uint_32 row_number, int pass for the - * png_bytep data of the row. When transforming an interlaced image the - * row number is the row number within the sub-image of the interlace pass, so - * the value will increase to the height of the sub-image (not the full image) - * then reset to 0 for the next pass. - * - * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to - * find the output pixel (x,y) given an interlaced sub-image pixel - * (row,col,pass). (See below for these macros.) - */ -typedef PNG_CALLBACK(void, *png_progressive_row_ptr, (png_structp, png_bytep, - png_uint_32, int)); -#endif - -#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ - defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) -typedef PNG_CALLBACK(void, *png_user_transform_ptr, (png_structp, png_row_infop, - png_bytep)); -#endif - -#ifdef PNG_USER_CHUNKS_SUPPORTED -typedef PNG_CALLBACK(int, *png_user_chunk_ptr, (png_structp, - png_unknown_chunkp)); -#endif -#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED -/* not used anywhere */ -/* typedef PNG_CALLBACK(void, *png_unknown_chunk_ptr, (png_structp)); */ -#endif - -#ifdef PNG_SETJMP_SUPPORTED -/* This must match the function definition in , and the application - * must include this before png.h to obtain the definition of jmp_buf. The - * function is required to be PNG_NORETURN, but this is not checked. If the - * function does return the application will crash via an abort() or similar - * system level call. - * - * If you get a warning here while building the library you may need to make - * changes to ensure that pnglibconf.h records the calling convention used by - * your compiler. This may be very difficult - try using a different compiler - * to build the library! - */ -PNG_FUNCTION(void, (PNGCAPI *png_longjmp_ptr), PNGARG((jmp_buf, int)), typedef); -#endif - -/* Transform masks for the high-level interface */ -#define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */ -#define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */ -#define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */ -#define PNG_TRANSFORM_PACKING 0x0004 /* read and write */ -#define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */ -#define PNG_TRANSFORM_EXPAND 0x0010 /* read only */ -#define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */ -#define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */ -#define PNG_TRANSFORM_BGR 0x0080 /* read and write */ -#define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */ -#define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */ -#define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */ -#define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* write only */ -/* Added to libpng-1.2.34 */ -#define PNG_TRANSFORM_STRIP_FILLER_BEFORE PNG_TRANSFORM_STRIP_FILLER -#define PNG_TRANSFORM_STRIP_FILLER_AFTER 0x1000 /* write only */ -/* Added to libpng-1.4.0 */ -#define PNG_TRANSFORM_GRAY_TO_RGB 0x2000 /* read only */ -/* Added to libpng-1.5.4 */ -#define PNG_TRANSFORM_EXPAND_16 0x4000 /* read only */ -#if INT_MAX >= 0x8000 /* else this might break */ -#define PNG_TRANSFORM_SCALE_16 0x8000 /* read only */ -#endif - -/* Flags for MNG supported features */ -#define PNG_FLAG_MNG_EMPTY_PLTE 0x01 -#define PNG_FLAG_MNG_FILTER_64 0x04 -#define PNG_ALL_MNG_FEATURES 0x05 - -/* NOTE: prior to 1.5 these functions had no 'API' style declaration, - * this allowed the zlib default functions to be used on Windows - * platforms. In 1.5 the zlib default malloc (which just calls malloc and - * ignores the first argument) should be completely compatible with the - * following. - */ -typedef PNG_CALLBACK(png_voidp, *png_malloc_ptr, (png_structp, - png_alloc_size_t)); -typedef PNG_CALLBACK(void, *png_free_ptr, (png_structp, png_voidp)); - -/* Section 4: exported functions - * Here are the function definitions most commonly used. This is not - * the place to find out how to use libpng. See libpng-manual.txt for the - * full explanation, see example.c for the summary. This just provides - * a simple one line description of the use of each function. - * - * The PNG_EXPORT() and PNG_EXPORTA() macros used below are defined in - * pngconf.h and in the *.dfn files in the scripts directory. - * - * PNG_EXPORT(ordinal, type, name, (args)); - * - * ordinal: ordinal that is used while building - * *.def files. The ordinal value is only - * relevant when preprocessing png.h with - * the *.dfn files for building symbol table - * entries, and are removed by pngconf.h. - * type: return type of the function - * name: function name - * args: function arguments, with types - * - * When we wish to append attributes to a function prototype we use - * the PNG_EXPORTA() macro instead. - * - * PNG_EXPORTA(ordinal, type, name, (args), attributes); - * - * ordinal, type, name, and args: same as in PNG_EXPORT(). - * attributes: function attributes - */ - -/* Returns the version number of the library */ -PNG_EXPORT(1, png_uint_32, png_access_version_number, (void)); - -/* Tell lib we have already handled the first magic bytes. - * Handling more than 8 bytes from the beginning of the file is an error. - */ -PNG_EXPORT(2, void, png_set_sig_bytes, (png_structrp png_ptr, int num_bytes)); - -/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a - * PNG file. Returns zero if the supplied bytes match the 8-byte PNG - * signature, and non-zero otherwise. Having num_to_check == 0 or - * start > 7 will always fail (ie return non-zero). - */ -PNG_EXPORT(3, int, png_sig_cmp, (png_const_bytep sig, size_t start, - size_t num_to_check)); - -/* Simple signature checking function. This is the same as calling - * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n). - */ -#define png_check_sig(sig, n) !png_sig_cmp((sig), 0, (n)) - -/* Allocate and initialize png_ptr struct for reading, and any other memory. */ -PNG_EXPORTA(4, png_structp, png_create_read_struct, - (png_const_charp user_png_ver, png_voidp error_ptr, - png_error_ptr error_fn, png_error_ptr warn_fn), - PNG_ALLOCATED); - -/* Allocate and initialize png_ptr struct for writing, and any other memory */ -PNG_EXPORTA(5, png_structp, png_create_write_struct, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn), - PNG_ALLOCATED); - -PNG_EXPORT(6, size_t, png_get_compression_buffer_size, - (png_const_structrp png_ptr)); - -PNG_EXPORT(7, void, png_set_compression_buffer_size, (png_structrp png_ptr, - size_t size)); - -/* Moved from pngconf.h in 1.4.0 and modified to ensure setjmp/longjmp - * match up. - */ -#ifdef PNG_SETJMP_SUPPORTED -/* This function returns the jmp_buf built in to *png_ptr. It must be - * supplied with an appropriate 'longjmp' function to use on that jmp_buf - * unless the default error function is overridden in which case NULL is - * acceptable. The size of the jmp_buf is checked against the actual size - * allocated by the library - the call will return NULL on a mismatch - * indicating an ABI mismatch. - */ -PNG_EXPORT(8, jmp_buf*, png_set_longjmp_fn, (png_structrp png_ptr, - png_longjmp_ptr longjmp_fn, size_t jmp_buf_size)); -# define png_jmpbuf(png_ptr) \ - (*png_set_longjmp_fn((png_ptr), longjmp, (sizeof (jmp_buf)))) -#else -# define png_jmpbuf(png_ptr) \ - (LIBPNG_WAS_COMPILED_WITH__PNG_NO_SETJMP) -#endif -/* This function should be used by libpng applications in place of - * longjmp(png_ptr->jmpbuf, val). If longjmp_fn() has been set, it - * will use it; otherwise it will call PNG_ABORT(). This function was - * added in libpng-1.5.0. - */ -PNG_EXPORTA(9, void, png_longjmp, (png_const_structrp png_ptr, int val), - PNG_NORETURN); - -#ifdef PNG_READ_SUPPORTED -/* Reset the compression stream */ -PNG_EXPORTA(10, int, png_reset_zstream, (png_structrp png_ptr), PNG_DEPRECATED); -#endif - -/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */ -#ifdef PNG_USER_MEM_SUPPORTED -PNG_EXPORTA(11, png_structp, png_create_read_struct_2, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn, - png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn), - PNG_ALLOCATED); -PNG_EXPORTA(12, png_structp, png_create_write_struct_2, - (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, - png_error_ptr warn_fn, - png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn), - PNG_ALLOCATED); -#endif - -/* Write the PNG file signature. */ -PNG_EXPORT(13, void, png_write_sig, (png_structrp png_ptr)); - -/* Write a PNG chunk - size, type, (optional) data, CRC. */ -PNG_EXPORT(14, void, png_write_chunk, (png_structrp png_ptr, png_const_bytep - chunk_name, png_const_bytep data, size_t length)); - -/* Write the start of a PNG chunk - length and chunk name. */ -PNG_EXPORT(15, void, png_write_chunk_start, (png_structrp png_ptr, - png_const_bytep chunk_name, png_uint_32 length)); - -/* Write the data of a PNG chunk started with png_write_chunk_start(). */ -PNG_EXPORT(16, void, png_write_chunk_data, (png_structrp png_ptr, - png_const_bytep data, size_t length)); - -/* Finish a chunk started with png_write_chunk_start() (includes CRC). */ -PNG_EXPORT(17, void, png_write_chunk_end, (png_structrp png_ptr)); - -/* Allocate and initialize the info structure */ -PNG_EXPORTA(18, png_infop, png_create_info_struct, (png_const_structrp png_ptr), - PNG_ALLOCATED); - -/* DEPRECATED: this function allowed init structures to be created using the - * default allocation method (typically malloc). Use is deprecated in 1.6.0 and - * the API will be removed in the future. - */ -PNG_EXPORTA(19, void, png_info_init_3, (png_infopp info_ptr, - size_t png_info_struct_size), PNG_DEPRECATED); - -/* Writes all the PNG information before the image. */ -PNG_EXPORT(20, void, png_write_info_before_PLTE, - (png_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(21, void, png_write_info, - (png_structrp png_ptr, png_const_inforp info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the information before the actual image data. */ -PNG_EXPORT(22, void, png_read_info, - (png_structrp png_ptr, png_inforp info_ptr)); -#endif - -#ifdef PNG_TIME_RFC1123_SUPPORTED - /* Convert to a US string format: there is no localization support in this - * routine. The original implementation used a 29 character buffer in - * png_struct, this will be removed in future versions. - */ -#if PNG_LIBPNG_VER < 10700 -/* To do: remove this from libpng17 (and from libpng17/png.c and pngstruct.h) */ -PNG_EXPORTA(23, png_const_charp, png_convert_to_rfc1123, (png_structrp png_ptr, - png_const_timep ptime),PNG_DEPRECATED); -#endif -PNG_EXPORT(241, int, png_convert_to_rfc1123_buffer, (char out[29], - png_const_timep ptime)); -#endif - -#ifdef PNG_CONVERT_tIME_SUPPORTED -/* Convert from a struct tm to png_time */ -PNG_EXPORT(24, void, png_convert_from_struct_tm, (png_timep ptime, - const struct tm * ttime)); - -/* Convert from time_t to png_time. Uses gmtime() */ -PNG_EXPORT(25, void, png_convert_from_time_t, (png_timep ptime, time_t ttime)); -#endif /* CONVERT_tIME */ - -#ifdef PNG_READ_EXPAND_SUPPORTED -/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */ -PNG_EXPORT(26, void, png_set_expand, (png_structrp png_ptr)); -PNG_EXPORT(27, void, png_set_expand_gray_1_2_4_to_8, (png_structrp png_ptr)); -PNG_EXPORT(28, void, png_set_palette_to_rgb, (png_structrp png_ptr)); -PNG_EXPORT(29, void, png_set_tRNS_to_alpha, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_EXPAND_16_SUPPORTED -/* Expand to 16-bit channels, forces conversion of palette to RGB and expansion - * of a tRNS chunk if present. - */ -PNG_EXPORT(221, void, png_set_expand_16, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED) -/* Use blue, green, red order for pixels. */ -PNG_EXPORT(30, void, png_set_bgr, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED -/* Expand the grayscale to 24-bit RGB if necessary. */ -PNG_EXPORT(31, void, png_set_gray_to_rgb, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED -/* Reduce RGB to grayscale. */ -#define PNG_ERROR_ACTION_NONE 1 -#define PNG_ERROR_ACTION_WARN 2 -#define PNG_ERROR_ACTION_ERROR 3 -#define PNG_RGB_TO_GRAY_DEFAULT (-1)/*for red/green coefficients*/ - -PNG_FP_EXPORT(32, void, png_set_rgb_to_gray, (png_structrp png_ptr, - int error_action, double red, double green)) -PNG_FIXED_EXPORT(33, void, png_set_rgb_to_gray_fixed, (png_structrp png_ptr, - int error_action, png_fixed_point red, png_fixed_point green)) - -PNG_EXPORT(34, png_byte, png_get_rgb_to_gray_status, (png_const_structrp - png_ptr)); -#endif - -#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED -PNG_EXPORT(35, void, png_build_grayscale_palette, (int bit_depth, - png_colorp palette)); -#endif - -#ifdef PNG_READ_ALPHA_MODE_SUPPORTED -/* How the alpha channel is interpreted - this affects how the color channels - * of a PNG file are returned to the calling application when an alpha channel, - * or a tRNS chunk in a palette file, is present. - * - * This has no effect on the way pixels are written into a PNG output - * datastream. The color samples in a PNG datastream are never premultiplied - * with the alpha samples. - * - * The default is to return data according to the PNG specification: the alpha - * channel is a linear measure of the contribution of the pixel to the - * corresponding composited pixel, and the color channels are unassociated - * (not premultiplied). The gamma encoded color channels must be scaled - * according to the contribution and to do this it is necessary to undo - * the encoding, scale the color values, perform the composition and re-encode - * the values. This is the 'PNG' mode. - * - * The alternative is to 'associate' the alpha with the color information by - * storing color channel values that have been scaled by the alpha. - * image. These are the 'STANDARD', 'ASSOCIATED' or 'PREMULTIPLIED' modes - * (the latter being the two common names for associated alpha color channels). - * - * For the 'OPTIMIZED' mode, a pixel is treated as opaque only if the alpha - * value is equal to the maximum value. - * - * The final choice is to gamma encode the alpha channel as well. This is - * broken because, in practice, no implementation that uses this choice - * correctly undoes the encoding before handling alpha composition. Use this - * choice only if other serious errors in the software or hardware you use - * mandate it; the typical serious error is for dark halos to appear around - * opaque areas of the composited PNG image because of arithmetic overflow. - * - * The API function png_set_alpha_mode specifies which of these choices to use - * with an enumerated 'mode' value and the gamma of the required output: - */ -#define PNG_ALPHA_PNG 0 /* according to the PNG standard */ -#define PNG_ALPHA_STANDARD 1 /* according to Porter/Duff */ -#define PNG_ALPHA_ASSOCIATED 1 /* as above; this is the normal practice */ -#define PNG_ALPHA_PREMULTIPLIED 1 /* as above */ -#define PNG_ALPHA_OPTIMIZED 2 /* 'PNG' for opaque pixels, else 'STANDARD' */ -#define PNG_ALPHA_BROKEN 3 /* the alpha channel is gamma encoded */ - -PNG_FP_EXPORT(227, void, png_set_alpha_mode, (png_structrp png_ptr, int mode, - double output_gamma)) -PNG_FIXED_EXPORT(228, void, png_set_alpha_mode_fixed, (png_structrp png_ptr, - int mode, png_fixed_point output_gamma)) -#endif - -#if defined(PNG_GAMMA_SUPPORTED) || defined(PNG_READ_ALPHA_MODE_SUPPORTED) -/* The output_gamma value is a screen gamma in libpng terminology: it expresses - * how to decode the output values, not how they are encoded. - */ -#define PNG_DEFAULT_sRGB -1 /* sRGB gamma and color space */ -#define PNG_GAMMA_MAC_18 -2 /* Old Mac '1.8' gamma and color space */ -#define PNG_GAMMA_sRGB 220000 /* Television standards--matches sRGB gamma */ -#define PNG_GAMMA_LINEAR PNG_FP_1 /* Linear */ -#endif - -/* The following are examples of calls to png_set_alpha_mode to achieve the - * required overall gamma correction and, where necessary, alpha - * premultiplication. - * - * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB); - * This is the default libpng handling of the alpha channel - it is not - * pre-multiplied into the color components. In addition the call states - * that the output is for a sRGB system and causes all PNG files without gAMA - * chunks to be assumed to be encoded using sRGB. - * - * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC); - * In this case the output is assumed to be something like an sRGB conformant - * display preceded by a power-law lookup table of power 1.45. This is how - * early Mac systems behaved. - * - * png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_GAMMA_LINEAR); - * This is the classic Jim Blinn approach and will work in academic - * environments where everything is done by the book. It has the shortcoming - * of assuming that input PNG data with no gamma information is linear - this - * is unlikely to be correct unless the PNG files where generated locally. - * Most of the time the output precision will be so low as to show - * significant banding in dark areas of the image. - * - * png_set_expand_16(pp); - * png_set_alpha_mode(pp, PNG_ALPHA_STANDARD, PNG_DEFAULT_sRGB); - * This is a somewhat more realistic Jim Blinn inspired approach. PNG files - * are assumed to have the sRGB encoding if not marked with a gamma value and - * the output is always 16 bits per component. This permits accurate scaling - * and processing of the data. If you know that your input PNG files were - * generated locally you might need to replace PNG_DEFAULT_sRGB with the - * correct value for your system. - * - * png_set_alpha_mode(pp, PNG_ALPHA_OPTIMIZED, PNG_DEFAULT_sRGB); - * If you just need to composite the PNG image onto an existing background - * and if you control the code that does this you can use the optimization - * setting. In this case you just copy completely opaque pixels to the - * output. For pixels that are not completely transparent (you just skip - * those) you do the composition math using png_composite or png_composite_16 - * below then encode the resultant 8-bit or 16-bit values to match the output - * encoding. - * - * Other cases - * If neither the PNG nor the standard linear encoding work for you because - * of the software or hardware you use then you have a big problem. The PNG - * case will probably result in halos around the image. The linear encoding - * will probably result in a washed out, too bright, image (it's actually too - * contrasty.) Try the ALPHA_OPTIMIZED mode above - this will probably - * substantially reduce the halos. Alternatively try: - * - * png_set_alpha_mode(pp, PNG_ALPHA_BROKEN, PNG_DEFAULT_sRGB); - * This option will also reduce the halos, but there will be slight dark - * halos round the opaque parts of the image where the background is light. - * In the OPTIMIZED mode the halos will be light halos where the background - * is dark. Take your pick - the halos are unavoidable unless you can get - * your hardware/software fixed! (The OPTIMIZED approach is slightly - * faster.) - * - * When the default gamma of PNG files doesn't match the output gamma. - * If you have PNG files with no gamma information png_set_alpha_mode allows - * you to provide a default gamma, but it also sets the output gamma to the - * matching value. If you know your PNG files have a gamma that doesn't - * match the output you can take advantage of the fact that - * png_set_alpha_mode always sets the output gamma but only sets the PNG - * default if it is not already set: - * - * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_DEFAULT_sRGB); - * png_set_alpha_mode(pp, PNG_ALPHA_PNG, PNG_GAMMA_MAC); - * The first call sets both the default and the output gamma values, the - * second call overrides the output gamma without changing the default. This - * is easier than achieving the same effect with png_set_gamma. You must use - * PNG_ALPHA_PNG for the first call - internal checking in png_set_alpha will - * fire if more than one call to png_set_alpha_mode and png_set_background is - * made in the same read operation, however multiple calls with PNG_ALPHA_PNG - * are ignored. - */ - -#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED -PNG_EXPORT(36, void, png_set_strip_alpha, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \ - defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) -PNG_EXPORT(37, void, png_set_swap_alpha, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \ - defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) -PNG_EXPORT(38, void, png_set_invert_alpha, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED) -/* Add a filler byte to 8-bit or 16-bit Gray or 24-bit or 48-bit RGB images. */ -PNG_EXPORT(39, void, png_set_filler, (png_structrp png_ptr, png_uint_32 filler, - int flags)); -/* The values of the PNG_FILLER_ defines should NOT be changed */ -# define PNG_FILLER_BEFORE 0 -# define PNG_FILLER_AFTER 1 -/* Add an alpha byte to 8-bit or 16-bit Gray or 24-bit or 48-bit RGB images. */ -PNG_EXPORT(40, void, png_set_add_alpha, (png_structrp png_ptr, - png_uint_32 filler, int flags)); -#endif /* READ_FILLER || WRITE_FILLER */ - -#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED) -/* Swap bytes in 16-bit depth files. */ -PNG_EXPORT(41, void, png_set_swap, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) -/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */ -PNG_EXPORT(42, void, png_set_packing, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_PACKSWAP_SUPPORTED) || \ - defined(PNG_WRITE_PACKSWAP_SUPPORTED) -/* Swap packing order of pixels in bytes. */ -PNG_EXPORT(43, void, png_set_packswap, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED) -/* Converts files to legal bit depths. */ -PNG_EXPORT(44, void, png_set_shift, (png_structrp png_ptr, png_const_color_8p - true_bits)); -#endif - -#if defined(PNG_READ_INTERLACING_SUPPORTED) || \ - defined(PNG_WRITE_INTERLACING_SUPPORTED) -/* Have the code handle the interlacing. Returns the number of passes. - * MUST be called before png_read_update_info or png_start_read_image, - * otherwise it will not have the desired effect. Note that it is still - * necessary to call png_read_row or png_read_rows png_get_image_height - * times for each pass. -*/ -PNG_EXPORT(45, int, png_set_interlace_handling, (png_structrp png_ptr)); -#endif - -#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED) -/* Invert monochrome files */ -PNG_EXPORT(46, void, png_set_invert_mono, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_BACKGROUND_SUPPORTED -/* Handle alpha and tRNS by replacing with a background color. Prior to - * libpng-1.5.4 this API must not be called before the PNG file header has been - * read. Doing so will result in unexpected behavior and possible warnings or - * errors if the PNG file contains a bKGD chunk. - */ -PNG_FP_EXPORT(47, void, png_set_background, (png_structrp png_ptr, - png_const_color_16p background_color, int background_gamma_code, - int need_expand, double background_gamma)) -PNG_FIXED_EXPORT(215, void, png_set_background_fixed, (png_structrp png_ptr, - png_const_color_16p background_color, int background_gamma_code, - int need_expand, png_fixed_point background_gamma)) -#endif -#ifdef PNG_READ_BACKGROUND_SUPPORTED -# define PNG_BACKGROUND_GAMMA_UNKNOWN 0 -# define PNG_BACKGROUND_GAMMA_SCREEN 1 -# define PNG_BACKGROUND_GAMMA_FILE 2 -# define PNG_BACKGROUND_GAMMA_UNIQUE 3 -#endif - -#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED -/* Scale a 16-bit depth file down to 8-bit, accurately. */ -PNG_EXPORT(229, void, png_set_scale_16, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED -#define PNG_READ_16_TO_8_SUPPORTED /* Name prior to 1.5.4 */ -/* Strip the second byte of information from a 16-bit depth file. */ -PNG_EXPORT(48, void, png_set_strip_16, (png_structrp png_ptr)); -#endif - -#ifdef PNG_READ_QUANTIZE_SUPPORTED -/* Turn on quantizing, and reduce the palette to the number of colors - * available. - */ -PNG_EXPORT(49, void, png_set_quantize, (png_structrp png_ptr, - png_colorp palette, int num_palette, int maximum_colors, - png_const_uint_16p histogram, int full_quantize)); -#endif - -#ifdef PNG_READ_GAMMA_SUPPORTED -/* The threshold on gamma processing is configurable but hard-wired into the - * library. The following is the floating point variant. - */ -#define PNG_GAMMA_THRESHOLD (PNG_GAMMA_THRESHOLD_FIXED*.00001) - -/* Handle gamma correction. Screen_gamma=(display_exponent). - * NOTE: this API simply sets the screen and file gamma values. It will - * therefore override the value for gamma in a PNG file if it is called after - * the file header has been read - use with care - call before reading the PNG - * file for best results! - * - * These routines accept the same gamma values as png_set_alpha_mode (described - * above). The PNG_GAMMA_ defines and PNG_DEFAULT_sRGB can be passed to either - * API (floating point or fixed.) Notice, however, that the 'file_gamma' value - * is the inverse of a 'screen gamma' value. - */ -PNG_FP_EXPORT(50, void, png_set_gamma, (png_structrp png_ptr, - double screen_gamma, double override_file_gamma)) -PNG_FIXED_EXPORT(208, void, png_set_gamma_fixed, (png_structrp png_ptr, - png_fixed_point screen_gamma, png_fixed_point override_file_gamma)) -#endif - -#ifdef PNG_WRITE_FLUSH_SUPPORTED -/* Set how many lines between output flushes - 0 for no flushing */ -PNG_EXPORT(51, void, png_set_flush, (png_structrp png_ptr, int nrows)); -/* Flush the current PNG output buffer */ -PNG_EXPORT(52, void, png_write_flush, (png_structrp png_ptr)); -#endif - -/* Optional update palette with requested transformations */ -PNG_EXPORT(53, void, png_start_read_image, (png_structrp png_ptr)); - -/* Optional call to update the users info structure */ -PNG_EXPORT(54, void, png_read_update_info, (png_structrp png_ptr, - png_inforp info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read one or more rows of image data. */ -PNG_EXPORT(55, void, png_read_rows, (png_structrp png_ptr, png_bytepp row, - png_bytepp display_row, png_uint_32 num_rows)); -#endif - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read a row of data. */ -PNG_EXPORT(56, void, png_read_row, (png_structrp png_ptr, png_bytep row, - png_bytep display_row)); -#endif - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the whole image into memory at once. */ -PNG_EXPORT(57, void, png_read_image, (png_structrp png_ptr, png_bytepp image)); -#endif - -/* Write a row of image data */ -PNG_EXPORT(58, void, png_write_row, (png_structrp png_ptr, - png_const_bytep row)); - -/* Write a few rows of image data: (*row) is not written; however, the type - * is declared as writeable to maintain compatibility with previous versions - * of libpng and to allow the 'display_row' array from read_rows to be passed - * unchanged to write_rows. - */ -PNG_EXPORT(59, void, png_write_rows, (png_structrp png_ptr, png_bytepp row, - png_uint_32 num_rows)); - -/* Write the image data */ -PNG_EXPORT(60, void, png_write_image, (png_structrp png_ptr, png_bytepp image)); - -/* Write the end of the PNG file. */ -PNG_EXPORT(61, void, png_write_end, (png_structrp png_ptr, - png_inforp info_ptr)); - -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -/* Read the end of the PNG file. */ -PNG_EXPORT(62, void, png_read_end, (png_structrp png_ptr, png_inforp info_ptr)); -#endif - -/* Free any memory associated with the png_info_struct */ -PNG_EXPORT(63, void, png_destroy_info_struct, (png_const_structrp png_ptr, - png_infopp info_ptr_ptr)); - -/* Free any memory associated with the png_struct and the png_info_structs */ -PNG_EXPORT(64, void, png_destroy_read_struct, (png_structpp png_ptr_ptr, - png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr)); - -/* Free any memory associated with the png_struct and the png_info_structs */ -PNG_EXPORT(65, void, png_destroy_write_struct, (png_structpp png_ptr_ptr, - png_infopp info_ptr_ptr)); - -/* Set the libpng method of handling chunk CRC errors */ -PNG_EXPORT(66, void, png_set_crc_action, (png_structrp png_ptr, int crit_action, - int ancil_action)); - -/* Values for png_set_crc_action() say how to handle CRC errors in - * ancillary and critical chunks, and whether to use the data contained - * therein. Note that it is impossible to "discard" data in a critical - * chunk. For versions prior to 0.90, the action was always error/quit, - * whereas in version 0.90 and later, the action for CRC errors in ancillary - * chunks is warn/discard. These values should NOT be changed. - * - * value action:critical action:ancillary - */ -#define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */ -#define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */ -#define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */ -#define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */ -#define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */ -#define PNG_CRC_NO_CHANGE 5 /* use current value use current value */ - -#ifdef PNG_WRITE_SUPPORTED -/* These functions give the user control over the scan-line filtering in - * libpng and the compression methods used by zlib. These functions are - * mainly useful for testing, as the defaults should work with most users. - * Those users who are tight on memory or want faster performance at the - * expense of compression can modify them. See the compression library - * header file (zlib.h) for an explination of the compression functions. - */ - -/* Set the filtering method(s) used by libpng. Currently, the only valid - * value for "method" is 0. - */ -PNG_EXPORT(67, void, png_set_filter, (png_structrp png_ptr, int method, - int filters)); -#endif /* WRITE */ - -/* Flags for png_set_filter() to say which filters to use. The flags - * are chosen so that they don't conflict with real filter types - * below, in case they are supplied instead of the #defined constants. - * These values should NOT be changed. - */ -#define PNG_NO_FILTERS 0x00 -#define PNG_FILTER_NONE 0x08 -#define PNG_FILTER_SUB 0x10 -#define PNG_FILTER_UP 0x20 -#define PNG_FILTER_AVG 0x40 -#define PNG_FILTER_PAETH 0x80 -#define PNG_FAST_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP) -#define PNG_ALL_FILTERS (PNG_FAST_FILTERS | PNG_FILTER_AVG | PNG_FILTER_PAETH) - -/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now. - * These defines should NOT be changed. - */ -#define PNG_FILTER_VALUE_NONE 0 -#define PNG_FILTER_VALUE_SUB 1 -#define PNG_FILTER_VALUE_UP 2 -#define PNG_FILTER_VALUE_AVG 3 -#define PNG_FILTER_VALUE_PAETH 4 -#define PNG_FILTER_VALUE_LAST 5 - -#ifdef PNG_WRITE_SUPPORTED -#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* DEPRECATED */ -PNG_FP_EXPORT(68, void, png_set_filter_heuristics, (png_structrp png_ptr, - int heuristic_method, int num_weights, png_const_doublep filter_weights, - png_const_doublep filter_costs)) -PNG_FIXED_EXPORT(209, void, png_set_filter_heuristics_fixed, - (png_structrp png_ptr, int heuristic_method, int num_weights, - png_const_fixed_point_p filter_weights, - png_const_fixed_point_p filter_costs)) -#endif /* WRITE_WEIGHTED_FILTER */ - -/* The following are no longer used and will be removed from libpng-1.7: */ -#define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */ -#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */ -#define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */ -#define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */ - -/* Set the library compression level. Currently, valid values range from - * 0 - 9, corresponding directly to the zlib compression levels 0 - 9 - * (0 - no compression, 9 - "maximal" compression). Note that tests have - * shown that zlib compression levels 3-6 usually perform as well as level 9 - * for PNG images, and do considerably fewer caclulations. In the future, - * these values may not correspond directly to the zlib compression levels. - */ -#ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED -PNG_EXPORT(69, void, png_set_compression_level, (png_structrp png_ptr, - int level)); - -PNG_EXPORT(70, void, png_set_compression_mem_level, (png_structrp png_ptr, - int mem_level)); - -PNG_EXPORT(71, void, png_set_compression_strategy, (png_structrp png_ptr, - int strategy)); - -/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a - * smaller value of window_bits if it can do so safely. - */ -PNG_EXPORT(72, void, png_set_compression_window_bits, (png_structrp png_ptr, - int window_bits)); - -PNG_EXPORT(73, void, png_set_compression_method, (png_structrp png_ptr, - int method)); -#endif /* WRITE_CUSTOMIZE_COMPRESSION */ - -#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED -/* Also set zlib parameters for compressing non-IDAT chunks */ -PNG_EXPORT(222, void, png_set_text_compression_level, (png_structrp png_ptr, - int level)); - -PNG_EXPORT(223, void, png_set_text_compression_mem_level, (png_structrp png_ptr, - int mem_level)); - -PNG_EXPORT(224, void, png_set_text_compression_strategy, (png_structrp png_ptr, - int strategy)); - -/* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a - * smaller value of window_bits if it can do so safely. - */ -PNG_EXPORT(225, void, png_set_text_compression_window_bits, - (png_structrp png_ptr, int window_bits)); - -PNG_EXPORT(226, void, png_set_text_compression_method, (png_structrp png_ptr, - int method)); -#endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */ -#endif /* WRITE */ - -/* These next functions are called for input/output, memory, and error - * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c, - * and call standard C I/O routines such as fread(), fwrite(), and - * fprintf(). These functions can be made to use other I/O routines - * at run time for those applications that need to handle I/O in a - * different manner by calling png_set_???_fn(). See libpng-manual.txt for - * more information. - */ - -#ifdef PNG_STDIO_SUPPORTED -/* Initialize the input/output for the PNG file to the default functions. */ -PNG_EXPORT(74, void, png_init_io, (png_structrp png_ptr, png_FILE_p fp)); -#endif - -/* Replace the (error and abort), and warning functions with user - * supplied functions. If no messages are to be printed you must still - * write and use replacement functions. The replacement error_fn should - * still do a longjmp to the last setjmp location if you are using this - * method of error handling. If error_fn or warning_fn is NULL, the - * default function will be used. - */ - -PNG_EXPORT(75, void, png_set_error_fn, (png_structrp png_ptr, - png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn)); - -/* Return the user pointer associated with the error functions */ -PNG_EXPORT(76, png_voidp, png_get_error_ptr, (png_const_structrp png_ptr)); - -/* Replace the default data output functions with a user supplied one(s). - * If buffered output is not used, then output_flush_fn can be set to NULL. - * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time - * output_flush_fn will be ignored (and thus can be NULL). - * It is probably a mistake to use NULL for output_flush_fn if - * write_data_fn is not also NULL unless you have built libpng with - * PNG_WRITE_FLUSH_SUPPORTED undefined, because in this case libpng's - * default flush function, which uses the standard *FILE structure, will - * be used. - */ -PNG_EXPORT(77, void, png_set_write_fn, (png_structrp png_ptr, png_voidp io_ptr, - png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)); - -/* Replace the default data input function with a user supplied one. */ -PNG_EXPORT(78, void, png_set_read_fn, (png_structrp png_ptr, png_voidp io_ptr, - png_rw_ptr read_data_fn)); - -/* Return the user pointer associated with the I/O functions */ -PNG_EXPORT(79, png_voidp, png_get_io_ptr, (png_const_structrp png_ptr)); - -PNG_EXPORT(80, void, png_set_read_status_fn, (png_structrp png_ptr, - png_read_status_ptr read_row_fn)); - -PNG_EXPORT(81, void, png_set_write_status_fn, (png_structrp png_ptr, - png_write_status_ptr write_row_fn)); - -#ifdef PNG_USER_MEM_SUPPORTED -/* Replace the default memory allocation functions with user supplied one(s). */ -PNG_EXPORT(82, void, png_set_mem_fn, (png_structrp png_ptr, png_voidp mem_ptr, - png_malloc_ptr malloc_fn, png_free_ptr free_fn)); -/* Return the user pointer associated with the memory functions */ -PNG_EXPORT(83, png_voidp, png_get_mem_ptr, (png_const_structrp png_ptr)); -#endif - -#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED -PNG_EXPORT(84, void, png_set_read_user_transform_fn, (png_structrp png_ptr, - png_user_transform_ptr read_user_transform_fn)); -#endif - -#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED -PNG_EXPORT(85, void, png_set_write_user_transform_fn, (png_structrp png_ptr, - png_user_transform_ptr write_user_transform_fn)); -#endif - -#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED -PNG_EXPORT(86, void, png_set_user_transform_info, (png_structrp png_ptr, - png_voidp user_transform_ptr, int user_transform_depth, - int user_transform_channels)); -/* Return the user pointer associated with the user transform functions */ -PNG_EXPORT(87, png_voidp, png_get_user_transform_ptr, - (png_const_structrp png_ptr)); -#endif - -#ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED -/* Return information about the row currently being processed. Note that these - * APIs do not fail but will return unexpected results if called outside a user - * transform callback. Also note that when transforming an interlaced image the - * row number is the row number within the sub-image of the interlace pass, so - * the value will increase to the height of the sub-image (not the full image) - * then reset to 0 for the next pass. - * - * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to - * find the output pixel (x,y) given an interlaced sub-image pixel - * (row,col,pass). (See below for these macros.) - */ -PNG_EXPORT(217, png_uint_32, png_get_current_row_number, (png_const_structrp)); -PNG_EXPORT(218, png_byte, png_get_current_pass_number, (png_const_structrp)); -#endif - -#ifdef PNG_READ_USER_CHUNKS_SUPPORTED -/* This callback is called only for *unknown* chunks. If - * PNG_HANDLE_AS_UNKNOWN_SUPPORTED is set then it is possible to set known - * chunks to be treated as unknown, however in this case the callback must do - * any processing required by the chunk (e.g. by calling the appropriate - * png_set_ APIs.) - * - * There is no write support - on write, by default, all the chunks in the - * 'unknown' list are written in the specified position. - * - * The integer return from the callback function is interpreted thus: - * - * negative: An error occurred; png_chunk_error will be called. - * zero: The chunk was not handled, the chunk will be saved. A critical - * chunk will cause an error at this point unless it is to be saved. - * positive: The chunk was handled, libpng will ignore/discard it. - * - * See "INTERACTION WITH USER CHUNK CALLBACKS" below for important notes about - * how this behavior will change in libpng 1.7 - */ -PNG_EXPORT(88, void, png_set_read_user_chunk_fn, (png_structrp png_ptr, - png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn)); -#endif - -#ifdef PNG_USER_CHUNKS_SUPPORTED -PNG_EXPORT(89, png_voidp, png_get_user_chunk_ptr, (png_const_structrp png_ptr)); -#endif - -#ifdef PNG_PROGRESSIVE_READ_SUPPORTED -/* Sets the function callbacks for the push reader, and a pointer to a - * user-defined structure available to the callback functions. - */ -PNG_EXPORT(90, void, png_set_progressive_read_fn, (png_structrp png_ptr, - png_voidp progressive_ptr, png_progressive_info_ptr info_fn, - png_progressive_row_ptr row_fn, png_progressive_end_ptr end_fn)); - -/* Returns the user pointer associated with the push read functions */ -PNG_EXPORT(91, png_voidp, png_get_progressive_ptr, - (png_const_structrp png_ptr)); - -/* Function to be called when data becomes available */ -PNG_EXPORT(92, void, png_process_data, (png_structrp png_ptr, - png_inforp info_ptr, png_bytep buffer, size_t buffer_size)); - -/* A function which may be called *only* within png_process_data to stop the - * processing of any more data. The function returns the number of bytes - * remaining, excluding any that libpng has cached internally. A subsequent - * call to png_process_data must supply these bytes again. If the argument - * 'save' is set to true the routine will first save all the pending data and - * will always return 0. - */ -PNG_EXPORT(219, size_t, png_process_data_pause, (png_structrp, int save)); - -/* A function which may be called *only* outside (after) a call to - * png_process_data. It returns the number of bytes of data to skip in the - * input. Normally it will return 0, but if it returns a non-zero value the - * application must skip than number of bytes of input data and pass the - * following data to the next call to png_process_data. - */ -PNG_EXPORT(220, png_uint_32, png_process_data_skip, (png_structrp)); - -/* Function that combines rows. 'new_row' is a flag that should come from - * the callback and be non-NULL if anything needs to be done; the library - * stores its own version of the new data internally and ignores the passed - * in value. - */ -PNG_EXPORT(93, void, png_progressive_combine_row, (png_const_structrp png_ptr, - png_bytep old_row, png_const_bytep new_row)); -#endif /* PROGRESSIVE_READ */ - -PNG_EXPORTA(94, png_voidp, png_malloc, (png_const_structrp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED); -/* Added at libpng version 1.4.0 */ -PNG_EXPORTA(95, png_voidp, png_calloc, (png_const_structrp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED); - -/* Added at libpng version 1.2.4 */ -PNG_EXPORTA(96, png_voidp, png_malloc_warn, (png_const_structrp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED); - -/* Frees a pointer allocated by png_malloc() */ -PNG_EXPORT(97, void, png_free, (png_const_structrp png_ptr, png_voidp ptr)); - -/* Free data that was allocated internally */ -PNG_EXPORT(98, void, png_free_data, (png_const_structrp png_ptr, - png_inforp info_ptr, png_uint_32 free_me, int num)); - -/* Reassign responsibility for freeing existing data, whether allocated - * by libpng or by the application; this works on the png_info structure passed - * in, it does not change the state for other png_info structures. - * - * It is unlikely that this function works correctly as of 1.6.0 and using it - * may result either in memory leaks or double free of allocated data. - */ -PNG_EXPORT(99, void, png_data_freer, (png_const_structrp png_ptr, - png_inforp info_ptr, int freer, png_uint_32 mask)); - -/* Assignments for png_data_freer */ -#define PNG_DESTROY_WILL_FREE_DATA 1 -#define PNG_SET_WILL_FREE_DATA 1 -#define PNG_USER_WILL_FREE_DATA 2 -/* Flags for png_ptr->free_me and info_ptr->free_me */ -#define PNG_FREE_HIST 0x0008U -#define PNG_FREE_ICCP 0x0010U -#define PNG_FREE_SPLT 0x0020U -#define PNG_FREE_ROWS 0x0040U -#define PNG_FREE_PCAL 0x0080U -#define PNG_FREE_SCAL 0x0100U -#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED -# define PNG_FREE_UNKN 0x0200U -#endif -/* PNG_FREE_LIST 0x0400U removed in 1.6.0 because it is ignored */ -#define PNG_FREE_PLTE 0x1000U -#define PNG_FREE_TRNS 0x2000U -#define PNG_FREE_TEXT 0x4000U -#define PNG_FREE_EXIF 0x8000U /* Added at libpng-1.6.31 */ -#define PNG_FREE_ALL 0xffffU -#define PNG_FREE_MUL 0x4220U /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */ - -#ifdef PNG_USER_MEM_SUPPORTED -PNG_EXPORTA(100, png_voidp, png_malloc_default, (png_const_structrp png_ptr, - png_alloc_size_t size), PNG_ALLOCATED PNG_DEPRECATED); -PNG_EXPORTA(101, void, png_free_default, (png_const_structrp png_ptr, - png_voidp ptr), PNG_DEPRECATED); -#endif - -#ifdef PNG_ERROR_TEXT_SUPPORTED -/* Fatal error in PNG image of libpng - can't continue */ -PNG_EXPORTA(102, void, png_error, (png_const_structrp png_ptr, - png_const_charp error_message), PNG_NORETURN); - -/* The same, but the chunk name is prepended to the error string. */ -PNG_EXPORTA(103, void, png_chunk_error, (png_const_structrp png_ptr, - png_const_charp error_message), PNG_NORETURN); - -#else -/* Fatal error in PNG image of libpng - can't continue */ -PNG_EXPORTA(104, void, png_err, (png_const_structrp png_ptr), PNG_NORETURN); -# define png_error(s1,s2) png_err(s1) -# define png_chunk_error(s1,s2) png_err(s1) -#endif - -#ifdef PNG_WARNINGS_SUPPORTED -/* Non-fatal error in libpng. Can continue, but may have a problem. */ -PNG_EXPORT(105, void, png_warning, (png_const_structrp png_ptr, - png_const_charp warning_message)); - -/* Non-fatal error in libpng, chunk name is prepended to message. */ -PNG_EXPORT(106, void, png_chunk_warning, (png_const_structrp png_ptr, - png_const_charp warning_message)); -#else -# define png_warning(s1,s2) ((void)(s1)) -# define png_chunk_warning(s1,s2) ((void)(s1)) -#endif - -#ifdef PNG_BENIGN_ERRORS_SUPPORTED -/* Benign error in libpng. Can continue, but may have a problem. - * User can choose whether to handle as a fatal error or as a warning. */ -PNG_EXPORT(107, void, png_benign_error, (png_const_structrp png_ptr, - png_const_charp warning_message)); - -#ifdef PNG_READ_SUPPORTED -/* Same, chunk name is prepended to message (only during read) */ -PNG_EXPORT(108, void, png_chunk_benign_error, (png_const_structrp png_ptr, - png_const_charp warning_message)); -#endif - -PNG_EXPORT(109, void, png_set_benign_errors, - (png_structrp png_ptr, int allowed)); -#else -# ifdef PNG_ALLOW_BENIGN_ERRORS -# define png_benign_error png_warning -# define png_chunk_benign_error png_chunk_warning -# else -# define png_benign_error png_error -# define png_chunk_benign_error png_chunk_error -# endif -#endif - -/* The png_set_ functions are for storing values in the png_info_struct. - * Similarly, the png_get_ calls are used to read values from the - * png_info_struct, either storing the parameters in the passed variables, or - * setting pointers into the png_info_struct where the data is stored. The - * png_get_ functions return a non-zero value if the data was available - * in info_ptr, or return zero and do not change any of the parameters if the - * data was not available. - * - * These functions should be used instead of directly accessing png_info - * to avoid problems with future changes in the size and internal layout of - * png_info_struct. - */ -/* Returns "flag" if chunk data is valid in info_ptr. */ -PNG_EXPORT(110, png_uint_32, png_get_valid, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_uint_32 flag)); - -/* Returns number of bytes needed to hold a transformed row. */ -PNG_EXPORT(111, size_t, png_get_rowbytes, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -#ifdef PNG_INFO_IMAGE_SUPPORTED -/* Returns row_pointers, which is an array of pointers to scanlines that was - * returned from png_read_png(). - */ -PNG_EXPORT(112, png_bytepp, png_get_rows, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Set row_pointers, which is an array of pointers to scanlines for use - * by png_write_png(). - */ -PNG_EXPORT(113, void, png_set_rows, (png_const_structrp png_ptr, - png_inforp info_ptr, png_bytepp row_pointers)); -#endif - -/* Returns number of color channels in image. */ -PNG_EXPORT(114, png_byte, png_get_channels, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -#ifdef PNG_EASY_ACCESS_SUPPORTED -/* Returns image width in pixels. */ -PNG_EXPORT(115, png_uint_32, png_get_image_width, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image height in pixels. */ -PNG_EXPORT(116, png_uint_32, png_get_image_height, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image bit_depth. */ -PNG_EXPORT(117, png_byte, png_get_bit_depth, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image color_type. */ -PNG_EXPORT(118, png_byte, png_get_color_type, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image filter_type. */ -PNG_EXPORT(119, png_byte, png_get_filter_type, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image interlace_type. */ -PNG_EXPORT(120, png_byte, png_get_interlace_type, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image compression_type. */ -PNG_EXPORT(121, png_byte, png_get_compression_type, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); - -/* Returns image resolution in pixels per meter, from pHYs chunk data. */ -PNG_EXPORT(122, png_uint_32, png_get_pixels_per_meter, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(123, png_uint_32, png_get_x_pixels_per_meter, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(124, png_uint_32, png_get_y_pixels_per_meter, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); - -/* Returns pixel aspect ratio, computed from pHYs chunk data. */ -PNG_FP_EXPORT(125, float, png_get_pixel_aspect_ratio, - (png_const_structrp png_ptr, png_const_inforp info_ptr)) -PNG_FIXED_EXPORT(210, png_fixed_point, png_get_pixel_aspect_ratio_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr)) - -/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */ -PNG_EXPORT(126, png_int_32, png_get_x_offset_pixels, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(127, png_int_32, png_get_y_offset_pixels, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(128, png_int_32, png_get_x_offset_microns, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); -PNG_EXPORT(129, png_int_32, png_get_y_offset_microns, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); - -#endif /* EASY_ACCESS */ - -#ifdef PNG_READ_SUPPORTED -/* Returns pointer to signature string read from PNG header */ -PNG_EXPORT(130, png_const_bytep, png_get_signature, (png_const_structrp png_ptr, - png_const_inforp info_ptr)); -#endif - -#ifdef PNG_bKGD_SUPPORTED -PNG_EXPORT(131, png_uint_32, png_get_bKGD, (png_const_structrp png_ptr, - png_inforp info_ptr, png_color_16p *background)); -#endif - -#ifdef PNG_bKGD_SUPPORTED -PNG_EXPORT(132, void, png_set_bKGD, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_color_16p background)); -#endif - -#ifdef PNG_cHRM_SUPPORTED -PNG_FP_EXPORT(133, png_uint_32, png_get_cHRM, (png_const_structrp png_ptr, - png_const_inforp info_ptr, double *white_x, double *white_y, double *red_x, - double *red_y, double *green_x, double *green_y, double *blue_x, - double *blue_y)) -PNG_FP_EXPORT(230, png_uint_32, png_get_cHRM_XYZ, (png_const_structrp png_ptr, - png_const_inforp info_ptr, double *red_X, double *red_Y, double *red_Z, - double *green_X, double *green_Y, double *green_Z, double *blue_X, - double *blue_Y, double *blue_Z)) -PNG_FIXED_EXPORT(134, png_uint_32, png_get_cHRM_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr, - png_fixed_point *int_white_x, png_fixed_point *int_white_y, - png_fixed_point *int_red_x, png_fixed_point *int_red_y, - png_fixed_point *int_green_x, png_fixed_point *int_green_y, - png_fixed_point *int_blue_x, png_fixed_point *int_blue_y)) -PNG_FIXED_EXPORT(231, png_uint_32, png_get_cHRM_XYZ_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr, - png_fixed_point *int_red_X, png_fixed_point *int_red_Y, - png_fixed_point *int_red_Z, png_fixed_point *int_green_X, - png_fixed_point *int_green_Y, png_fixed_point *int_green_Z, - png_fixed_point *int_blue_X, png_fixed_point *int_blue_Y, - png_fixed_point *int_blue_Z)) -#endif - -#ifdef PNG_cHRM_SUPPORTED -PNG_FP_EXPORT(135, void, png_set_cHRM, (png_const_structrp png_ptr, - png_inforp info_ptr, - double white_x, double white_y, double red_x, double red_y, double green_x, - double green_y, double blue_x, double blue_y)) -PNG_FP_EXPORT(232, void, png_set_cHRM_XYZ, (png_const_structrp png_ptr, - png_inforp info_ptr, double red_X, double red_Y, double red_Z, - double green_X, double green_Y, double green_Z, double blue_X, - double blue_Y, double blue_Z)) -PNG_FIXED_EXPORT(136, void, png_set_cHRM_fixed, (png_const_structrp png_ptr, - png_inforp info_ptr, png_fixed_point int_white_x, - png_fixed_point int_white_y, png_fixed_point int_red_x, - png_fixed_point int_red_y, png_fixed_point int_green_x, - png_fixed_point int_green_y, png_fixed_point int_blue_x, - png_fixed_point int_blue_y)) -PNG_FIXED_EXPORT(233, void, png_set_cHRM_XYZ_fixed, (png_const_structrp png_ptr, - png_inforp info_ptr, png_fixed_point int_red_X, png_fixed_point int_red_Y, - png_fixed_point int_red_Z, png_fixed_point int_green_X, - png_fixed_point int_green_Y, png_fixed_point int_green_Z, - png_fixed_point int_blue_X, png_fixed_point int_blue_Y, - png_fixed_point int_blue_Z)) -#endif - -#ifdef PNG_eXIf_SUPPORTED -PNG_EXPORT(246, png_uint_32, png_get_eXIf, (png_const_structrp png_ptr, - png_inforp info_ptr, png_bytep *exif)); -PNG_EXPORT(247, void, png_set_eXIf, (png_const_structrp png_ptr, - png_inforp info_ptr, png_bytep exif)); - -PNG_EXPORT(248, png_uint_32, png_get_eXIf_1, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_uint_32 *num_exif, png_bytep *exif)); -PNG_EXPORT(249, void, png_set_eXIf_1, (png_const_structrp png_ptr, - png_inforp info_ptr, png_uint_32 num_exif, png_bytep exif)); -#endif - -#ifdef PNG_gAMA_SUPPORTED -PNG_FP_EXPORT(137, png_uint_32, png_get_gAMA, (png_const_structrp png_ptr, - png_const_inforp info_ptr, double *file_gamma)) -PNG_FIXED_EXPORT(138, png_uint_32, png_get_gAMA_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr, - png_fixed_point *int_file_gamma)) -#endif - -#ifdef PNG_gAMA_SUPPORTED -PNG_FP_EXPORT(139, void, png_set_gAMA, (png_const_structrp png_ptr, - png_inforp info_ptr, double file_gamma)) -PNG_FIXED_EXPORT(140, void, png_set_gAMA_fixed, (png_const_structrp png_ptr, - png_inforp info_ptr, png_fixed_point int_file_gamma)) -#endif - -#ifdef PNG_hIST_SUPPORTED -PNG_EXPORT(141, png_uint_32, png_get_hIST, (png_const_structrp png_ptr, - png_inforp info_ptr, png_uint_16p *hist)); -PNG_EXPORT(142, void, png_set_hIST, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_uint_16p hist)); -#endif - -PNG_EXPORT(143, png_uint_32, png_get_IHDR, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_uint_32 *width, png_uint_32 *height, - int *bit_depth, int *color_type, int *interlace_method, - int *compression_method, int *filter_method)); - -PNG_EXPORT(144, void, png_set_IHDR, (png_const_structrp png_ptr, - png_inforp info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, - int color_type, int interlace_method, int compression_method, - int filter_method)); - -#ifdef PNG_oFFs_SUPPORTED -PNG_EXPORT(145, png_uint_32, png_get_oFFs, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_int_32 *offset_x, png_int_32 *offset_y, - int *unit_type)); -#endif - -#ifdef PNG_oFFs_SUPPORTED -PNG_EXPORT(146, void, png_set_oFFs, (png_const_structrp png_ptr, - png_inforp info_ptr, png_int_32 offset_x, png_int_32 offset_y, - int unit_type)); -#endif - -#ifdef PNG_pCAL_SUPPORTED -PNG_EXPORT(147, png_uint_32, png_get_pCAL, (png_const_structrp png_ptr, - png_inforp info_ptr, png_charp *purpose, png_int_32 *X0, - png_int_32 *X1, int *type, int *nparams, png_charp *units, - png_charpp *params)); -#endif - -#ifdef PNG_pCAL_SUPPORTED -PNG_EXPORT(148, void, png_set_pCAL, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_charp purpose, png_int_32 X0, png_int_32 X1, - int type, int nparams, png_const_charp units, png_charpp params)); -#endif - -#ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(149, png_uint_32, png_get_pHYs, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, - int *unit_type)); -#endif - -#ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(150, void, png_set_pHYs, (png_const_structrp png_ptr, - png_inforp info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type)); -#endif - -PNG_EXPORT(151, png_uint_32, png_get_PLTE, (png_const_structrp png_ptr, - png_inforp info_ptr, png_colorp *palette, int *num_palette)); - -PNG_EXPORT(152, void, png_set_PLTE, (png_structrp png_ptr, - png_inforp info_ptr, png_const_colorp palette, int num_palette)); - -#ifdef PNG_sBIT_SUPPORTED -PNG_EXPORT(153, png_uint_32, png_get_sBIT, (png_const_structrp png_ptr, - png_inforp info_ptr, png_color_8p *sig_bit)); -#endif - -#ifdef PNG_sBIT_SUPPORTED -PNG_EXPORT(154, void, png_set_sBIT, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_color_8p sig_bit)); -#endif - -#ifdef PNG_sRGB_SUPPORTED -PNG_EXPORT(155, png_uint_32, png_get_sRGB, (png_const_structrp png_ptr, - png_const_inforp info_ptr, int *file_srgb_intent)); -#endif - -#ifdef PNG_sRGB_SUPPORTED -PNG_EXPORT(156, void, png_set_sRGB, (png_const_structrp png_ptr, - png_inforp info_ptr, int srgb_intent)); -PNG_EXPORT(157, void, png_set_sRGB_gAMA_and_cHRM, (png_const_structrp png_ptr, - png_inforp info_ptr, int srgb_intent)); -#endif - -#ifdef PNG_iCCP_SUPPORTED -PNG_EXPORT(158, png_uint_32, png_get_iCCP, (png_const_structrp png_ptr, - png_inforp info_ptr, png_charpp name, int *compression_type, - png_bytepp profile, png_uint_32 *proflen)); -#endif - -#ifdef PNG_iCCP_SUPPORTED -PNG_EXPORT(159, void, png_set_iCCP, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_charp name, int compression_type, - png_const_bytep profile, png_uint_32 proflen)); -#endif - -#ifdef PNG_sPLT_SUPPORTED -PNG_EXPORT(160, int, png_get_sPLT, (png_const_structrp png_ptr, - png_inforp info_ptr, png_sPLT_tpp entries)); -#endif - -#ifdef PNG_sPLT_SUPPORTED -PNG_EXPORT(161, void, png_set_sPLT, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_sPLT_tp entries, int nentries)); -#endif - -#ifdef PNG_TEXT_SUPPORTED -/* png_get_text also returns the number of text chunks in *num_text */ -PNG_EXPORT(162, int, png_get_text, (png_const_structrp png_ptr, - png_inforp info_ptr, png_textp *text_ptr, int *num_text)); -#endif - -/* Note while png_set_text() will accept a structure whose text, - * language, and translated keywords are NULL pointers, the structure - * returned by png_get_text will always contain regular - * zero-terminated C strings. They might be empty strings but - * they will never be NULL pointers. - */ - -#ifdef PNG_TEXT_SUPPORTED -PNG_EXPORT(163, void, png_set_text, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_textp text_ptr, int num_text)); -#endif - -#ifdef PNG_tIME_SUPPORTED -PNG_EXPORT(164, png_uint_32, png_get_tIME, (png_const_structrp png_ptr, - png_inforp info_ptr, png_timep *mod_time)); -#endif - -#ifdef PNG_tIME_SUPPORTED -PNG_EXPORT(165, void, png_set_tIME, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_timep mod_time)); -#endif - -#ifdef PNG_tRNS_SUPPORTED -PNG_EXPORT(166, png_uint_32, png_get_tRNS, (png_const_structrp png_ptr, - png_inforp info_ptr, png_bytep *trans_alpha, int *num_trans, - png_color_16p *trans_color)); -#endif - -#ifdef PNG_tRNS_SUPPORTED -PNG_EXPORT(167, void, png_set_tRNS, (png_structrp png_ptr, - png_inforp info_ptr, png_const_bytep trans_alpha, int num_trans, - png_const_color_16p trans_color)); -#endif - -#ifdef PNG_sCAL_SUPPORTED -PNG_FP_EXPORT(168, png_uint_32, png_get_sCAL, (png_const_structrp png_ptr, - png_const_inforp info_ptr, int *unit, double *width, double *height)) -#if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || \ - defined(PNG_FLOATING_POINT_SUPPORTED) -/* NOTE: this API is currently implemented using floating point arithmetic, - * consequently it can only be used on systems with floating point support. - * In any case the range of values supported by png_fixed_point is small and it - * is highly recommended that png_get_sCAL_s be used instead. - */ -PNG_FIXED_EXPORT(214, png_uint_32, png_get_sCAL_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr, int *unit, - png_fixed_point *width, png_fixed_point *height)) -#endif -PNG_EXPORT(169, png_uint_32, png_get_sCAL_s, - (png_const_structrp png_ptr, png_const_inforp info_ptr, int *unit, - png_charpp swidth, png_charpp sheight)); - -PNG_FP_EXPORT(170, void, png_set_sCAL, (png_const_structrp png_ptr, - png_inforp info_ptr, int unit, double width, double height)) -PNG_FIXED_EXPORT(213, void, png_set_sCAL_fixed, (png_const_structrp png_ptr, - png_inforp info_ptr, int unit, png_fixed_point width, - png_fixed_point height)) -PNG_EXPORT(171, void, png_set_sCAL_s, (png_const_structrp png_ptr, - png_inforp info_ptr, int unit, - png_const_charp swidth, png_const_charp sheight)); -#endif /* sCAL */ - -#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED -/* Provide the default handling for all unknown chunks or, optionally, for - * specific unknown chunks. - * - * NOTE: prior to 1.6.0 the handling specified for particular chunks on read was - * ignored and the default was used, the per-chunk setting only had an effect on - * write. If you wish to have chunk-specific handling on read in code that must - * work on earlier versions you must use a user chunk callback to specify the - * desired handling (keep or discard.) - * - * The 'keep' parameter is a PNG_HANDLE_CHUNK_ value as listed below. The - * parameter is interpreted as follows: - * - * READ: - * PNG_HANDLE_CHUNK_AS_DEFAULT: - * Known chunks: do normal libpng processing, do not keep the chunk (but - * see the comments below about PNG_HANDLE_AS_UNKNOWN_SUPPORTED) - * Unknown chunks: for a specific chunk use the global default, when used - * as the default discard the chunk data. - * PNG_HANDLE_CHUNK_NEVER: - * Discard the chunk data. - * PNG_HANDLE_CHUNK_IF_SAFE: - * Keep the chunk data if the chunk is not critical else raise a chunk - * error. - * PNG_HANDLE_CHUNK_ALWAYS: - * Keep the chunk data. - * - * If the chunk data is saved it can be retrieved using png_get_unknown_chunks, - * below. Notice that specifying "AS_DEFAULT" as a global default is equivalent - * to specifying "NEVER", however when "AS_DEFAULT" is used for specific chunks - * it simply resets the behavior to the libpng default. - * - * INTERACTION WITH USER CHUNK CALLBACKS: - * The per-chunk handling is always used when there is a png_user_chunk_ptr - * callback and the callback returns 0; the chunk is then always stored *unless* - * it is critical and the per-chunk setting is other than ALWAYS. Notice that - * the global default is *not* used in this case. (In effect the per-chunk - * value is incremented to at least IF_SAFE.) - * - * IMPORTANT NOTE: this behavior will change in libpng 1.7 - the global and - * per-chunk defaults will be honored. If you want to preserve the current - * behavior when your callback returns 0 you must set PNG_HANDLE_CHUNK_IF_SAFE - * as the default - if you don't do this libpng 1.6 will issue a warning. - * - * If you want unhandled unknown chunks to be discarded in libpng 1.6 and - * earlier simply return '1' (handled). - * - * PNG_HANDLE_AS_UNKNOWN_SUPPORTED: - * If this is *not* set known chunks will always be handled by libpng and - * will never be stored in the unknown chunk list. Known chunks listed to - * png_set_keep_unknown_chunks will have no effect. If it is set then known - * chunks listed with a keep other than AS_DEFAULT will *never* be processed - * by libpng, in addition critical chunks must either be processed by the - * callback or saved. - * - * The IHDR and IEND chunks must not be listed. Because this turns off the - * default handling for chunks that would otherwise be recognized the - * behavior of libpng transformations may well become incorrect! - * - * WRITE: - * When writing chunks the options only apply to the chunks specified by - * png_set_unknown_chunks (below), libpng will *always* write known chunks - * required by png_set_ calls and will always write the core critical chunks - * (as required for PLTE). - * - * Each chunk in the png_set_unknown_chunks list is looked up in the - * png_set_keep_unknown_chunks list to find the keep setting, this is then - * interpreted as follows: - * - * PNG_HANDLE_CHUNK_AS_DEFAULT: - * Write safe-to-copy chunks and write other chunks if the global - * default is set to _ALWAYS, otherwise don't write this chunk. - * PNG_HANDLE_CHUNK_NEVER: - * Do not write the chunk. - * PNG_HANDLE_CHUNK_IF_SAFE: - * Write the chunk if it is safe-to-copy, otherwise do not write it. - * PNG_HANDLE_CHUNK_ALWAYS: - * Write the chunk. - * - * Note that the default behavior is effectively the opposite of the read case - - * in read unknown chunks are not stored by default, in write they are written - * by default. Also the behavior of PNG_HANDLE_CHUNK_IF_SAFE is very different - * - on write the safe-to-copy bit is checked, on read the critical bit is - * checked and on read if the chunk is critical an error will be raised. - * - * num_chunks: - * =========== - * If num_chunks is positive, then the "keep" parameter specifies the manner - * for handling only those chunks appearing in the chunk_list array, - * otherwise the chunk list array is ignored. - * - * If num_chunks is 0 the "keep" parameter specifies the default behavior for - * unknown chunks, as described above. - * - * If num_chunks is negative, then the "keep" parameter specifies the manner - * for handling all unknown chunks plus all chunks recognized by libpng - * except for the IHDR, PLTE, tRNS, IDAT, and IEND chunks (which continue to - * be processed by libpng. - */ -#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED -PNG_EXPORT(172, void, png_set_keep_unknown_chunks, (png_structrp png_ptr, - int keep, png_const_bytep chunk_list, int num_chunks)); -#endif /* HANDLE_AS_UNKNOWN */ - -/* The "keep" PNG_HANDLE_CHUNK_ parameter for the specified chunk is returned; - * the result is therefore true (non-zero) if special handling is required, - * false for the default handling. - */ -PNG_EXPORT(173, int, png_handle_as_unknown, (png_const_structrp png_ptr, - png_const_bytep chunk_name)); -#endif /* SET_UNKNOWN_CHUNKS */ - -#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED -PNG_EXPORT(174, void, png_set_unknown_chunks, (png_const_structrp png_ptr, - png_inforp info_ptr, png_const_unknown_chunkp unknowns, - int num_unknowns)); - /* NOTE: prior to 1.6.0 this routine set the 'location' field of the added - * unknowns to the location currently stored in the png_struct. This is - * invariably the wrong value on write. To fix this call the following API - * for each chunk in the list with the correct location. If you know your - * code won't be compiled on earlier versions you can rely on - * png_set_unknown_chunks(write-ptr, png_get_unknown_chunks(read-ptr)) doing - * the correct thing. - */ - -PNG_EXPORT(175, void, png_set_unknown_chunk_location, - (png_const_structrp png_ptr, png_inforp info_ptr, int chunk, int location)); - -PNG_EXPORT(176, int, png_get_unknown_chunks, (png_const_structrp png_ptr, - png_inforp info_ptr, png_unknown_chunkpp entries)); -#endif - -/* Png_free_data() will turn off the "valid" flag for anything it frees. - * If you need to turn it off for a chunk that your application has freed, - * you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); - */ -PNG_EXPORT(177, void, png_set_invalid, (png_const_structrp png_ptr, - png_inforp info_ptr, int mask)); - -#ifdef PNG_INFO_IMAGE_SUPPORTED -/* The "params" pointer is currently not used and is for future expansion. */ -#ifdef PNG_SEQUENTIAL_READ_SUPPORTED -PNG_EXPORT(178, void, png_read_png, (png_structrp png_ptr, png_inforp info_ptr, - int transforms, png_voidp params)); -#endif -#ifdef PNG_WRITE_SUPPORTED -PNG_EXPORT(179, void, png_write_png, (png_structrp png_ptr, png_inforp info_ptr, - int transforms, png_voidp params)); -#endif -#endif - -PNG_EXPORT(180, png_const_charp, png_get_copyright, - (png_const_structrp png_ptr)); -PNG_EXPORT(181, png_const_charp, png_get_header_ver, - (png_const_structrp png_ptr)); -PNG_EXPORT(182, png_const_charp, png_get_header_version, - (png_const_structrp png_ptr)); -PNG_EXPORT(183, png_const_charp, png_get_libpng_ver, - (png_const_structrp png_ptr)); - -#ifdef PNG_MNG_FEATURES_SUPPORTED -PNG_EXPORT(184, png_uint_32, png_permit_mng_features, (png_structrp png_ptr, - png_uint_32 mng_features_permitted)); -#endif - -/* For use in png_set_keep_unknown, added to version 1.2.6 */ -#define PNG_HANDLE_CHUNK_AS_DEFAULT 0 -#define PNG_HANDLE_CHUNK_NEVER 1 -#define PNG_HANDLE_CHUNK_IF_SAFE 2 -#define PNG_HANDLE_CHUNK_ALWAYS 3 -#define PNG_HANDLE_CHUNK_LAST 4 - -/* Strip the prepended error numbers ("#nnn ") from error and warning - * messages before passing them to the error or warning handler. - */ -#ifdef PNG_ERROR_NUMBERS_SUPPORTED -PNG_EXPORT(185, void, png_set_strip_error_numbers, (png_structrp png_ptr, - png_uint_32 strip_mode)); -#endif - -/* Added in libpng-1.2.6 */ -#ifdef PNG_SET_USER_LIMITS_SUPPORTED -PNG_EXPORT(186, void, png_set_user_limits, (png_structrp png_ptr, - png_uint_32 user_width_max, png_uint_32 user_height_max)); -PNG_EXPORT(187, png_uint_32, png_get_user_width_max, - (png_const_structrp png_ptr)); -PNG_EXPORT(188, png_uint_32, png_get_user_height_max, - (png_const_structrp png_ptr)); -/* Added in libpng-1.4.0 */ -PNG_EXPORT(189, void, png_set_chunk_cache_max, (png_structrp png_ptr, - png_uint_32 user_chunk_cache_max)); -PNG_EXPORT(190, png_uint_32, png_get_chunk_cache_max, - (png_const_structrp png_ptr)); -/* Added in libpng-1.4.1 */ -PNG_EXPORT(191, void, png_set_chunk_malloc_max, (png_structrp png_ptr, - png_alloc_size_t user_chunk_cache_max)); -PNG_EXPORT(192, png_alloc_size_t, png_get_chunk_malloc_max, - (png_const_structrp png_ptr)); -#endif - -#if defined(PNG_INCH_CONVERSIONS_SUPPORTED) -PNG_EXPORT(193, png_uint_32, png_get_pixels_per_inch, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); - -PNG_EXPORT(194, png_uint_32, png_get_x_pixels_per_inch, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); - -PNG_EXPORT(195, png_uint_32, png_get_y_pixels_per_inch, - (png_const_structrp png_ptr, png_const_inforp info_ptr)); - -PNG_FP_EXPORT(196, float, png_get_x_offset_inches, - (png_const_structrp png_ptr, png_const_inforp info_ptr)) -#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */ -PNG_FIXED_EXPORT(211, png_fixed_point, png_get_x_offset_inches_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr)) -#endif - -PNG_FP_EXPORT(197, float, png_get_y_offset_inches, (png_const_structrp png_ptr, - png_const_inforp info_ptr)) -#ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */ -PNG_FIXED_EXPORT(212, png_fixed_point, png_get_y_offset_inches_fixed, - (png_const_structrp png_ptr, png_const_inforp info_ptr)) -#endif - -# ifdef PNG_pHYs_SUPPORTED -PNG_EXPORT(198, png_uint_32, png_get_pHYs_dpi, (png_const_structrp png_ptr, - png_const_inforp info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, - int *unit_type)); -# endif /* pHYs */ -#endif /* INCH_CONVERSIONS */ - -/* Added in libpng-1.4.0 */ -#ifdef PNG_IO_STATE_SUPPORTED -PNG_EXPORT(199, png_uint_32, png_get_io_state, (png_const_structrp png_ptr)); - -/* Removed from libpng 1.6; use png_get_io_chunk_type. */ -PNG_REMOVED(200, png_const_bytep, png_get_io_chunk_name, (png_structrp png_ptr), - PNG_DEPRECATED) - -PNG_EXPORT(216, png_uint_32, png_get_io_chunk_type, - (png_const_structrp png_ptr)); - -/* The flags returned by png_get_io_state() are the following: */ -# define PNG_IO_NONE 0x0000 /* no I/O at this moment */ -# define PNG_IO_READING 0x0001 /* currently reading */ -# define PNG_IO_WRITING 0x0002 /* currently writing */ -# define PNG_IO_SIGNATURE 0x0010 /* currently at the file signature */ -# define PNG_IO_CHUNK_HDR 0x0020 /* currently at the chunk header */ -# define PNG_IO_CHUNK_DATA 0x0040 /* currently at the chunk data */ -# define PNG_IO_CHUNK_CRC 0x0080 /* currently at the chunk crc */ -# define PNG_IO_MASK_OP 0x000f /* current operation: reading/writing */ -# define PNG_IO_MASK_LOC 0x00f0 /* current location: sig/hdr/data/crc */ -#endif /* IO_STATE */ - -/* Interlace support. The following macros are always defined so that if - * libpng interlace handling is turned off the macros may be used to handle - * interlaced images within the application. - */ -#define PNG_INTERLACE_ADAM7_PASSES 7 - -/* Two macros to return the first row and first column of the original, - * full, image which appears in a given pass. 'pass' is in the range 0 - * to 6 and the result is in the range 0 to 7. - */ -#define PNG_PASS_START_ROW(pass) (((1&~(pass))<<(3-((pass)>>1)))&7) -#define PNG_PASS_START_COL(pass) (((1& (pass))<<(3-(((pass)+1)>>1)))&7) - -/* A macro to return the offset between pixels in the output row for a pair of - * pixels in the input - effectively the inverse of the 'COL_SHIFT' macro that - * follows. Note that ROW_OFFSET is the offset from one row to the next whereas - * COL_OFFSET is from one column to the next, within a row. - */ -#define PNG_PASS_ROW_OFFSET(pass) ((pass)>2?(8>>(((pass)-1)>>1)):8) -#define PNG_PASS_COL_OFFSET(pass) (1<<((7-(pass))>>1)) - -/* Two macros to help evaluate the number of rows or columns in each - * pass. This is expressed as a shift - effectively log2 of the number or - * rows or columns in each 8x8 tile of the original image. - */ -#define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3) -#define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3) - -/* Hence two macros to determine the number of rows or columns in a given - * pass of an image given its height or width. In fact these macros may - * return non-zero even though the sub-image is empty, because the other - * dimension may be empty for a small image. - */ -#define PNG_PASS_ROWS(height, pass) (((height)+(((1<>PNG_PASS_ROW_SHIFT(pass)) -#define PNG_PASS_COLS(width, pass) (((width)+(((1<>PNG_PASS_COL_SHIFT(pass)) - -/* For the reader row callbacks (both progressive and sequential) it is - * necessary to find the row in the output image given a row in an interlaced - * image, so two more macros: - */ -#define PNG_ROW_FROM_PASS_ROW(y_in, pass) \ - (((y_in)<>(((7-(off))-(pass))<<2)) & 0xF) | \ - ((0x01145AF0>>(((7-(off))-(pass))<<2)) & 0xF0)) - -#define PNG_ROW_IN_INTERLACE_PASS(y, pass) \ - ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1) -#define PNG_COL_IN_INTERLACE_PASS(x, pass) \ - ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1) - -#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED -/* With these routines we avoid an integer divide, which will be slower on - * most machines. However, it does take more operations than the corresponding - * divide method, so it may be slower on a few RISC systems. There are two - * shifts (by 8 or 16 bits) and an addition, versus a single integer divide. - * - * Note that the rounding factors are NOT supposed to be the same! 128 and - * 32768 are correct for the NODIV code; 127 and 32767 are correct for the - * standard method. - * - * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ] - */ - - /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */ - -# define png_composite(composite, fg, alpha, bg) \ - { \ - png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) \ - * (png_uint_16)(alpha) \ - + (png_uint_16)(bg)*(png_uint_16)(255 \ - - (png_uint_16)(alpha)) + 128); \ - (composite) = (png_byte)(((temp + (temp >> 8)) >> 8) & 0xff); \ - } - -# define png_composite_16(composite, fg, alpha, bg) \ - { \ - png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) \ - * (png_uint_32)(alpha) \ - + (png_uint_32)(bg)*(65535 \ - - (png_uint_32)(alpha)) + 32768); \ - (composite) = (png_uint_16)(0xffff & ((temp + (temp >> 16)) >> 16)); \ - } - -#else /* Standard method using integer division */ - -# define png_composite(composite, fg, alpha, bg) \ - (composite) = \ - (png_byte)(0xff & (((png_uint_16)(fg) * (png_uint_16)(alpha) + \ - (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \ - 127) / 255)) - -# define png_composite_16(composite, fg, alpha, bg) \ - (composite) = \ - (png_uint_16)(0xffff & (((png_uint_32)(fg) * (png_uint_32)(alpha) + \ - (png_uint_32)(bg)*(png_uint_32)(65535 - (png_uint_32)(alpha)) + \ - 32767) / 65535)) -#endif /* READ_COMPOSITE_NODIV */ - -#ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(201, png_uint_32, png_get_uint_32, (png_const_bytep buf)); -PNG_EXPORT(202, png_uint_16, png_get_uint_16, (png_const_bytep buf)); -PNG_EXPORT(203, png_int_32, png_get_int_32, (png_const_bytep buf)); -#endif - -PNG_EXPORT(204, png_uint_32, png_get_uint_31, (png_const_structrp png_ptr, - png_const_bytep buf)); -/* No png_get_int_16 -- may be added if there's a real need for it. */ - -/* Place a 32-bit number into a buffer in PNG byte order (big-endian). */ -#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(205, void, png_save_uint_32, (png_bytep buf, png_uint_32 i)); -#endif -#ifdef PNG_SAVE_INT_32_SUPPORTED -PNG_EXPORT(206, void, png_save_int_32, (png_bytep buf, png_int_32 i)); -#endif - -/* Place a 16-bit number into a buffer in PNG byte order. - * The parameter is declared unsigned int, not png_uint_16, - * just to avoid potential problems on pre-ANSI C compilers. - */ -#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED -PNG_EXPORT(207, void, png_save_uint_16, (png_bytep buf, unsigned int i)); -/* No png_save_int_16 -- may be added if there's a real need for it. */ -#endif - -#ifdef PNG_USE_READ_MACROS -/* Inline macros to do direct reads of bytes from the input buffer. - * The png_get_int_32() routine assumes we are using two's complement - * format for negative values, which is almost certainly true. - */ -# define PNG_get_uint_32(buf) \ - (((png_uint_32)(*(buf)) << 24) + \ - ((png_uint_32)(*((buf) + 1)) << 16) + \ - ((png_uint_32)(*((buf) + 2)) << 8) + \ - ((png_uint_32)(*((buf) + 3)))) - - /* From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the - * function) incorrectly returned a value of type png_uint_32. - */ -# define PNG_get_uint_16(buf) \ - ((png_uint_16) \ - (((unsigned int)(*(buf)) << 8) + \ - ((unsigned int)(*((buf) + 1))))) - -# define PNG_get_int_32(buf) \ - ((png_int_32)((*(buf) & 0x80) \ - ? -((png_int_32)(((png_get_uint_32(buf)^0xffffffffU)+1U)&0x7fffffffU)) \ - : (png_int_32)png_get_uint_32(buf))) - -/* If PNG_PREFIX is defined the same thing as below happens in pnglibconf.h, - * but defining a macro name prefixed with PNG_PREFIX. - */ -# ifndef PNG_PREFIX -# define png_get_uint_32(buf) PNG_get_uint_32(buf) -# define png_get_uint_16(buf) PNG_get_uint_16(buf) -# define png_get_int_32(buf) PNG_get_int_32(buf) -# endif -#else -# ifdef PNG_PREFIX - /* No macros; revert to the (redefined) function */ -# define PNG_get_uint_32 (png_get_uint_32) -# define PNG_get_uint_16 (png_get_uint_16) -# define PNG_get_int_32 (png_get_int_32) -# endif -#endif - -#ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED -PNG_EXPORT(242, void, png_set_check_for_invalid_index, - (png_structrp png_ptr, int allowed)); -# ifdef PNG_GET_PALETTE_MAX_SUPPORTED -PNG_EXPORT(243, int, png_get_palette_max, (png_const_structp png_ptr, - png_const_infop info_ptr)); -# endif -#endif /* CHECK_FOR_INVALID_INDEX */ - -/******************************************************************************* - * Section 5: SIMPLIFIED API - ******************************************************************************* - * - * Please read the documentation in libpng-manual.txt (TODO: write said - * documentation) if you don't understand what follows. - * - * The simplified API hides the details of both libpng and the PNG file format - * itself. It allows PNG files to be read into a very limited number of - * in-memory bitmap formats or to be written from the same formats. If these - * formats do not accommodate your needs then you can, and should, use the more - * sophisticated APIs above - these support a wide variety of in-memory formats - * and a wide variety of sophisticated transformations to those formats as well - * as a wide variety of APIs to manipulate ancillary information. - * - * To read a PNG file using the simplified API: - * - * 1) Declare a 'png_image' structure (see below) on the stack, set the - * version field to PNG_IMAGE_VERSION and the 'opaque' pointer to NULL - * (this is REQUIRED, your program may crash if you don't do it.) - * 2) Call the appropriate png_image_begin_read... function. - * 3) Set the png_image 'format' member to the required sample format. - * 4) Allocate a buffer for the image and, if required, the color-map. - * 5) Call png_image_finish_read to read the image and, if required, the - * color-map into your buffers. - * - * There are no restrictions on the format of the PNG input itself; all valid - * color types, bit depths, and interlace methods are acceptable, and the - * input image is transformed as necessary to the requested in-memory format - * during the png_image_finish_read() step. The only caveat is that if you - * request a color-mapped image from a PNG that is full-color or makes - * complex use of an alpha channel the transformation is extremely lossy and the - * result may look terrible. - * - * To write a PNG file using the simplified API: - * - * 1) Declare a 'png_image' structure on the stack and memset() it to all zero. - * 2) Initialize the members of the structure that describe the image, setting - * the 'format' member to the format of the image samples. - * 3) Call the appropriate png_image_write... function with a pointer to the - * image and, if necessary, the color-map to write the PNG data. - * - * png_image is a structure that describes the in-memory format of an image - * when it is being read or defines the in-memory format of an image that you - * need to write: - */ -#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) || \ - defined(PNG_SIMPLIFIED_WRITE_SUPPORTED) - -#define PNG_IMAGE_VERSION 1 - -typedef struct png_control *png_controlp; -typedef struct -{ - png_controlp opaque; /* Initialize to NULL, free with png_image_free */ - png_uint_32 version; /* Set to PNG_IMAGE_VERSION */ - png_uint_32 width; /* Image width in pixels (columns) */ - png_uint_32 height; /* Image height in pixels (rows) */ - png_uint_32 format; /* Image format as defined below */ - png_uint_32 flags; /* A bit mask containing informational flags */ - png_uint_32 colormap_entries; - /* Number of entries in the color-map */ - - /* In the event of an error or warning the following field will be set to a - * non-zero value and the 'message' field will contain a '\0' terminated - * string with the libpng error or warning message. If both warnings and - * an error were encountered, only the error is recorded. If there - * are multiple warnings, only the first one is recorded. - * - * The upper 30 bits of this value are reserved, the low two bits contain - * a value as follows: - */ -# define PNG_IMAGE_WARNING 1 -# define PNG_IMAGE_ERROR 2 - /* - * The result is a two-bit code such that a value more than 1 indicates - * a failure in the API just called: - * - * 0 - no warning or error - * 1 - warning - * 2 - error - * 3 - error preceded by warning - */ -# define PNG_IMAGE_FAILED(png_cntrl) ((((png_cntrl).warning_or_error)&0x03)>1) - - png_uint_32 warning_or_error; - - char message[64]; -} png_image, *png_imagep; - -/* The samples of the image have one to four channels whose components have - * original values in the range 0 to 1.0: - * - * 1: A single gray or luminance channel (G). - * 2: A gray/luminance channel and an alpha channel (GA). - * 3: Three red, green, blue color channels (RGB). - * 4: Three color channels and an alpha channel (RGBA). - * - * The components are encoded in one of two ways: - * - * a) As a small integer, value 0..255, contained in a single byte. For the - * alpha channel the original value is simply value/255. For the color or - * luminance channels the value is encoded according to the sRGB specification - * and matches the 8-bit format expected by typical display devices. - * - * The color/gray channels are not scaled (pre-multiplied) by the alpha - * channel and are suitable for passing to color management software. - * - * b) As a value in the range 0..65535, contained in a 2-byte integer. All - * channels can be converted to the original value by dividing by 65535; all - * channels are linear. Color channels use the RGB encoding (RGB end-points) of - * the sRGB specification. This encoding is identified by the - * PNG_FORMAT_FLAG_LINEAR flag below. - * - * When the simplified API needs to convert between sRGB and linear colorspaces, - * the actual sRGB transfer curve defined in the sRGB specification (see the - * article at ) is used, not the gamma=1/2.2 - * approximation used elsewhere in libpng. - * - * When an alpha channel is present it is expected to denote pixel coverage - * of the color or luminance channels and is returned as an associated alpha - * channel: the color/gray channels are scaled (pre-multiplied) by the alpha - * value. - * - * The samples are either contained directly in the image data, between 1 and 8 - * bytes per pixel according to the encoding, or are held in a color-map indexed - * by bytes in the image data. In the case of a color-map the color-map entries - * are individual samples, encoded as above, and the image data has one byte per - * pixel to select the relevant sample from the color-map. - */ - -/* PNG_FORMAT_* - * - * #defines to be used in png_image::format. Each #define identifies a - * particular layout of sample data and, if present, alpha values. There are - * separate defines for each of the two component encodings. - * - * A format is built up using single bit flag values. All combinations are - * valid. Formats can be built up from the flag values or you can use one of - * the predefined values below. When testing formats always use the FORMAT_FLAG - * macros to test for individual features - future versions of the library may - * add new flags. - * - * When reading or writing color-mapped images the format should be set to the - * format of the entries in the color-map then png_image_{read,write}_colormap - * called to read or write the color-map and set the format correctly for the - * image data. Do not set the PNG_FORMAT_FLAG_COLORMAP bit directly! - * - * NOTE: libpng can be built with particular features disabled. If you see - * compiler errors because the definition of one of the following flags has been - * compiled out it is because libpng does not have the required support. It is - * possible, however, for the libpng configuration to enable the format on just - * read or just write; in that case you may see an error at run time. You can - * guard against this by checking for the definition of the appropriate - * "_SUPPORTED" macro, one of: - * - * PNG_SIMPLIFIED_{READ,WRITE}_{BGR,AFIRST}_SUPPORTED - */ -#define PNG_FORMAT_FLAG_ALPHA 0x01U /* format with an alpha channel */ -#define PNG_FORMAT_FLAG_COLOR 0x02U /* color format: otherwise grayscale */ -#define PNG_FORMAT_FLAG_LINEAR 0x04U /* 2-byte channels else 1-byte */ -#define PNG_FORMAT_FLAG_COLORMAP 0x08U /* image data is color-mapped */ - -#ifdef PNG_FORMAT_BGR_SUPPORTED -# define PNG_FORMAT_FLAG_BGR 0x10U /* BGR colors, else order is RGB */ -#endif - -#ifdef PNG_FORMAT_AFIRST_SUPPORTED -# define PNG_FORMAT_FLAG_AFIRST 0x20U /* alpha channel comes first */ -#endif - -#define PNG_FORMAT_FLAG_ASSOCIATED_ALPHA 0x40U /* alpha channel is associated */ - -/* Commonly used formats have predefined macros. - * - * First the single byte (sRGB) formats: - */ -#define PNG_FORMAT_GRAY 0 -#define PNG_FORMAT_GA PNG_FORMAT_FLAG_ALPHA -#define PNG_FORMAT_AG (PNG_FORMAT_GA|PNG_FORMAT_FLAG_AFIRST) -#define PNG_FORMAT_RGB PNG_FORMAT_FLAG_COLOR -#define PNG_FORMAT_BGR (PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_BGR) -#define PNG_FORMAT_RGBA (PNG_FORMAT_RGB|PNG_FORMAT_FLAG_ALPHA) -#define PNG_FORMAT_ARGB (PNG_FORMAT_RGBA|PNG_FORMAT_FLAG_AFIRST) -#define PNG_FORMAT_BGRA (PNG_FORMAT_BGR|PNG_FORMAT_FLAG_ALPHA) -#define PNG_FORMAT_ABGR (PNG_FORMAT_BGRA|PNG_FORMAT_FLAG_AFIRST) - -/* Then the linear 2-byte formats. When naming these "Y" is used to - * indicate a luminance (gray) channel. - */ -#define PNG_FORMAT_LINEAR_Y PNG_FORMAT_FLAG_LINEAR -#define PNG_FORMAT_LINEAR_Y_ALPHA (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_ALPHA) -#define PNG_FORMAT_LINEAR_RGB (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLOR) -#define PNG_FORMAT_LINEAR_RGB_ALPHA \ - (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_ALPHA) - -/* With color-mapped formats the image data is one byte for each pixel, the byte - * is an index into the color-map which is formatted as above. To obtain a - * color-mapped format it is sufficient just to add the PNG_FOMAT_FLAG_COLORMAP - * to one of the above definitions, or you can use one of the definitions below. - */ -#define PNG_FORMAT_RGB_COLORMAP (PNG_FORMAT_RGB|PNG_FORMAT_FLAG_COLORMAP) -#define PNG_FORMAT_BGR_COLORMAP (PNG_FORMAT_BGR|PNG_FORMAT_FLAG_COLORMAP) -#define PNG_FORMAT_RGBA_COLORMAP (PNG_FORMAT_RGBA|PNG_FORMAT_FLAG_COLORMAP) -#define PNG_FORMAT_ARGB_COLORMAP (PNG_FORMAT_ARGB|PNG_FORMAT_FLAG_COLORMAP) -#define PNG_FORMAT_BGRA_COLORMAP (PNG_FORMAT_BGRA|PNG_FORMAT_FLAG_COLORMAP) -#define PNG_FORMAT_ABGR_COLORMAP (PNG_FORMAT_ABGR|PNG_FORMAT_FLAG_COLORMAP) - -/* PNG_IMAGE macros - * - * These are convenience macros to derive information from a png_image - * structure. The PNG_IMAGE_SAMPLE_ macros return values appropriate to the - * actual image sample values - either the entries in the color-map or the - * pixels in the image. The PNG_IMAGE_PIXEL_ macros return corresponding values - * for the pixels and will always return 1 for color-mapped formats. The - * remaining macros return information about the rows in the image and the - * complete image. - * - * NOTE: All the macros that take a png_image::format parameter are compile time - * constants if the format parameter is, itself, a constant. Therefore these - * macros can be used in array declarations and case labels where required. - * Similarly the macros are also pre-processor constants (sizeof is not used) so - * they can be used in #if tests. - * - * First the information about the samples. - */ -#define PNG_IMAGE_SAMPLE_CHANNELS(fmt)\ - (((fmt)&(PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_ALPHA))+1) - /* Return the total number of channels in a given format: 1..4 */ - -#define PNG_IMAGE_SAMPLE_COMPONENT_SIZE(fmt)\ - ((((fmt) & PNG_FORMAT_FLAG_LINEAR) >> 2)+1) - /* Return the size in bytes of a single component of a pixel or color-map - * entry (as appropriate) in the image: 1 or 2. - */ - -#define PNG_IMAGE_SAMPLE_SIZE(fmt)\ - (PNG_IMAGE_SAMPLE_CHANNELS(fmt) * PNG_IMAGE_SAMPLE_COMPONENT_SIZE(fmt)) - /* This is the size of the sample data for one sample. If the image is - * color-mapped it is the size of one color-map entry (and image pixels are - * one byte in size), otherwise it is the size of one image pixel. - */ - -#define PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(fmt)\ - (PNG_IMAGE_SAMPLE_CHANNELS(fmt) * 256) - /* The maximum size of the color-map required by the format expressed in a - * count of components. This can be used to compile-time allocate a - * color-map: - * - * png_uint_16 colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(linear_fmt)]; - * - * png_byte colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(sRGB_fmt)]; - * - * Alternatively use the PNG_IMAGE_COLORMAP_SIZE macro below to use the - * information from one of the png_image_begin_read_ APIs and dynamically - * allocate the required memory. - */ - -/* Corresponding information about the pixels */ -#define PNG_IMAGE_PIXEL_(test,fmt)\ - (((fmt)&PNG_FORMAT_FLAG_COLORMAP)?1:test(fmt)) - -#define PNG_IMAGE_PIXEL_CHANNELS(fmt)\ - PNG_IMAGE_PIXEL_(PNG_IMAGE_SAMPLE_CHANNELS,fmt) - /* The number of separate channels (components) in a pixel; 1 for a - * color-mapped image. - */ - -#define PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)\ - PNG_IMAGE_PIXEL_(PNG_IMAGE_SAMPLE_COMPONENT_SIZE,fmt) - /* The size, in bytes, of each component in a pixel; 1 for a color-mapped - * image. - */ - -#define PNG_IMAGE_PIXEL_SIZE(fmt) PNG_IMAGE_PIXEL_(PNG_IMAGE_SAMPLE_SIZE,fmt) - /* The size, in bytes, of a complete pixel; 1 for a color-mapped image. */ - -/* Information about the whole row, or whole image */ -#define PNG_IMAGE_ROW_STRIDE(image)\ - (PNG_IMAGE_PIXEL_CHANNELS((image).format) * (image).width) - /* Return the total number of components in a single row of the image; this - * is the minimum 'row stride', the minimum count of components between each - * row. For a color-mapped image this is the minimum number of bytes in a - * row. - * - * WARNING: this macro overflows for some images with more than one component - * and very large image widths. libpng will refuse to process an image where - * this macro would overflow. - */ - -#define PNG_IMAGE_BUFFER_SIZE(image, row_stride)\ - (PNG_IMAGE_PIXEL_COMPONENT_SIZE((image).format)*(image).height*(row_stride)) - /* Return the size, in bytes, of an image buffer given a png_image and a row - * stride - the number of components to leave space for in each row. - * - * WARNING: this macro overflows a 32-bit integer for some large PNG images, - * libpng will refuse to process an image where such an overflow would occur. - */ - -#define PNG_IMAGE_SIZE(image)\ - PNG_IMAGE_BUFFER_SIZE(image, PNG_IMAGE_ROW_STRIDE(image)) - /* Return the size, in bytes, of the image in memory given just a png_image; - * the row stride is the minimum stride required for the image. - */ - -#define PNG_IMAGE_COLORMAP_SIZE(image)\ - (PNG_IMAGE_SAMPLE_SIZE((image).format) * (image).colormap_entries) - /* Return the size, in bytes, of the color-map of this image. If the image - * format is not a color-map format this will return a size sufficient for - * 256 entries in the given format; check PNG_FORMAT_FLAG_COLORMAP if - * you don't want to allocate a color-map in this case. - */ - -/* PNG_IMAGE_FLAG_* - * - * Flags containing additional information about the image are held in the - * 'flags' field of png_image. - */ -#define PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB 0x01 - /* This indicates that the RGB values of the in-memory bitmap do not - * correspond to the red, green and blue end-points defined by sRGB. - */ - -#define PNG_IMAGE_FLAG_FAST 0x02 - /* On write emphasise speed over compression; the resultant PNG file will be - * larger but will be produced significantly faster, particular for large - * images. Do not use this option for images which will be distributed, only - * used it when producing intermediate files that will be read back in - * repeatedly. For a typical 24-bit image the option will double the read - * speed at the cost of increasing the image size by 25%, however for many - * more compressible images the PNG file can be 10 times larger with only a - * slight speed gain. - */ - -#define PNG_IMAGE_FLAG_16BIT_sRGB 0x04 - /* On read if the image is a 16-bit per component image and there is no gAMA - * or sRGB chunk assume that the components are sRGB encoded. Notice that - * images output by the simplified API always have gamma information; setting - * this flag only affects the interpretation of 16-bit images from an - * external source. It is recommended that the application expose this flag - * to the user; the user can normally easily recognize the difference between - * linear and sRGB encoding. This flag has no effect on write - the data - * passed to the write APIs must have the correct encoding (as defined - * above.) - * - * If the flag is not set (the default) input 16-bit per component data is - * assumed to be linear. - * - * NOTE: the flag can only be set after the png_image_begin_read_ call, - * because that call initializes the 'flags' field. - */ - -#ifdef PNG_SIMPLIFIED_READ_SUPPORTED -/* READ APIs - * --------- - * - * The png_image passed to the read APIs must have been initialized by setting - * the png_controlp field 'opaque' to NULL (or, safer, memset the whole thing.) - */ -#ifdef PNG_STDIO_SUPPORTED -PNG_EXPORT(234, int, png_image_begin_read_from_file, (png_imagep image, - const char *file_name)); - /* The named file is opened for read and the image header is filled in - * from the PNG header in the file. - */ - -PNG_EXPORT(235, int, png_image_begin_read_from_stdio, (png_imagep image, - FILE* file)); - /* The PNG header is read from the stdio FILE object. */ -#endif /* STDIO */ - -PNG_EXPORT(236, int, png_image_begin_read_from_memory, (png_imagep image, - png_const_voidp memory, size_t size)); - /* The PNG header is read from the given memory buffer. */ - -PNG_EXPORT(237, int, png_image_finish_read, (png_imagep image, - png_const_colorp background, void *buffer, png_int_32 row_stride, - void *colormap)); - /* Finish reading the image into the supplied buffer and clean up the - * png_image structure. - * - * row_stride is the step, in byte or 2-byte units as appropriate, - * between adjacent rows. A positive stride indicates that the top-most row - * is first in the buffer - the normal top-down arrangement. A negative - * stride indicates that the bottom-most row is first in the buffer. - * - * background need only be supplied if an alpha channel must be removed from - * a png_byte format and the removal is to be done by compositing on a solid - * color; otherwise it may be NULL and any composition will be done directly - * onto the buffer. The value is an sRGB color to use for the background, - * for grayscale output the green channel is used. - * - * background must be supplied when an alpha channel must be removed from a - * single byte color-mapped output format, in other words if: - * - * 1) The original format from png_image_begin_read_from_* had - * PNG_FORMAT_FLAG_ALPHA set. - * 2) The format set by the application does not. - * 3) The format set by the application has PNG_FORMAT_FLAG_COLORMAP set and - * PNG_FORMAT_FLAG_LINEAR *not* set. - * - * For linear output removing the alpha channel is always done by compositing - * on black and background is ignored. - * - * colormap must be supplied when PNG_FORMAT_FLAG_COLORMAP is set. It must - * be at least the size (in bytes) returned by PNG_IMAGE_COLORMAP_SIZE. - * image->colormap_entries will be updated to the actual number of entries - * written to the colormap; this may be less than the original value. - */ - -PNG_EXPORT(238, void, png_image_free, (png_imagep image)); - /* Free any data allocated by libpng in image->opaque, setting the pointer to - * NULL. May be called at any time after the structure is initialized. - */ -#endif /* SIMPLIFIED_READ */ - -#ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED -/* WRITE APIS - * ---------- - * For write you must initialize a png_image structure to describe the image to - * be written. To do this use memset to set the whole structure to 0 then - * initialize fields describing your image. - * - * version: must be set to PNG_IMAGE_VERSION - * opaque: must be initialized to NULL - * width: image width in pixels - * height: image height in rows - * format: the format of the data (image and color-map) you wish to write - * flags: set to 0 unless one of the defined flags applies; set - * PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB for color format images where the RGB - * values do not correspond to the colors in sRGB. - * colormap_entries: set to the number of entries in the color-map (0 to 256) - */ -#ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED -PNG_EXPORT(239, int, png_image_write_to_file, (png_imagep image, - const char *file, int convert_to_8bit, const void *buffer, - png_int_32 row_stride, const void *colormap)); - /* Write the image to the named file. */ - -PNG_EXPORT(240, int, png_image_write_to_stdio, (png_imagep image, FILE *file, - int convert_to_8_bit, const void *buffer, png_int_32 row_stride, - const void *colormap)); - /* Write the image to the given (FILE*). */ -#endif /* SIMPLIFIED_WRITE_STDIO */ - -/* With all write APIs if image is in one of the linear formats with 16-bit - * data then setting convert_to_8_bit will cause the output to be an 8-bit PNG - * gamma encoded according to the sRGB specification, otherwise a 16-bit linear - * encoded PNG file is written. - * - * With color-mapped data formats the colormap parameter point to a color-map - * with at least image->colormap_entries encoded in the specified format. If - * the format is linear the written PNG color-map will be converted to sRGB - * regardless of the convert_to_8_bit flag. - * - * With all APIs row_stride is handled as in the read APIs - it is the spacing - * from one row to the next in component sized units (1 or 2 bytes) and if - * negative indicates a bottom-up row layout in the buffer. If row_stride is - * zero, libpng will calculate it for you from the image width and number of - * channels. - * - * Note that the write API does not support interlacing, sub-8-bit pixels or - * most ancillary chunks. If you need to write text chunks (e.g. for copyright - * notices) you need to use one of the other APIs. - */ - -PNG_EXPORT(245, int, png_image_write_to_memory, (png_imagep image, void *memory, - png_alloc_size_t * PNG_RESTRICT memory_bytes, int convert_to_8_bit, - const void *buffer, png_int_32 row_stride, const void *colormap)); - /* Write the image to the given memory buffer. The function both writes the - * whole PNG data stream to *memory and updates *memory_bytes with the count - * of bytes written. - * - * 'memory' may be NULL. In this case *memory_bytes is not read however on - * success the number of bytes which would have been written will still be - * stored in *memory_bytes. On failure *memory_bytes will contain 0. - * - * If 'memory' is not NULL it must point to memory[*memory_bytes] of - * writeable memory. - * - * If the function returns success memory[*memory_bytes] (if 'memory' is not - * NULL) contains the written PNG data. *memory_bytes will always be less - * than or equal to the original value. - * - * If the function returns false and *memory_bytes was not changed an error - * occurred during write. If *memory_bytes was changed, or is not 0 if - * 'memory' was NULL, the write would have succeeded but for the memory - * buffer being too small. *memory_bytes contains the required number of - * bytes and will be bigger that the original value. - */ - -#define png_image_write_get_memory_size(image, size, convert_to_8_bit, buffer,\ - row_stride, colormap)\ - png_image_write_to_memory(&(image), 0, &(size), convert_to_8_bit, buffer,\ - row_stride, colormap) - /* Return the amount of memory in 'size' required to compress this image. - * The png_image structure 'image' must be filled in as in the above - * function and must not be changed before the actual write call, the buffer - * and all other parameters must also be identical to that in the final - * write call. The 'size' variable need not be initialized. - * - * NOTE: the macro returns true/false, if false is returned 'size' will be - * set to zero and the write failed and probably will fail if tried again. - */ - -/* You can pre-allocate the buffer by making sure it is of sufficient size - * regardless of the amount of compression achieved. The buffer size will - * always be bigger than the original image and it will never be filled. The - * following macros are provided to assist in allocating the buffer. - */ -#define PNG_IMAGE_DATA_SIZE(image) (PNG_IMAGE_SIZE(image)+(image).height) - /* The number of uncompressed bytes in the PNG byte encoding of the image; - * uncompressing the PNG IDAT data will give this number of bytes. - * - * NOTE: while PNG_IMAGE_SIZE cannot overflow for an image in memory this - * macro can because of the extra bytes used in the PNG byte encoding. You - * need to avoid this macro if your image size approaches 2^30 in width or - * height. The same goes for the remainder of these macros; they all produce - * bigger numbers than the actual in-memory image size. - */ -#ifndef PNG_ZLIB_MAX_SIZE -# define PNG_ZLIB_MAX_SIZE(b) ((b)+(((b)+7U)>>3)+(((b)+63U)>>6)+11U) - /* An upper bound on the number of compressed bytes given 'b' uncompressed - * bytes. This is based on deflateBounds() in zlib; different - * implementations of zlib compression may conceivably produce more data so - * if your zlib implementation is not zlib itself redefine this macro - * appropriately. - */ -#endif - -#define PNG_IMAGE_COMPRESSED_SIZE_MAX(image)\ - PNG_ZLIB_MAX_SIZE((png_alloc_size_t)PNG_IMAGE_DATA_SIZE(image)) - /* An upper bound on the size of the data in the PNG IDAT chunks. */ - -#define PNG_IMAGE_PNG_SIZE_MAX_(image, image_size)\ - ((8U/*sig*/+25U/*IHDR*/+16U/*gAMA*/+44U/*cHRM*/+12U/*IEND*/+\ - (((image).format&PNG_FORMAT_FLAG_COLORMAP)?/*colormap: PLTE, tRNS*/\ - 12U+3U*(image).colormap_entries/*PLTE data*/+\ - (((image).format&PNG_FORMAT_FLAG_ALPHA)?\ - 12U/*tRNS*/+(image).colormap_entries:0U):0U)+\ - 12U)+(12U*((image_size)/PNG_ZBUF_SIZE))/*IDAT*/+(image_size)) - /* A helper for the following macro; if your compiler cannot handle the - * following macro use this one with the result of - * PNG_IMAGE_COMPRESSED_SIZE_MAX(image) as the second argument (most - * compilers should handle this just fine.) - */ - -#define PNG_IMAGE_PNG_SIZE_MAX(image)\ - PNG_IMAGE_PNG_SIZE_MAX_(image, PNG_IMAGE_COMPRESSED_SIZE_MAX(image)) - /* An upper bound on the total length of the PNG data stream for 'image'. - * The result is of type png_alloc_size_t, on 32-bit systems this may - * overflow even though PNG_IMAGE_DATA_SIZE does not overflow; the write will - * run out of buffer space but return a corrected size which should work. - */ -#endif /* SIMPLIFIED_WRITE */ -/******************************************************************************* - * END OF SIMPLIFIED API - ******************************************************************************/ -#endif /* SIMPLIFIED_{READ|WRITE} */ - -/******************************************************************************* - * Section 6: IMPLEMENTATION OPTIONS - ******************************************************************************* - * - * Support for arbitrary implementation-specific optimizations. The API allows - * particular options to be turned on or off. 'Option' is the number of the - * option and 'onoff' is 0 (off) or non-0 (on). The value returned is given - * by the PNG_OPTION_ defines below. - * - * HARDWARE: normally hardware capabilities, such as the Intel SSE instructions, - * are detected at run time, however sometimes it may be impossible - * to do this in user mode, in which case it is necessary to discover - * the capabilities in an OS specific way. Such capabilities are - * listed here when libpng has support for them and must be turned - * ON by the application if present. - * - * SOFTWARE: sometimes software optimizations actually result in performance - * decrease on some architectures or systems, or with some sets of - * PNG images. 'Software' options allow such optimizations to be - * selected at run time. - */ -#ifdef PNG_SET_OPTION_SUPPORTED -#ifdef PNG_ARM_NEON_API_SUPPORTED -# define PNG_ARM_NEON 0 /* HARDWARE: ARM Neon SIMD instructions supported */ -#endif -#define PNG_MAXIMUM_INFLATE_WINDOW 2 /* SOFTWARE: force maximum window */ -#define PNG_SKIP_sRGB_CHECK_PROFILE 4 /* SOFTWARE: Check ICC profile for sRGB */ -#ifdef PNG_MIPS_MSA_API_SUPPORTED -# define PNG_MIPS_MSA 6 /* HARDWARE: MIPS Msa SIMD instructions supported */ -#endif -#define PNG_IGNORE_ADLER32 8 -#ifdef PNG_POWERPC_VSX_API_SUPPORTED -# define PNG_POWERPC_VSX 10 /* HARDWARE: PowerPC VSX SIMD instructions supported */ -#endif -#define PNG_OPTION_NEXT 12 /* Next option - numbers must be even */ - -/* Return values: NOTE: there are four values and 'off' is *not* zero */ -#define PNG_OPTION_UNSET 0 /* Unset - defaults to off */ -#define PNG_OPTION_INVALID 1 /* Option number out of range */ -#define PNG_OPTION_OFF 2 -#define PNG_OPTION_ON 3 - -PNG_EXPORT(244, int, png_set_option, (png_structrp png_ptr, int option, - int onoff)); -#endif /* SET_OPTION */ - -/******************************************************************************* - * END OF HARDWARE AND SOFTWARE OPTIONS - ******************************************************************************/ - -/* Maintainer: Put new public prototypes here ^, in libpng.3, in project - * defs, and in scripts/symbols.def. - */ - -/* The last ordinal number (this is the *last* one already used; the next - * one to use is one more than this.) - */ -#ifdef PNG_EXPORT_LAST_ORDINAL - PNG_EXPORT_LAST_ORDINAL(249); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* PNG_VERSION_INFO_ONLY */ -/* Do not put anything past this line */ -#endif /* PNG_H */ diff --git a/libs/include/libpng/pngconf.h b/libs/include/libpng/pngconf.h deleted file mode 100644 index 927a769d..00000000 --- a/libs/include/libpng/pngconf.h +++ /dev/null @@ -1,623 +0,0 @@ - -/* pngconf.h - machine-configurable file for libpng - * - * libpng version 1.6.37 - * - * Copyright (c) 2018-2019 Cosmin Truta - * Copyright (c) 1998-2002,2004,2006-2016,2018 Glenn Randers-Pehrson - * Copyright (c) 1996-1997 Andreas Dilger - * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. - * - * This code is released under the libpng license. - * For conditions of distribution and use, see the disclaimer - * and license in png.h - * - * Any machine specific code is near the front of this file, so if you - * are configuring libpng for a machine, you may want to read the section - * starting here down to where it starts to typedef png_color, png_text, - * and png_info. - */ - -#ifndef PNGCONF_H -#define PNGCONF_H - -#ifndef PNG_BUILDING_SYMBOL_TABLE /* else includes may cause problems */ - -/* From libpng 1.6.0 libpng requires an ANSI X3.159-1989 ("ISOC90") compliant C - * compiler for correct compilation. The following header files are required by - * the standard. If your compiler doesn't provide these header files, or they - * do not match the standard, you will need to provide/improve them. - */ -#include -#include - -/* Library header files. These header files are all defined by ISOC90; libpng - * expects conformant implementations, however, an ISOC90 conformant system need - * not provide these header files if the functionality cannot be implemented. - * In this case it will be necessary to disable the relevant parts of libpng in - * the build of pnglibconf.h. - * - * Prior to 1.6.0 string.h was included here; the API changes in 1.6.0 to not - * include this unnecessary header file. - */ - -#ifdef PNG_STDIO_SUPPORTED - /* Required for the definition of FILE: */ -# include -#endif - -#ifdef PNG_SETJMP_SUPPORTED - /* Required for the definition of jmp_buf and the declaration of longjmp: */ -# include -#endif - -#ifdef PNG_CONVERT_tIME_SUPPORTED - /* Required for struct tm: */ -# include -#endif - -#endif /* PNG_BUILDING_SYMBOL_TABLE */ - -/* Prior to 1.6.0, it was possible to turn off 'const' in declarations, - * using PNG_NO_CONST. This is no longer supported. - */ -#define PNG_CONST const /* backward compatibility only */ - -/* This controls optimization of the reading of 16-bit and 32-bit - * values from PNG files. It can be set on a per-app-file basis: it - * just changes whether a macro is used when the function is called. - * The library builder sets the default; if read functions are not - * built into the library the macro implementation is forced on. - */ -#ifndef PNG_READ_INT_FUNCTIONS_SUPPORTED -# define PNG_USE_READ_MACROS -#endif -#if !defined(PNG_NO_USE_READ_MACROS) && !defined(PNG_USE_READ_MACROS) -# if PNG_DEFAULT_READ_MACROS -# define PNG_USE_READ_MACROS -# endif -#endif - -/* COMPILER SPECIFIC OPTIONS. - * - * These options are provided so that a variety of difficult compilers - * can be used. Some are fixed at build time (e.g. PNG_API_RULE - * below) but still have compiler specific implementations, others - * may be changed on a per-file basis when compiling against libpng. - */ - -/* The PNGARG macro was used in versions of libpng prior to 1.6.0 to protect - * against legacy (pre ISOC90) compilers that did not understand function - * prototypes. It is not required for modern C compilers. - */ -#ifndef PNGARG -# define PNGARG(arglist) arglist -#endif - -/* Function calling conventions. - * ============================= - * Normally it is not necessary to specify to the compiler how to call - * a function - it just does it - however on x86 systems derived from - * Microsoft and Borland C compilers ('IBM PC', 'DOS', 'Windows' systems - * and some others) there are multiple ways to call a function and the - * default can be changed on the compiler command line. For this reason - * libpng specifies the calling convention of every exported function and - * every function called via a user supplied function pointer. This is - * done in this file by defining the following macros: - * - * PNGAPI Calling convention for exported functions. - * PNGCBAPI Calling convention for user provided (callback) functions. - * PNGCAPI Calling convention used by the ANSI-C library (required - * for longjmp callbacks and sometimes used internally to - * specify the calling convention for zlib). - * - * These macros should never be overridden. If it is necessary to - * change calling convention in a private build this can be done - * by setting PNG_API_RULE (which defaults to 0) to one of the values - * below to select the correct 'API' variants. - * - * PNG_API_RULE=0 Use PNGCAPI - the 'C' calling convention - throughout. - * This is correct in every known environment. - * PNG_API_RULE=1 Use the operating system convention for PNGAPI and - * the 'C' calling convention (from PNGCAPI) for - * callbacks (PNGCBAPI). This is no longer required - * in any known environment - if it has to be used - * please post an explanation of the problem to the - * libpng mailing list. - * - * These cases only differ if the operating system does not use the C - * calling convention, at present this just means the above cases - * (x86 DOS/Windows systems) and, even then, this does not apply to - * Cygwin running on those systems. - * - * Note that the value must be defined in pnglibconf.h so that what - * the application uses to call the library matches the conventions - * set when building the library. - */ - -/* Symbol export - * ============= - * When building a shared library it is almost always necessary to tell - * the compiler which symbols to export. The png.h macro 'PNG_EXPORT' - * is used to mark the symbols. On some systems these symbols can be - * extracted at link time and need no special processing by the compiler, - * on other systems the symbols are flagged by the compiler and just - * the declaration requires a special tag applied (unfortunately) in a - * compiler dependent way. Some systems can do either. - * - * A small number of older systems also require a symbol from a DLL to - * be flagged to the program that calls it. This is a problem because - * we do not know in the header file included by application code that - * the symbol will come from a shared library, as opposed to a statically - * linked one. For this reason the application must tell us by setting - * the magic flag PNG_USE_DLL to turn on the special processing before - * it includes png.h. - * - * Four additional macros are used to make this happen: - * - * PNG_IMPEXP The magic (if any) to cause a symbol to be exported from - * the build or imported if PNG_USE_DLL is set - compiler - * and system specific. - * - * PNG_EXPORT_TYPE(type) A macro that pre or appends PNG_IMPEXP to - * 'type', compiler specific. - * - * PNG_DLL_EXPORT Set to the magic to use during a libpng build to - * make a symbol exported from the DLL. Not used in the - * public header files; see pngpriv.h for how it is used - * in the libpng build. - * - * PNG_DLL_IMPORT Set to the magic to force the libpng symbols to come - * from a DLL - used to define PNG_IMPEXP when - * PNG_USE_DLL is set. - */ - -/* System specific discovery. - * ========================== - * This code is used at build time to find PNG_IMPEXP, the API settings - * and PNG_EXPORT_TYPE(), it may also set a macro to indicate the DLL - * import processing is possible. On Windows systems it also sets - * compiler-specific macros to the values required to change the calling - * conventions of the various functions. - */ -#if defined(_Windows) || defined(_WINDOWS) || defined(WIN32) ||\ - defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) - /* Windows system (DOS doesn't support DLLs). Includes builds under Cygwin or - * MinGW on any architecture currently supported by Windows. Also includes - * Watcom builds but these need special treatment because they are not - * compatible with GCC or Visual C because of different calling conventions. - */ -# if PNG_API_RULE == 2 - /* If this line results in an error, either because __watcall is not - * understood or because of a redefine just below you cannot use *this* - * build of the library with the compiler you are using. *This* build was - * build using Watcom and applications must also be built using Watcom! - */ -# define PNGCAPI __watcall -# endif - -# if defined(__GNUC__) || (defined(_MSC_VER) && (_MSC_VER >= 800)) -# define PNGCAPI __cdecl -# if PNG_API_RULE == 1 - /* If this line results in an error __stdcall is not understood and - * PNG_API_RULE should not have been set to '1'. - */ -# define PNGAPI __stdcall -# endif -# else - /* An older compiler, or one not detected (erroneously) above, - * if necessary override on the command line to get the correct - * variants for the compiler. - */ -# ifndef PNGCAPI -# define PNGCAPI _cdecl -# endif -# if PNG_API_RULE == 1 && !defined(PNGAPI) -# define PNGAPI _stdcall -# endif -# endif /* compiler/api */ - - /* NOTE: PNGCBAPI always defaults to PNGCAPI. */ - -# if defined(PNGAPI) && !defined(PNG_USER_PRIVATEBUILD) -# error "PNG_USER_PRIVATEBUILD must be defined if PNGAPI is changed" -# endif - -# if (defined(_MSC_VER) && _MSC_VER < 800) ||\ - (defined(__BORLANDC__) && __BORLANDC__ < 0x500) - /* older Borland and MSC - * compilers used '__export' and required this to be after - * the type. - */ -# ifndef PNG_EXPORT_TYPE -# define PNG_EXPORT_TYPE(type) type PNG_IMPEXP -# endif -# define PNG_DLL_EXPORT __export -# else /* newer compiler */ -# define PNG_DLL_EXPORT __declspec(dllexport) -# ifndef PNG_DLL_IMPORT -# define PNG_DLL_IMPORT __declspec(dllimport) -# endif -# endif /* compiler */ - -#else /* !Windows */ -# if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__) -# define PNGAPI _System -# else /* !Windows/x86 && !OS/2 */ - /* Use the defaults, or define PNG*API on the command line (but - * this will have to be done for every compile!) - */ -# endif /* other system, !OS/2 */ -#endif /* !Windows/x86 */ - -/* Now do all the defaulting . */ -#ifndef PNGCAPI -# define PNGCAPI -#endif -#ifndef PNGCBAPI -# define PNGCBAPI PNGCAPI -#endif -#ifndef PNGAPI -# define PNGAPI PNGCAPI -#endif - -/* PNG_IMPEXP may be set on the compilation system command line or (if not set) - * then in an internal header file when building the library, otherwise (when - * using the library) it is set here. - */ -#ifndef PNG_IMPEXP -# if defined(PNG_USE_DLL) && defined(PNG_DLL_IMPORT) - /* This forces use of a DLL, disallowing static linking */ -# define PNG_IMPEXP PNG_DLL_IMPORT -# endif - -# ifndef PNG_IMPEXP -# define PNG_IMPEXP -# endif -#endif - -/* In 1.5.2 the definition of PNG_FUNCTION has been changed to always treat - * 'attributes' as a storage class - the attributes go at the start of the - * function definition, and attributes are always appended regardless of the - * compiler. This considerably simplifies these macros but may cause problems - * if any compilers both need function attributes and fail to handle them as - * a storage class (this is unlikely.) - */ -#ifndef PNG_FUNCTION -# define PNG_FUNCTION(type, name, args, attributes) attributes type name args -#endif - -#ifndef PNG_EXPORT_TYPE -# define PNG_EXPORT_TYPE(type) PNG_IMPEXP type -#endif - - /* The ordinal value is only relevant when preprocessing png.h for symbol - * table entries, so we discard it here. See the .dfn files in the - * scripts directory. - */ - -#ifndef PNG_EXPORTA -# define PNG_EXPORTA(ordinal, type, name, args, attributes) \ - PNG_FUNCTION(PNG_EXPORT_TYPE(type), (PNGAPI name), PNGARG(args), \ - PNG_LINKAGE_API attributes) -#endif - -/* ANSI-C (C90) does not permit a macro to be invoked with an empty argument, - * so make something non-empty to satisfy the requirement: - */ -#define PNG_EMPTY /*empty list*/ - -#define PNG_EXPORT(ordinal, type, name, args) \ - PNG_EXPORTA(ordinal, type, name, args, PNG_EMPTY) - -/* Use PNG_REMOVED to comment out a removed interface. */ -#ifndef PNG_REMOVED -# define PNG_REMOVED(ordinal, type, name, args, attributes) -#endif - -#ifndef PNG_CALLBACK -# define PNG_CALLBACK(type, name, args) type (PNGCBAPI name) PNGARG(args) -#endif - -/* Support for compiler specific function attributes. These are used - * so that where compiler support is available incorrect use of API - * functions in png.h will generate compiler warnings. - * - * Added at libpng-1.2.41. - */ - -#ifndef PNG_NO_PEDANTIC_WARNINGS -# ifndef PNG_PEDANTIC_WARNINGS_SUPPORTED -# define PNG_PEDANTIC_WARNINGS_SUPPORTED -# endif -#endif - -#ifdef PNG_PEDANTIC_WARNINGS_SUPPORTED - /* Support for compiler specific function attributes. These are used - * so that where compiler support is available, incorrect use of API - * functions in png.h will generate compiler warnings. Added at libpng - * version 1.2.41. Disabling these removes the warnings but may also produce - * less efficient code. - */ -# if defined(__clang__) && defined(__has_attribute) - /* Clang defines both __clang__ and __GNUC__. Check __clang__ first. */ -# if !defined(PNG_USE_RESULT) && __has_attribute(__warn_unused_result__) -# define PNG_USE_RESULT __attribute__((__warn_unused_result__)) -# endif -# if !defined(PNG_NORETURN) && __has_attribute(__noreturn__) -# define PNG_NORETURN __attribute__((__noreturn__)) -# endif -# if !defined(PNG_ALLOCATED) && __has_attribute(__malloc__) -# define PNG_ALLOCATED __attribute__((__malloc__)) -# endif -# if !defined(PNG_DEPRECATED) && __has_attribute(__deprecated__) -# define PNG_DEPRECATED __attribute__((__deprecated__)) -# endif -# if !defined(PNG_PRIVATE) -# ifdef __has_extension -# if __has_extension(attribute_unavailable_with_message) -# define PNG_PRIVATE __attribute__((__unavailable__(\ - "This function is not exported by libpng."))) -# endif -# endif -# endif -# ifndef PNG_RESTRICT -# define PNG_RESTRICT __restrict -# endif - -# elif defined(__GNUC__) -# ifndef PNG_USE_RESULT -# define PNG_USE_RESULT __attribute__((__warn_unused_result__)) -# endif -# ifndef PNG_NORETURN -# define PNG_NORETURN __attribute__((__noreturn__)) -# endif -# if __GNUC__ >= 3 -# ifndef PNG_ALLOCATED -# define PNG_ALLOCATED __attribute__((__malloc__)) -# endif -# ifndef PNG_DEPRECATED -# define PNG_DEPRECATED __attribute__((__deprecated__)) -# endif -# ifndef PNG_PRIVATE -# if 0 /* Doesn't work so we use deprecated instead*/ -# define PNG_PRIVATE \ - __attribute__((warning("This function is not exported by libpng."))) -# else -# define PNG_PRIVATE \ - __attribute__((__deprecated__)) -# endif -# endif -# if ((__GNUC__ > 3) || !defined(__GNUC_MINOR__) || (__GNUC_MINOR__ >= 1)) -# ifndef PNG_RESTRICT -# define PNG_RESTRICT __restrict -# endif -# endif /* __GNUC__.__GNUC_MINOR__ > 3.0 */ -# endif /* __GNUC__ >= 3 */ - -# elif defined(_MSC_VER) && (_MSC_VER >= 1300) -# ifndef PNG_USE_RESULT -# define PNG_USE_RESULT /* not supported */ -# endif -# ifndef PNG_NORETURN -# define PNG_NORETURN __declspec(noreturn) -# endif -# ifndef PNG_ALLOCATED -# if (_MSC_VER >= 1400) -# define PNG_ALLOCATED __declspec(restrict) -# endif -# endif -# ifndef PNG_DEPRECATED -# define PNG_DEPRECATED __declspec(deprecated) -# endif -# ifndef PNG_PRIVATE -# define PNG_PRIVATE __declspec(deprecated) -# endif -# ifndef PNG_RESTRICT -# if (_MSC_VER >= 1400) -# define PNG_RESTRICT __restrict -# endif -# endif - -# elif defined(__WATCOMC__) -# ifndef PNG_RESTRICT -# define PNG_RESTRICT __restrict -# endif -# endif -#endif /* PNG_PEDANTIC_WARNINGS */ - -#ifndef PNG_DEPRECATED -# define PNG_DEPRECATED /* Use of this function is deprecated */ -#endif -#ifndef PNG_USE_RESULT -# define PNG_USE_RESULT /* The result of this function must be checked */ -#endif -#ifndef PNG_NORETURN -# define PNG_NORETURN /* This function does not return */ -#endif -#ifndef PNG_ALLOCATED -# define PNG_ALLOCATED /* The result of the function is new memory */ -#endif -#ifndef PNG_PRIVATE -# define PNG_PRIVATE /* This is a private libpng function */ -#endif -#ifndef PNG_RESTRICT -# define PNG_RESTRICT /* The C99 "restrict" feature */ -#endif - -#ifndef PNG_FP_EXPORT /* A floating point API. */ -# ifdef PNG_FLOATING_POINT_SUPPORTED -# define PNG_FP_EXPORT(ordinal, type, name, args)\ - PNG_EXPORT(ordinal, type, name, args); -# else /* No floating point APIs */ -# define PNG_FP_EXPORT(ordinal, type, name, args) -# endif -#endif -#ifndef PNG_FIXED_EXPORT /* A fixed point API. */ -# ifdef PNG_FIXED_POINT_SUPPORTED -# define PNG_FIXED_EXPORT(ordinal, type, name, args)\ - PNG_EXPORT(ordinal, type, name, args); -# else /* No fixed point APIs */ -# define PNG_FIXED_EXPORT(ordinal, type, name, args) -# endif -#endif - -#ifndef PNG_BUILDING_SYMBOL_TABLE -/* Some typedefs to get us started. These should be safe on most of the common - * platforms. - * - * png_uint_32 and png_int_32 may, currently, be larger than required to hold a - * 32-bit value however this is not normally advisable. - * - * png_uint_16 and png_int_16 should always be two bytes in size - this is - * verified at library build time. - * - * png_byte must always be one byte in size. - * - * The checks below use constants from limits.h, as defined by the ISOC90 - * standard. - */ -#if CHAR_BIT == 8 && UCHAR_MAX == 255 - typedef unsigned char png_byte; -#else -# error "libpng requires 8-bit bytes" -#endif - -#if INT_MIN == -32768 && INT_MAX == 32767 - typedef int png_int_16; -#elif SHRT_MIN == -32768 && SHRT_MAX == 32767 - typedef short png_int_16; -#else -# error "libpng requires a signed 16-bit type" -#endif - -#if UINT_MAX == 65535 - typedef unsigned int png_uint_16; -#elif USHRT_MAX == 65535 - typedef unsigned short png_uint_16; -#else -# error "libpng requires an unsigned 16-bit type" -#endif - -#if INT_MIN < -2147483646 && INT_MAX > 2147483646 - typedef int png_int_32; -#elif LONG_MIN < -2147483646 && LONG_MAX > 2147483646 - typedef long int png_int_32; -#else -# error "libpng requires a signed 32-bit (or more) type" -#endif - -#if UINT_MAX > 4294967294U - typedef unsigned int png_uint_32; -#elif ULONG_MAX > 4294967294U - typedef unsigned long int png_uint_32; -#else -# error "libpng requires an unsigned 32-bit (or more) type" -#endif - -/* Prior to 1.6.0, it was possible to disable the use of size_t and ptrdiff_t. - * From 1.6.0 onwards, an ISO C90 compiler, as well as a standard-compliant - * behavior of sizeof and ptrdiff_t are required. - * The legacy typedefs are provided here for backwards compatibility. - */ -typedef size_t png_size_t; -typedef ptrdiff_t png_ptrdiff_t; - -/* libpng needs to know the maximum value of 'size_t' and this controls the - * definition of png_alloc_size_t, below. This maximum value of size_t limits - * but does not control the maximum allocations the library makes - there is - * direct application control of this through png_set_user_limits(). - */ -#ifndef PNG_SMALL_SIZE_T - /* Compiler specific tests for systems where size_t is known to be less than - * 32 bits (some of these systems may no longer work because of the lack of - * 'far' support; see above.) - */ -# if (defined(__TURBOC__) && !defined(__FLAT__)) ||\ - (defined(_MSC_VER) && defined(MAXSEG_64K)) -# define PNG_SMALL_SIZE_T -# endif -#endif - -/* png_alloc_size_t is guaranteed to be no smaller than size_t, and no smaller - * than png_uint_32. Casts from size_t or png_uint_32 to png_alloc_size_t are - * not necessary; in fact, it is recommended not to use them at all, so that - * the compiler can complain when something turns out to be problematic. - * - * Casts in the other direction (from png_alloc_size_t to size_t or - * png_uint_32) should be explicitly applied; however, we do not expect to - * encounter practical situations that require such conversions. - * - * PNG_SMALL_SIZE_T must be defined if the maximum value of size_t is less than - * 4294967295 - i.e. less than the maximum value of png_uint_32. - */ -#ifdef PNG_SMALL_SIZE_T - typedef png_uint_32 png_alloc_size_t; -#else - typedef size_t png_alloc_size_t; -#endif - -/* Prior to 1.6.0 libpng offered limited support for Microsoft C compiler - * implementations of Intel CPU specific support of user-mode segmented address - * spaces, where 16-bit pointers address more than 65536 bytes of memory using - * separate 'segment' registers. The implementation requires two different - * types of pointer (only one of which includes the segment value.) - * - * If required this support is available in version 1.2 of libpng and may be - * available in versions through 1.5, although the correctness of the code has - * not been verified recently. - */ - -/* Typedef for floating-point numbers that are converted to fixed-point with a - * multiple of 100,000, e.g., gamma - */ -typedef png_int_32 png_fixed_point; - -/* Add typedefs for pointers */ -typedef void * png_voidp; -typedef const void * png_const_voidp; -typedef png_byte * png_bytep; -typedef const png_byte * png_const_bytep; -typedef png_uint_32 * png_uint_32p; -typedef const png_uint_32 * png_const_uint_32p; -typedef png_int_32 * png_int_32p; -typedef const png_int_32 * png_const_int_32p; -typedef png_uint_16 * png_uint_16p; -typedef const png_uint_16 * png_const_uint_16p; -typedef png_int_16 * png_int_16p; -typedef const png_int_16 * png_const_int_16p; -typedef char * png_charp; -typedef const char * png_const_charp; -typedef png_fixed_point * png_fixed_point_p; -typedef const png_fixed_point * png_const_fixed_point_p; -typedef size_t * png_size_tp; -typedef const size_t * png_const_size_tp; - -#ifdef PNG_STDIO_SUPPORTED -typedef FILE * png_FILE_p; -#endif - -#ifdef PNG_FLOATING_POINT_SUPPORTED -typedef double * png_doublep; -typedef const double * png_const_doublep; -#endif - -/* Pointers to pointers; i.e. arrays */ -typedef png_byte * * png_bytepp; -typedef png_uint_32 * * png_uint_32pp; -typedef png_int_32 * * png_int_32pp; -typedef png_uint_16 * * png_uint_16pp; -typedef png_int_16 * * png_int_16pp; -typedef const char * * png_const_charpp; -typedef char * * png_charpp; -typedef png_fixed_point * * png_fixed_point_pp; -#ifdef PNG_FLOATING_POINT_SUPPORTED -typedef double * * png_doublepp; -#endif - -/* Pointers to pointers to pointers; i.e., pointer to array */ -typedef char * * * png_charppp; - -#endif /* PNG_BUILDING_SYMBOL_TABLE */ - -#endif /* PNGCONF_H */ diff --git a/libs/include/libpng/pnglibconf.h b/libs/include/libpng/pnglibconf.h deleted file mode 100644 index 702aad8a..00000000 --- a/libs/include/libpng/pnglibconf.h +++ /dev/null @@ -1,219 +0,0 @@ -/* pnglibconf.h - library build configuration */ - -/* libpng version 1.6.37 */ - -/* Copyright (c) 2018-2019 Cosmin Truta */ -/* Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson */ - -/* This code is released under the libpng license. */ -/* For conditions of distribution and use, see the disclaimer */ -/* and license in png.h */ - -/* pnglibconf.h */ -/* Machine generated file: DO NOT EDIT */ -/* Derived from: scripts/pnglibconf.dfa */ -#ifndef PNGLCONF_H -#define PNGLCONF_H -/* options */ -#define PNG_16BIT_SUPPORTED -#define PNG_ALIGNED_MEMORY_SUPPORTED -/*#undef PNG_ARM_NEON_API_SUPPORTED*/ -/*#undef PNG_ARM_NEON_CHECK_SUPPORTED*/ -#define PNG_BENIGN_ERRORS_SUPPORTED -#define PNG_BENIGN_READ_ERRORS_SUPPORTED -/*#undef PNG_BENIGN_WRITE_ERRORS_SUPPORTED*/ -#define PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED -#define PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED -#define PNG_COLORSPACE_SUPPORTED -#define PNG_CONSOLE_IO_SUPPORTED -#define PNG_CONVERT_tIME_SUPPORTED -#define PNG_EASY_ACCESS_SUPPORTED -/*#undef PNG_ERROR_NUMBERS_SUPPORTED*/ -#define PNG_ERROR_TEXT_SUPPORTED -#define PNG_FIXED_POINT_SUPPORTED -#define PNG_FLOATING_ARITHMETIC_SUPPORTED -#define PNG_FLOATING_POINT_SUPPORTED -#define PNG_FORMAT_AFIRST_SUPPORTED -#define PNG_FORMAT_BGR_SUPPORTED -#define PNG_GAMMA_SUPPORTED -#define PNG_GET_PALETTE_MAX_SUPPORTED -#define PNG_HANDLE_AS_UNKNOWN_SUPPORTED -#define PNG_INCH_CONVERSIONS_SUPPORTED -#define PNG_INFO_IMAGE_SUPPORTED -#define PNG_IO_STATE_SUPPORTED -#define PNG_MNG_FEATURES_SUPPORTED -#define PNG_POINTER_INDEXING_SUPPORTED -/*#undef PNG_POWERPC_VSX_API_SUPPORTED*/ -/*#undef PNG_POWERPC_VSX_CHECK_SUPPORTED*/ -#define PNG_PROGRESSIVE_READ_SUPPORTED -#define PNG_READ_16BIT_SUPPORTED -#define PNG_READ_ALPHA_MODE_SUPPORTED -#define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED -#define PNG_READ_BACKGROUND_SUPPORTED -#define PNG_READ_BGR_SUPPORTED -#define PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED -#define PNG_READ_COMPOSITE_NODIV_SUPPORTED -#define PNG_READ_COMPRESSED_TEXT_SUPPORTED -#define PNG_READ_EXPAND_16_SUPPORTED -#define PNG_READ_EXPAND_SUPPORTED -#define PNG_READ_FILLER_SUPPORTED -#define PNG_READ_GAMMA_SUPPORTED -#define PNG_READ_GET_PALETTE_MAX_SUPPORTED -#define PNG_READ_GRAY_TO_RGB_SUPPORTED -#define PNG_READ_INTERLACING_SUPPORTED -#define PNG_READ_INT_FUNCTIONS_SUPPORTED -#define PNG_READ_INVERT_ALPHA_SUPPORTED -#define PNG_READ_INVERT_SUPPORTED -#define PNG_READ_OPT_PLTE_SUPPORTED -#define PNG_READ_PACKSWAP_SUPPORTED -#define PNG_READ_PACK_SUPPORTED -#define PNG_READ_QUANTIZE_SUPPORTED -#define PNG_READ_RGB_TO_GRAY_SUPPORTED -#define PNG_READ_SCALE_16_TO_8_SUPPORTED -#define PNG_READ_SHIFT_SUPPORTED -#define PNG_READ_STRIP_16_TO_8_SUPPORTED -#define PNG_READ_STRIP_ALPHA_SUPPORTED -#define PNG_READ_SUPPORTED -#define PNG_READ_SWAP_ALPHA_SUPPORTED -#define PNG_READ_SWAP_SUPPORTED -#define PNG_READ_TEXT_SUPPORTED -#define PNG_READ_TRANSFORMS_SUPPORTED -#define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_READ_USER_CHUNKS_SUPPORTED -#define PNG_READ_USER_TRANSFORM_SUPPORTED -#define PNG_READ_bKGD_SUPPORTED -#define PNG_READ_cHRM_SUPPORTED -#define PNG_READ_eXIf_SUPPORTED -#define PNG_READ_gAMA_SUPPORTED -#define PNG_READ_hIST_SUPPORTED -#define PNG_READ_iCCP_SUPPORTED -#define PNG_READ_iTXt_SUPPORTED -#define PNG_READ_oFFs_SUPPORTED -#define PNG_READ_pCAL_SUPPORTED -#define PNG_READ_pHYs_SUPPORTED -#define PNG_READ_sBIT_SUPPORTED -#define PNG_READ_sCAL_SUPPORTED -#define PNG_READ_sPLT_SUPPORTED -#define PNG_READ_sRGB_SUPPORTED -#define PNG_READ_tEXt_SUPPORTED -#define PNG_READ_tIME_SUPPORTED -#define PNG_READ_tRNS_SUPPORTED -#define PNG_READ_zTXt_SUPPORTED -#define PNG_SAVE_INT_32_SUPPORTED -#define PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_SEQUENTIAL_READ_SUPPORTED -#define PNG_SETJMP_SUPPORTED -#define PNG_SET_OPTION_SUPPORTED -#define PNG_SET_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_SET_USER_LIMITS_SUPPORTED -#define PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED -#define PNG_SIMPLIFIED_READ_BGR_SUPPORTED -#define PNG_SIMPLIFIED_READ_SUPPORTED -#define PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED -#define PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED -#define PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED -#define PNG_SIMPLIFIED_WRITE_SUPPORTED -#define PNG_STDIO_SUPPORTED -#define PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_TEXT_SUPPORTED -#define PNG_TIME_RFC1123_SUPPORTED -#define PNG_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_USER_CHUNKS_SUPPORTED -#define PNG_USER_LIMITS_SUPPORTED -#define PNG_USER_MEM_SUPPORTED -#define PNG_USER_TRANSFORM_INFO_SUPPORTED -#define PNG_USER_TRANSFORM_PTR_SUPPORTED -#define PNG_WARNINGS_SUPPORTED -#define PNG_WRITE_16BIT_SUPPORTED -#define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED -#define PNG_WRITE_BGR_SUPPORTED -#define PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED -#define PNG_WRITE_COMPRESSED_TEXT_SUPPORTED -#define PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED -#define PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED -#define PNG_WRITE_FILLER_SUPPORTED -#define PNG_WRITE_FILTER_SUPPORTED -#define PNG_WRITE_FLUSH_SUPPORTED -#define PNG_WRITE_GET_PALETTE_MAX_SUPPORTED -#define PNG_WRITE_INTERLACING_SUPPORTED -#define PNG_WRITE_INT_FUNCTIONS_SUPPORTED -#define PNG_WRITE_INVERT_ALPHA_SUPPORTED -#define PNG_WRITE_INVERT_SUPPORTED -#define PNG_WRITE_OPTIMIZE_CMF_SUPPORTED -#define PNG_WRITE_PACKSWAP_SUPPORTED -#define PNG_WRITE_PACK_SUPPORTED -#define PNG_WRITE_SHIFT_SUPPORTED -#define PNG_WRITE_SUPPORTED -#define PNG_WRITE_SWAP_ALPHA_SUPPORTED -#define PNG_WRITE_SWAP_SUPPORTED -#define PNG_WRITE_TEXT_SUPPORTED -#define PNG_WRITE_TRANSFORMS_SUPPORTED -#define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED -#define PNG_WRITE_USER_TRANSFORM_SUPPORTED -#define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED -#define PNG_WRITE_bKGD_SUPPORTED -#define PNG_WRITE_cHRM_SUPPORTED -#define PNG_WRITE_eXIf_SUPPORTED -#define PNG_WRITE_gAMA_SUPPORTED -#define PNG_WRITE_hIST_SUPPORTED -#define PNG_WRITE_iCCP_SUPPORTED -#define PNG_WRITE_iTXt_SUPPORTED -#define PNG_WRITE_oFFs_SUPPORTED -#define PNG_WRITE_pCAL_SUPPORTED -#define PNG_WRITE_pHYs_SUPPORTED -#define PNG_WRITE_sBIT_SUPPORTED -#define PNG_WRITE_sCAL_SUPPORTED -#define PNG_WRITE_sPLT_SUPPORTED -#define PNG_WRITE_sRGB_SUPPORTED -#define PNG_WRITE_tEXt_SUPPORTED -#define PNG_WRITE_tIME_SUPPORTED -#define PNG_WRITE_tRNS_SUPPORTED -#define PNG_WRITE_zTXt_SUPPORTED -#define PNG_bKGD_SUPPORTED -#define PNG_cHRM_SUPPORTED -#define PNG_eXIf_SUPPORTED -#define PNG_gAMA_SUPPORTED -#define PNG_hIST_SUPPORTED -#define PNG_iCCP_SUPPORTED -#define PNG_iTXt_SUPPORTED -#define PNG_oFFs_SUPPORTED -#define PNG_pCAL_SUPPORTED -#define PNG_pHYs_SUPPORTED -#define PNG_sBIT_SUPPORTED -#define PNG_sCAL_SUPPORTED -#define PNG_sPLT_SUPPORTED -#define PNG_sRGB_SUPPORTED -#define PNG_tEXt_SUPPORTED -#define PNG_tIME_SUPPORTED -#define PNG_tRNS_SUPPORTED -#define PNG_zTXt_SUPPORTED -/* end of options */ -/* settings */ -#define PNG_API_RULE 0 -#define PNG_DEFAULT_READ_MACROS 1 -#define PNG_GAMMA_THRESHOLD_FIXED 5000 -#define PNG_IDAT_READ_SIZE PNG_ZBUF_SIZE -#define PNG_INFLATE_BUF_SIZE 1024 -#define PNG_LINKAGE_API extern -#define PNG_LINKAGE_CALLBACK extern -#define PNG_LINKAGE_DATA extern -#define PNG_LINKAGE_FUNCTION extern -#define PNG_MAX_GAMMA_8 11 -#define PNG_QUANTIZE_BLUE_BITS 5 -#define PNG_QUANTIZE_GREEN_BITS 5 -#define PNG_QUANTIZE_RED_BITS 5 -#define PNG_TEXT_Z_DEFAULT_COMPRESSION (-1) -#define PNG_TEXT_Z_DEFAULT_STRATEGY 0 -#define PNG_USER_CHUNK_CACHE_MAX 1000 -#define PNG_USER_CHUNK_MALLOC_MAX 8000000 -#define PNG_USER_HEIGHT_MAX 1000000 -#define PNG_USER_WIDTH_MAX 1000000 -#define PNG_ZBUF_SIZE 8192 -#define PNG_ZLIB_VERNUM 0x1280 -#define PNG_Z_DEFAULT_COMPRESSION (-1) -#define PNG_Z_DEFAULT_NOFILTER_STRATEGY 0 -#define PNG_Z_DEFAULT_STRATEGY 1 -#define PNG_sCAL_PRECISION 5 -#define PNG_sRGB_PROFILE_CHECKS 2 -/* end of settings */ -#endif /* PNGLCONF_H */ diff --git a/libs/include/mpg123.h b/libs/include/mpg123.h deleted file mode 100644 index c7f8ecc8..00000000 --- a/libs/include/mpg123.h +++ /dev/null @@ -1,2001 +0,0 @@ -/* - libmpg123: MPEG Audio Decoder library (version 1.28.2) - - copyright 1995-2015 by the mpg123 project - free software under the terms of the LGPL 2.1 - see COPYING and AUTHORS files in distribution or http://mpg123.org -*/ - -#ifndef MPG123_LIB_H -#define MPG123_LIB_H - -#include - -/** \file mpg123.h The header file for the libmpg123 MPEG Audio decoder */ - -/** A macro to check at compile time which set of API functions to expect. - * This should be incremented at least each time a new symbol is added - * to the header. - */ -#ifndef MPG123_API_VERSION -#define MPG123_API_VERSION 46 -#endif - -#ifndef MPG123_EXPORT -/** Defines needed for MS Visual Studio(tm) DLL builds. - * Every public function must be prefixed with MPG123_EXPORT. When building - * the DLL ensure to define BUILD_MPG123_DLL. This makes the function accessible - * for clients and includes it in the import library which is created together - * with the DLL. When consuming the DLL ensure to define LINK_MPG123_DLL which - * imports the functions from the DLL. - */ -#ifdef BUILD_MPG123_DLL -/* The dll exports. */ -#define MPG123_EXPORT __declspec(dllexport) -#else -#ifdef LINK_MPG123_DLL -/* The exe imports. */ -#define MPG123_EXPORT __declspec(dllimport) -#else -/* Nothing on normal/UNIX builds */ -#define MPG123_EXPORT -#endif -#endif -#endif - -/** Earlier versions of libmpg123 put enums into public API calls, - * thich is not exactly safe. There are ABI rules, but you can use - * compiler switches to change the sizes of enums. It is safer not - * to have them in API calls. Thus, the default is to remap calls and - * structs to variants that use plain ints. Define MPG123_ENUM_API to - * prevent that remapping. - * - * You might want to define this to increase the chance of your binary - * working with an older version of the library. But if that is your goal, - * you should better build with an older version to begin with. - */ -#ifndef MPG123_ENUM_API - -#define mpg123_param mpg123_param2 -#define mpg123_getparam mpg123_getparam2 -#define mpg123_feature mpg123_feature2 -#define mpg123_eq mpg123_eq2 -#define mpg123_geteq mpg123_geteq2 -#define mpg123_frameinfo mpg123_frameinfo2 -#define mpg123_info mpg123_info2 -#define mpg123_getstate mpg123_getstate2 -#define mpg123_enc_from_id3 mpg123_enc_from_id3_2 -#define mpg123_store_utf8 mpg123_store_utf8_2 -#define mpg123_par mpg123_par2 -#define mpg123_getpar mpg123_getpar2 - -#endif - -/* You can use this file directly, avoiding the autoconf replacements. - Might have to set MPG123_NO_LARGENAME, too, in case you have - _FILE_OFFSET_BITS defined where it does not make sense. */ -#ifndef MPG123_NO_CONFIGURE - -#include -#include - -/* A little hack to help MSVC not having ssize_t. */ -#ifdef _MSC_VER -#include -typedef ptrdiff_t mpg123_ssize_t; -#else -typedef ssize_t mpg123_ssize_t; -#endif - -/* You can always enforce largefile hackery by setting MPG123_LARGESUFFIX. */ -/* Otherwise, this header disables it if the build system decided so. */ -#if !defined(MPG123_LARGESUFFIX) && 0 -#ifndef MPG123_NO_LARGENAME -#define MPG123_NO_LARGENAME -#endif -#endif - -#endif /* MPG123_NO_CONFIGURE */ - -/* Simplified large file handling. - I used to have a check here that prevents building for a library with conflicting large file setup - (application that uses 32 bit offsets with library that uses 64 bits). - While that was perfectly fine in an environment where there is one incarnation of the library, - it hurt GNU/Linux and Solaris systems with multilib where the distribution fails to provide the - correct header matching the 32 bit library (where large files need explicit support) or - the 64 bit library (where there is no distinction). - - New approach: When the app defines _FILE_OFFSET_BITS, it wants non-default large file support, - and thus functions with added suffix (mpg123_open_64). - Any mismatch will be caught at link time because of the _FILE_OFFSET_BITS setting used when - building libmpg123. Plus, there's dual mode large file support in mpg123 since 1.12 now. - Link failure is not the expected outcome of any half-sane usage anymore. - - More complication: What about client code defining _LARGEFILE64_SOURCE? It might want direct access to the _64 functions, along with the ones without suffix. Well, that's possible now via defining MPG123_NO_LARGENAME and MPG123_LARGESUFFIX, respectively, for disabling or enforcing the suffix names. -*/ - -/* - Now, the renaming of large file aware functions. - By default, it appends underscore _FILE_OFFSET_BITS (so, mpg123_seek_64 for mpg123_seek), if _FILE_OFFSET_BITS is defined. You can force a different suffix via MPG123_LARGESUFFIX (that must include the underscore), or you can just disable the whole mess by defining MPG123_NO_LARGENAME. -*/ -#if (!defined MPG123_NO_LARGENAME) && ((defined _FILE_OFFSET_BITS) || (defined MPG123_LARGESUFFIX)) - -/* Need some trickery to concatenate the value(s) of the given macro(s). */ -#define MPG123_MACROCAT_REALLY(a, b) a ## b -#define MPG123_MACROCAT(a, b) MPG123_MACROCAT_REALLY(a, b) -#ifndef MPG123_LARGESUFFIX -#define MPG123_LARGESUFFIX MPG123_MACROCAT(_, _FILE_OFFSET_BITS) -#endif -#define MPG123_LARGENAME(func) MPG123_MACROCAT(func, MPG123_LARGESUFFIX) - -#define mpg123_open_fixed MPG123_LARGENAME(mpg123_open_fixed) -#define mpg123_open MPG123_LARGENAME(mpg123_open) -#define mpg123_open_fd MPG123_LARGENAME(mpg123_open_fd) -#define mpg123_open_handle MPG123_LARGENAME(mpg123_open_handle) -#define mpg123_framebyframe_decode MPG123_LARGENAME(mpg123_framebyframe_decode) -#define mpg123_decode_frame MPG123_LARGENAME(mpg123_decode_frame) -#define mpg123_tell MPG123_LARGENAME(mpg123_tell) -#define mpg123_tellframe MPG123_LARGENAME(mpg123_tellframe) -#define mpg123_tell_stream MPG123_LARGENAME(mpg123_tell_stream) -#define mpg123_seek MPG123_LARGENAME(mpg123_seek) -#define mpg123_feedseek MPG123_LARGENAME(mpg123_feedseek) -#define mpg123_seek_frame MPG123_LARGENAME(mpg123_seek_frame) -#define mpg123_timeframe MPG123_LARGENAME(mpg123_timeframe) -#define mpg123_index MPG123_LARGENAME(mpg123_index) -#define mpg123_set_index MPG123_LARGENAME(mpg123_set_index) -#define mpg123_position MPG123_LARGENAME(mpg123_position) -#define mpg123_length MPG123_LARGENAME(mpg123_length) -#define mpg123_framelength MPG123_LARGENAME(mpg123_framelength) -#define mpg123_set_filesize MPG123_LARGENAME(mpg123_set_filesize) -#define mpg123_replace_reader MPG123_LARGENAME(mpg123_replace_reader) -#define mpg123_replace_reader_handle MPG123_LARGENAME(mpg123_replace_reader_handle) -#define mpg123_framepos MPG123_LARGENAME(mpg123_framepos) - -#endif /* largefile hackery */ - -#ifdef __cplusplus -extern "C" { -#endif - -/** \defgroup mpg123_init mpg123 library and handle setup - * - * Functions to initialise and shutdown the mpg123 library and handles. - * The parameters of handles have workable defaults, you only have to tune them when you want to tune something;-) - * Tip: Use a RVA setting... - * - * @{ - */ - -/** Opaque structure for the libmpg123 decoder handle. */ -struct mpg123_handle_struct; - -/** Opaque structure for the libmpg123 decoder handle. - * Most functions take a pointer to a mpg123_handle as first argument and operate on its data in an object-oriented manner. - */ -typedef struct mpg123_handle_struct mpg123_handle; - -/** Useless no-op that used to do initialization work. - * - * For API version before 46 (mpg123 1.27.0), you had to ensure to have - * this called once before creating a handle. To be pure, this had to - * happen in a single-threaded context, too (while in practice, there was no - * harm done possibly racing to compute the same numbers again). - * - * Now this function really does nothing anymore. The only reason to call - * it is to be compatible with old versions of the library that still require - * it. - * - * \return MPG123_OK if successful, otherwise an error number. - */ -MPG123_EXPORT int mpg123_init(void); - -/** Superfluous Function to close down the mpg123 library. - * This was created with the thought that there sometime will be cleanup code - * to be run after library use. This never materialized. You can forget about - * this function and it is only here for old programs that do call it. - */ -MPG123_EXPORT void mpg123_exit(void); - -/** Create a handle with optional choice of decoder (named by a string, see mpg123_decoders() or mpg123_supported_decoders()). - * and optional retrieval of an error code to feed to mpg123_plain_strerror(). - * Optional means: Any of or both the parameters may be NULL. - * - * \param decoder optional choice of decoder variant (NULL for default) - * \param error optional address to store error codes - * \return Non-NULL pointer to fresh handle when successful. - */ -MPG123_EXPORT mpg123_handle *mpg123_new(const char* decoder, int *error); - -/** Delete handle, mh is either a valid mpg123 handle or NULL. - * \param mh handle - */ -MPG123_EXPORT void mpg123_delete(mpg123_handle *mh); - -/** Free plain memory allocated within libmpg123. - * This is for library users that are not sure to use the same underlying - * memory allocator as libmpg123. It is just a wrapper over free() in - * the underlying C library. - */ -MPG123_EXPORT void mpg123_free(void *ptr); - -/** Enumeration of the parameters types that it is possible to set/get. */ -enum mpg123_parms -{ - MPG123_VERBOSE = 0, /**< set verbosity value for enabling messages to stderr, >= 0 makes sense (integer) */ - MPG123_FLAGS, /**< set all flags, p.ex val = MPG123_GAPLESS|MPG123_MONO_MIX (integer) */ - MPG123_ADD_FLAGS, /**< add some flags (integer) */ - MPG123_FORCE_RATE, /**< when value > 0, force output rate to that value (integer) */ - MPG123_DOWN_SAMPLE, /**< 0=native rate, 1=half rate, 2=quarter rate (integer) */ - MPG123_RVA, /**< one of the RVA choices above (integer) */ - MPG123_DOWNSPEED, /**< play a frame N times (integer) */ - MPG123_UPSPEED, /**< play every Nth frame (integer) */ - MPG123_START_FRAME, /**< start with this frame (skip frames before that, integer) */ - MPG123_DECODE_FRAMES, /**< decode only this number of frames (integer) */ - MPG123_ICY_INTERVAL, /**< Stream contains ICY metadata with this interval (integer). - Make sure to set this _before_ opening a stream.*/ - MPG123_OUTSCALE, /**< the scale for output samples (amplitude - integer or float according to mpg123 output format, normally integer) */ - MPG123_TIMEOUT, /**< timeout for reading from a stream (not supported on win32, integer) */ - MPG123_REMOVE_FLAGS, /**< remove some flags (inverse of MPG123_ADD_FLAGS, integer) */ - MPG123_RESYNC_LIMIT, /**< Try resync on frame parsing for that many bytes or until end of stream (<0 ... integer). This can enlarge the limit for skipping junk on beginning, too (but not reduce it). */ - MPG123_INDEX_SIZE /**< Set the frame index size (if supported). Values <0 mean that the index is allowed to grow dynamically in these steps (in positive direction, of course) -- Use this when you really want a full index with every individual frame. */ - ,MPG123_PREFRAMES /**< Decode/ignore that many frames in advance for layer 3. This is needed to fill bit reservoir after seeking, for example (but also at least one frame in advance is needed to have all "normal" data for layer 3). Give a positive integer value, please.*/ - ,MPG123_FEEDPOOL /**< For feeder mode, keep that many buffers in a pool to avoid frequent malloc/free. The pool is allocated on mpg123_open_feed(). If you change this parameter afterwards, you can trigger growth and shrinkage during decoding. The default value could change any time. If you care about this, then set it. (integer) */ - ,MPG123_FEEDBUFFER /**< Minimal size of one internal feeder buffer, again, the default value is subject to change. (integer) */ - ,MPG123_FREEFORMAT_SIZE /**< Tell the parser a free-format frame size to - * avoid read-ahead to get it. A value of -1 (default) means that the parser - * will determine it. The parameter value is applied during decoder setup - * for a freshly opened stream only. - */ -}; - -/** Flag bits for MPG123_FLAGS, use the usual binary or to combine. */ -enum mpg123_param_flags -{ - MPG123_FORCE_MONO = 0x7 /**< 0111 Force some mono mode: This is a test bitmask for seeing if any mono forcing is active. */ - ,MPG123_MONO_LEFT = 0x1 /**< 0001 Force playback of left channel only. */ - ,MPG123_MONO_RIGHT = 0x2 /**< 0010 Force playback of right channel only. */ - ,MPG123_MONO_MIX = 0x4 /**< 0100 Force playback of mixed mono. */ - ,MPG123_FORCE_STEREO = 0x8 /**< 1000 Force stereo output. */ - ,MPG123_FORCE_8BIT = 0x10 /**< 00010000 Force 8bit formats. */ - ,MPG123_QUIET = 0x20 /**< 00100000 Suppress any printouts (overrules verbose). */ - ,MPG123_GAPLESS = 0x40 /**< 01000000 Enable gapless decoding (default on if libmpg123 has support). */ - ,MPG123_NO_RESYNC = 0x80 /**< 10000000 Disable resync stream after error. */ - ,MPG123_SEEKBUFFER = 0x100 /**< 000100000000 Enable small buffer on non-seekable streams to allow some peek-ahead (for better MPEG sync). */ - ,MPG123_FUZZY = 0x200 /**< 001000000000 Enable fuzzy seeks (guessing byte offsets or using approximate seek points from Xing TOC) */ - ,MPG123_FORCE_FLOAT = 0x400 /**< 010000000000 Force floating point output (32 or 64 bits depends on mpg123 internal precision). */ - ,MPG123_PLAIN_ID3TEXT = 0x800 /**< 100000000000 Do not translate ID3 text data to UTF-8. ID3 strings will contain the raw text data, with the first byte containing the ID3 encoding code. */ - ,MPG123_IGNORE_STREAMLENGTH = 0x1000 /**< 1000000000000 Ignore any stream length information contained in the stream, which can be contained in a 'TLEN' frame of an ID3v2 tag or a Xing tag */ - ,MPG123_SKIP_ID3V2 = 0x2000 /**< 10 0000 0000 0000 Do not parse ID3v2 tags, just skip them. */ - ,MPG123_IGNORE_INFOFRAME = 0x4000 /**< 100 0000 0000 0000 Do not parse the LAME/Xing info frame, treat it as normal MPEG data. */ - ,MPG123_AUTO_RESAMPLE = 0x8000 /**< 1000 0000 0000 0000 Allow automatic internal resampling of any kind (default on if supported). Especially when going lowlevel with replacing output buffer, you might want to unset this flag. Setting MPG123_DOWNSAMPLE or MPG123_FORCE_RATE will override this. */ - ,MPG123_PICTURE = 0x10000 /**< 17th bit: Enable storage of pictures from tags (ID3v2 APIC). */ - ,MPG123_NO_PEEK_END = 0x20000 /**< 18th bit: Do not seek to the end of - * the stream in order to probe - * the stream length and search for the id3v1 field. This also means - * the file size is unknown unless set using mpg123_set_filesize() and - * the stream is assumed as non-seekable unless overridden. - */ - ,MPG123_FORCE_SEEKABLE = 0x40000 /**< 19th bit: Force the stream to be seekable. */ - ,MPG123_STORE_RAW_ID3 = 0x80000 /**< store raw ID3 data (even if skipping) */ - ,MPG123_FORCE_ENDIAN = 0x100000 /**< Enforce endianess of output samples. - * This is not reflected in the format codes. If this flag is set along with - * MPG123_BIG_ENDIAN, MPG123_ENC_SIGNED16 means s16be, without - * MPG123_BIG_ENDIAN, it means s16le. Normal operation without - * MPG123_FORCE_ENDIAN produces output in native byte order. - */ - ,MPG123_BIG_ENDIAN = 0x200000 /**< Choose big endian instead of little. */ - ,MPG123_NO_READAHEAD = 0x400000 /**< Disable read-ahead in parser. If - * you know you provide full frames to the feeder API, this enables - * decoder output from the first one on, instead of having to wait for - * the next frame to confirm that the stream is healthy. It also disables - * free format support unless you provide a frame size using - * MPG123_FREEFORMAT_SIZE. - */ - ,MPG123_FLOAT_FALLBACK = 0x800000 /**< Consider floating point output encoding only after - * trying other (possibly downsampled) rates and encodings first. This is to - * support efficient playback where floating point output is only configured for - * an external resampler, bypassing that resampler when the desired rate can - * be produced directly. This is enabled by default to be closer to older versions - * of libmpg123 which did not enable float automatically at all. If disabled, - * float is considered after the 16 bit default and higher-bit integer encodings - * for any rate. */ - ,MPG123_NO_FRANKENSTEIN = 0x1000000 /**< Disable support for Frankenstein streams - * (different MPEG streams stiched together). Do not accept serious change of MPEG - * header inside a single stream. With this flag, the audio output format cannot - * change during decoding unless you open a new stream. This also stops decoding - * after an announced end of stream (Info header contained a number of frames - * and this number has been reached). This makes your MP3 files behave more like - * ordinary media files with defined structure, rather than stream dumps with - * some sugar. */ -}; - -/** choices for MPG123_RVA */ -enum mpg123_param_rva -{ - MPG123_RVA_OFF = 0 /**< RVA disabled (default). */ - ,MPG123_RVA_MIX = 1 /**< Use mix/track/radio gain. */ - ,MPG123_RVA_ALBUM = 2 /**< Use album/audiophile gain */ - ,MPG123_RVA_MAX = MPG123_RVA_ALBUM /**< The maximum RVA code, may increase in future. */ -}; - -#ifdef MPG123_ENUM_API -/** Set a specific parameter on a handle. - * - * Note that this name is mapped to mpg123_param2() instead unless - * MPG123_ENUM_API is defined. - * - * \param mh handle - * \param type parameter choice - * \param value integer value - * \param fvalue floating point value - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_param( mpg123_handle *mh -, enum mpg123_parms type, long value, double fvalue ); -#endif - -/** Set a specific parameter on a handle. No enums. - * - * This is actually called instead of mpg123_param() - * unless MPG123_ENUM_API is defined. - * - * \param mh handle - * \param type parameter choice (from enum #mpg123_parms) - * \param value integer value - * \param fvalue floating point value - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_param2( mpg123_handle *mh -, int type, long value, double fvalue ); - -#ifdef MPG123_ENUM_API -/** Get a specific parameter from a handle. - * - * Note that this name is mapped to mpg123_getparam2() instead unless - * MPG123_ENUM_API is defined. - * - * \param mh handle - * \param type parameter choice - * \param value integer value return address - * \param fvalue floating point value return address - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_getparam( mpg123_handle *mh -, enum mpg123_parms type, long *value, double *fvalue ); -#endif - -/** Get a specific parameter from a handle. No enums. - * - * This is actually called instead of mpg123_getparam() unless MPG123_ENUM_API - * is defined. - * - * \param mh handle - * \param type parameter choice (from enum #mpg123_parms) - * \param value integer value return address - * \param fvalue floating point value return address - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_getparam2( mpg123_handle *mh -, int type, long *value, double *fvalue ); - -/** Feature set available for query with mpg123_feature. */ -enum mpg123_feature_set -{ - MPG123_FEATURE_ABI_UTF8OPEN = 0 /**< mpg123 expects path names to be given in UTF-8 encoding instead of plain native. */ - ,MPG123_FEATURE_OUTPUT_8BIT /**< 8bit output */ - ,MPG123_FEATURE_OUTPUT_16BIT /**< 16bit output */ - ,MPG123_FEATURE_OUTPUT_32BIT /**< 32bit output */ - ,MPG123_FEATURE_INDEX /**< support for building a frame index for accurate seeking */ - ,MPG123_FEATURE_PARSE_ID3V2 /**< id3v2 parsing */ - ,MPG123_FEATURE_DECODE_LAYER1 /**< mpeg layer-1 decoder enabled */ - ,MPG123_FEATURE_DECODE_LAYER2 /**< mpeg layer-2 decoder enabled */ - ,MPG123_FEATURE_DECODE_LAYER3 /**< mpeg layer-3 decoder enabled */ - ,MPG123_FEATURE_DECODE_ACCURATE /**< accurate decoder rounding */ - ,MPG123_FEATURE_DECODE_DOWNSAMPLE /**< downsample (sample omit) */ - ,MPG123_FEATURE_DECODE_NTOM /**< flexible rate decoding */ - ,MPG123_FEATURE_PARSE_ICY /**< ICY support */ - ,MPG123_FEATURE_TIMEOUT_READ /**< Reader with timeout (network). */ - ,MPG123_FEATURE_EQUALIZER /**< tunable equalizer */ - ,MPG123_FEATURE_MOREINFO /**< more info extraction (for frame analyzer) */ - ,MPG123_FEATURE_OUTPUT_FLOAT32 /**< 32 bit float output */ - ,MPG123_FEATURE_OUTPUT_FLOAT64 /**< 64 bit float output (usually never) */ -}; - -#ifdef MPG123_ENUM_API -/** Query libmpg123 features. - * - * Note that this name is mapped to mpg123_feature2() instead unless - * MPG123_ENUM_API is defined. - * - * \param key feature selection - * \return 1 for success, 0 for unimplemented functions - */ -MPG123_EXPORT int mpg123_feature(const enum mpg123_feature_set key); -#endif - -/** Query libmpg123 features. No enums. - * - * This is actually called instead of mpg123_feature() unless MPG123_ENUM_API - * is defined. - * - * \param key feature selection (from enum #mpg123_feature_set) - * \return 1 for success, 0 for unimplemented functions - */ -MPG123_EXPORT int mpg123_feature2(int key); - -/** @} */ - - -/** \defgroup mpg123_error mpg123 error handling - * - * Functions to get text version of the error numbers and an enumeration - * of the error codes returned by libmpg123. - * - * Most functions operating on a mpg123_handle simply return MPG123_OK (0) - * on success and MPG123_ERR (-1) on failure, setting the internal error - * variable of the handle to the specific error code. If there was not a valid - * (non-NULL) handle provided to a function operating on one, MPG123_BAD_HANDLE - * may be returned if this can not be confused with a valid positive return - * value. - * Meaning: A function expected to return positive integers on success will - * always indicate error or a special condition by returning a negative one. - * - * Decoding/seek functions may also return message codes MPG123_DONE, - * MPG123_NEW_FORMAT and MPG123_NEED_MORE (all negative, see below on how to - * react). Note that calls to those can be nested, so generally watch out - * for these codes after initial handle setup. - * Especially any function that needs information about the current stream - * to work will try to at least parse the beginning if that did not happen - * yet. - * - * On a function that is supposed to return MPG123_OK on success and - * MPG123_ERR on failure, make sure you check for != MPG123_OK, not - * == MPG123_ERR, as the error code could get more specific in future, - * or there is just a special message from a decoding routine as indicated - * above. - * - * @{ - */ - -/** Enumeration of the message and error codes and returned by libmpg123 functions. */ -enum mpg123_errors -{ - MPG123_DONE=-12, /**< Message: Track ended. Stop decoding. */ - MPG123_NEW_FORMAT=-11, /**< Message: Output format will be different on next call. Note that some libmpg123 versions between 1.4.3 and 1.8.0 insist on you calling mpg123_getformat() after getting this message code. Newer verisons behave like advertised: You have the chance to call mpg123_getformat(), but you can also just continue decoding and get your data. */ - MPG123_NEED_MORE=-10, /**< Message: For feed reader: "Feed me more!" (call mpg123_feed() or mpg123_decode() with some new input data). */ - MPG123_ERR=-1, /**< Generic Error */ - MPG123_OK=0, /**< Success */ - MPG123_BAD_OUTFORMAT, /**< Unable to set up output format! */ - MPG123_BAD_CHANNEL, /**< Invalid channel number specified. */ - MPG123_BAD_RATE, /**< Invalid sample rate specified. */ - MPG123_ERR_16TO8TABLE, /**< Unable to allocate memory for 16 to 8 converter table! */ - MPG123_BAD_PARAM, /**< Bad parameter id! */ - MPG123_BAD_BUFFER, /**< Bad buffer given -- invalid pointer or too small size. */ - MPG123_OUT_OF_MEM, /**< Out of memory -- some malloc() failed. */ - MPG123_NOT_INITIALIZED, /**< You didn't initialize the library! */ - MPG123_BAD_DECODER, /**< Invalid decoder choice. */ - MPG123_BAD_HANDLE, /**< Invalid mpg123 handle. */ - MPG123_NO_BUFFERS, /**< Unable to initialize frame buffers (out of memory?). */ - MPG123_BAD_RVA, /**< Invalid RVA mode. */ - MPG123_NO_GAPLESS, /**< This build doesn't support gapless decoding. */ - MPG123_NO_SPACE, /**< Not enough buffer space. */ - MPG123_BAD_TYPES, /**< Incompatible numeric data types. */ - MPG123_BAD_BAND, /**< Bad equalizer band. */ - MPG123_ERR_NULL, /**< Null pointer given where valid storage address needed. */ - MPG123_ERR_READER, /**< Error reading the stream. */ - MPG123_NO_SEEK_FROM_END,/**< Cannot seek from end (end is not known). */ - MPG123_BAD_WHENCE, /**< Invalid 'whence' for seek function.*/ - MPG123_NO_TIMEOUT, /**< Build does not support stream timeouts. */ - MPG123_BAD_FILE, /**< File access error. */ - MPG123_NO_SEEK, /**< Seek not supported by stream. */ - MPG123_NO_READER, /**< No stream opened. */ - MPG123_BAD_PARS, /**< Bad parameter handle. */ - MPG123_BAD_INDEX_PAR, /**< Bad parameters to mpg123_index() and mpg123_set_index() */ - MPG123_OUT_OF_SYNC, /**< Lost track in bytestream and did not try to resync. */ - MPG123_RESYNC_FAIL, /**< Resync failed to find valid MPEG data. */ - MPG123_NO_8BIT, /**< No 8bit encoding possible. */ - MPG123_BAD_ALIGN, /**< Stack aligmnent error */ - MPG123_NULL_BUFFER, /**< NULL input buffer with non-zero size... */ - MPG123_NO_RELSEEK, /**< Relative seek not possible (screwed up file offset) */ - MPG123_NULL_POINTER, /**< You gave a null pointer somewhere where you shouldn't have. */ - MPG123_BAD_KEY, /**< Bad key value given. */ - MPG123_NO_INDEX, /**< No frame index in this build. */ - MPG123_INDEX_FAIL, /**< Something with frame index went wrong. */ - MPG123_BAD_DECODER_SETUP, /**< Something prevents a proper decoder setup */ - MPG123_MISSING_FEATURE /**< This feature has not been built into libmpg123. */ - ,MPG123_BAD_VALUE /**< A bad value has been given, somewhere. */ - ,MPG123_LSEEK_FAILED /**< Low-level seek failed. */ - ,MPG123_BAD_CUSTOM_IO /**< Custom I/O not prepared. */ - ,MPG123_LFS_OVERFLOW /**< Offset value overflow during translation of large file API calls -- your client program cannot handle that large file. */ - ,MPG123_INT_OVERFLOW /**< Some integer overflow. */ - ,MPG123_BAD_FLOAT /**< Floating-point computations work not as expected. */ -}; - -/** Look up error strings given integer code. - * \param errcode integer error code - * \return string describing what that error error code means - */ -MPG123_EXPORT const char* mpg123_plain_strerror(int errcode); - -/** Give string describing what error has occured in the context of handle mh. - * When a function operating on an mpg123 handle returns MPG123_ERR, you should check for the actual reason via - * char *errmsg = mpg123_strerror(mh) - * This function will catch mh == NULL and return the message for MPG123_BAD_HANDLE. - * \param mh handle - * \return error message - */ -MPG123_EXPORT const char* mpg123_strerror(mpg123_handle *mh); - -/** Return the plain errcode intead of a string. - * \param mh handle - * \return error code recorded in handle or MPG123_BAD_HANDLE - */ -MPG123_EXPORT int mpg123_errcode(mpg123_handle *mh); - -/** @} */ - - -/** \defgroup mpg123_decoder mpg123 decoder selection - * - * Functions to list and select the available decoders. - * Perhaps the most prominent feature of mpg123: You have several (optimized) decoders to choose from (on x86 and PPC (MacOS) systems, that is). - * - * @{ - */ - -/** Get available decoder list. - * \return NULL-terminated array of generally available decoder names (plain 8bit ASCII) - */ -MPG123_EXPORT const char **mpg123_decoders(void); - -/** Get supported decoder list. - * - * This possibly writes to static storage in the library, so avoid - * calling concurrently, please. - * - * \return NULL-terminated array of the decoders supported by the CPU (plain 8bit ASCII) - */ -MPG123_EXPORT const char **mpg123_supported_decoders(void); - -/** Set the active decoder. - * \param mh handle - * \param decoder_name name of decoder - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_decoder(mpg123_handle *mh, const char* decoder_name); - -/** Get the currently active decoder name. - * The active decoder engine can vary depening on output constraints, - * mostly non-resampling, integer output is accelerated via 3DNow & Co. but for - * other modes a fallback engine kicks in. - * Note that this can return a decoder that is only active in the hidden and not - * available as decoder choice from the outside. - * \param mh handle - * \return The decoder name or NULL on error. - */ -MPG123_EXPORT const char* mpg123_current_decoder(mpg123_handle *mh); - -/** @} */ - - -/** \defgroup mpg123_output mpg123 output audio format - * - * Functions to get and select the format of the decoded audio. - * - * Before you dive in, please be warned that you might get confused by this. - * This seems to happen a lot, therefore I am trying to explain in advance. - * If you do feel confused and just want to decode your normal MPEG audio files that - * don't alter properties in the middle, just use mpg123_open_fixed() with a fixed encoding - * and channel count and forget about a matrix of audio formats. If you want to get funky, - * read ahead ... - * - * The mpg123 library decides what output format to use when encountering the first frame in a stream, or actually any frame that is still valid but differs from the frames before in the prompted output format. At such a deciding point, an internal table of allowed encodings, sampling rates and channel setups is consulted. According to this table, an output format is chosen and the decoding engine set up accordingly (including optimized routines for different output formats). This might seem unusual but it just follows from the non-existence of "MPEG audio files" with defined overall properties. There are streams, streams are concatenations of (semi) independent frames. We store streams on disk and call them "MPEG audio files", but that does not change their nature as the decoder is concerned (the LAME/Xing header for gapless decoding makes things interesting again). - * - * To get to the point: What you do with mpg123_format() and friends is to fill the internal table of allowed formats before it is used. That includes removing support for some formats or adding your forced sample rate (see MPG123_FORCE_RATE) that will be used with the crude internal resampler. Also keep in mind that the sample encoding is just a question of choice -- the MPEG frames do only indicate their native sampling rate and channel count. If you want to decode to integer or float samples, 8 or 16 bit ... that is your decision. In a "clean" world, libmpg123 would always decode to 32 bit float and let you handle any sample conversion. But there are optimized routines that work faster by directly decoding to the desired encoding / accuracy. We prefer efficiency over conceptual tidyness. - * - * People often start out thinking that mpg123_format() should change the actual decoding format on the fly. That is wrong. It only has effect on the next natural change of output format, when libmpg123 will consult its format table again. To make life easier, you might want to call mpg123_format_none() before any thing else and then just allow one desired encoding and a limited set of sample rates / channel choices that you actually intend to deal with. You can force libmpg123 to decode everything to 44100 KHz, stereo, 16 bit integer ... it will duplicate mono channels and even do resampling if needed (unless that feature is disabled in the build, same with some encodings). But I have to stress that the resampling of libmpg123 is very crude and doesn't even contain any kind of "proper" interpolation. - * - * In any case, watch out for MPG123_NEW_FORMAT as return message from decoding routines and call mpg123_getformat() to get the currently active output format. - * - * @{ - */ - -/** They can be combined into one number (3) to indicate mono and stereo... */ -enum mpg123_channelcount -{ - MPG123_MONO = 1 /**< mono */ - ,MPG123_STEREO = 2 /**< stereo */ -}; - -/** An array of supported standard sample rates - * These are possible native sample rates of MPEG audio files. - * You can still force mpg123 to resample to a different one, but by - * default you will only get audio in one of these samplings. - * This list is in ascending order. - * \param list Store a pointer to the sample rates array there. - * \param number Store the number of sample rates there. */ -MPG123_EXPORT void mpg123_rates(const long **list, size_t *number); - -/** An array of supported audio encodings. - * An audio encoding is one of the fully qualified members of mpg123_enc_enum (MPG123_ENC_SIGNED_16, not MPG123_SIGNED). - * \param list Store a pointer to the encodings array there. - * \param number Store the number of encodings there. */ -MPG123_EXPORT void mpg123_encodings(const int **list, size_t *number); - -/** Return the size (in bytes) of one mono sample of the named encoding. - * \param encoding The encoding value to analyze. - * \return positive size of encoding in bytes, 0 on invalid encoding. */ -MPG123_EXPORT int mpg123_encsize(int encoding); - -/** Configure a mpg123 handle to accept no output format at all, - * use before specifying supported formats with mpg123_format - * \param mh handle - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_format_none(mpg123_handle *mh); - -/** Configure mpg123 handle to accept all formats - * (also any custom rate you may set) -- this is default. - * \param mh handle - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_format_all(mpg123_handle *mh); - -/** Set the audio format support of a mpg123_handle in detail: - * \param mh handle - * \param rate The sample rate value (in Hertz). - * \param channels A combination of MPG123_STEREO and MPG123_MONO. - * \param encodings A combination of accepted encodings for rate and channels, p.ex MPG123_ENC_SIGNED16 | MPG123_ENC_ULAW_8 (or 0 for no support). Please note that some encodings may not be supported in the library build and thus will be ignored here. - * \return MPG123_OK on success, MPG123_ERR if there was an error. */ -MPG123_EXPORT int mpg123_format( mpg123_handle *mh -, long rate, int channels, int encodings ); - -/** Set the audio format support of a mpg123_handle in detail: - * \param mh handle - * \param rate The sample rate value (in Hertz). Special value 0 means - * all rates (the reason for this variant of mpg123_format()). - * \param channels A combination of MPG123_STEREO and MPG123_MONO. - * \param encodings A combination of accepted encodings for rate and channels, - * p.ex MPG123_ENC_SIGNED16 | MPG123_ENC_ULAW_8 (or 0 for no support). - * Please note that some encodings may not be supported in the library build - * and thus will be ignored here. - * \return MPG123_OK on success, MPG123_ERR if there was an error. */ -MPG123_EXPORT int mpg123_format2( mpg123_handle *mh -, long rate, int channels, int encodings ); - -/** Check to see if a specific format at a specific rate is supported - * by mpg123_handle. - * \param mh handle - * \param rate sampling rate - * \param encoding encoding - * \return 0 for no support (that includes invalid parameters), MPG123_STEREO, - * MPG123_MONO or MPG123_STEREO|MPG123_MONO. */ -MPG123_EXPORT int mpg123_format_support( mpg123_handle *mh -, long rate, int encoding ); - -/** Get the current output format written to the addresses given. - * If the stream is freshly loaded, this will try to parse enough - * of it to give you the format to come. This clears the flag that - * would otherwise make the first decoding call return - * MPG123_NEW_FORMAT. - * \param mh handle - * \param rate sampling rate return address - * \param channels channel count return address - * \param encoding encoding return address - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_getformat( mpg123_handle *mh -, long *rate, int *channels, int *encoding ); - -/** Get the current output format written to the addresses given. - * This differs from plain mpg123_getformat() in that you can choose - * _not_ to clear the flag that would trigger the next decoding call - * to return MPG123_NEW_FORMAT in case of a new format arriving. - * \param mh handle - * \param rate sampling rate return address - * \param channels channel count return address - * \param encoding encoding return address - * \param clear_flag if true, clear internal format flag - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_getformat2( mpg123_handle *mh -, long *rate, int *channels, int *encoding, int clear_flag ); - -/** @} */ - - -/** \defgroup mpg123_input mpg123 file input and decoding - * - * Functions for input bitstream and decoding operations. - * Decoding/seek functions may also return message codes MPG123_DONE, MPG123_NEW_FORMAT and MPG123_NEED_MORE (please read up on these on how to react!). - * @{ - */ - -/** Open a simple MPEG file with fixed properties. - * - * This function shall simplify the common use case of a plain MPEG - * file on disk that you want to decode, with one fixed sample - * rate and channel count, and usually a length defined by a Lame/Info/Xing - * tag. It will: - * - * - set the MPG123_NO_FRANKENSTEIN flag - * - set up format support according to given parameters, - * - open the file, - * - query audio format, - * - fix the audio format support table to ensure the format stays the same, - * - call mpg123_scan() if there is no header frame to tell the track length. - * - * From that on, you can call mpg123_getformat() for querying the sample - * rate (and channel count in case you allowed both) and mpg123_length() - * to get a pretty safe number for the duration. - * Only the sample rate is left open as that indeed is a fixed property of - * MPEG files. You could set MPG123_FORCE_RATE beforehand, but that may trigger - * low-quality resampling in the decoder, only do so if in dire need. - * The library will convert mono files to stereo for you, and vice versa. - * If any constraint cannot be satisified (most likely because of a non-default - * build of libmpg123), you get MPG123_ERR returned and can query the detailed - * cause from the handle. Only on MPG123_OK there will an open file that you - * then close using mpg123_close(), or implicitly on mpg123_delete() or the next - * call to open another file. - * - * So, for your usual CD rip collection, you could use - * - * mpg123_open_fixed(mh, path, MPG123_STEREO, MPG123_ENC_SIGNED_16) - * - * and be happy calling mpg123_getformat() to verify 44100 Hz rate, then just - * playing away with mpg123_read(). The occasional mono file, or MP2 file, - * will also be decoded without you really noticing. Just the speed could be - * wrong if you do not care about sample rate at all. - * \param mh handle - * \param path filesystem path (see mpg123_open()) - * \param channels allowed channel count, either 1 (MPG123_MONO) or - * 2 (MPG123_STEREO), or bitwise or of them, but then you're halfway back to - * calling mpg123_format() again;-) - * \param encoding a definite encoding from enum mpg123_enc_enum - * or a bitmask like for mpg123_format(), defeating the purpose somewhat - */ -MPG123_EXPORT int mpg123_open_fixed(mpg123_handle *mh, const char *path -, int channels, int encoding); - -/** Open and prepare to decode the specified file by filesystem path. - * This does not open HTTP urls; libmpg123 contains no networking code. - * If you want to decode internet streams, use mpg123_open_fd() or mpg123_open_feed(). - * - * The path parameter usually is just a string that is handed to the underlying - * OS routine for opening, treated as a blob of binary data. On platforms - * where encoding needs to be involved, something like _wopen() is called - * underneath and the path argument to libmpg123 is assumed to be encoded in UTF-8. - * So, if you have to ask yourself which encoding is needed, the answer is - * UTF-8, which also fits any sane modern install of Unix-like systems. - * - * \param mh handle - * \param path filesystem - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_open(mpg123_handle *mh, const char *path); - -/** Use an already opened file descriptor as the bitstream input - * mpg123_close() will _not_ close the file descriptor. - * \param mh handle - * \param fd file descriptor - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_open_fd(mpg123_handle *mh, int fd); - -/** Use an opaque handle as bitstream input. This works only with the - * replaced I/O from mpg123_replace_reader_handle()! - * mpg123_close() will call the cleanup callback for your handle (if you gave one). - * \param mh handle - * \param iohandle your handle - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_open_handle(mpg123_handle *mh, void *iohandle); - -/** Open a new bitstream and prepare for direct feeding - * This works together with mpg123_decode(); you are responsible for reading and feeding the input bitstream. - * Also, you are expected to handle ICY metadata extraction yourself. This - * input method does not handle MPG123_ICY_INTERVAL. It does parse ID3 frames, though. - * \param mh handle - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_open_feed(mpg123_handle *mh); - -/** Closes the source, if libmpg123 opened it. - * \param mh handle - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_close(mpg123_handle *mh); - -/** Read from stream and decode up to outmemsize bytes. - * - * Note: The type of outmemory changed to a void pointer in mpg123 1.26.0 - * (API version 45). - * - * \param mh handle - * \param outmemory address of output buffer to write to - * \param outmemsize maximum number of bytes to write - * \param done address to store the number of actually decoded bytes to - * \return MPG123_OK or error/message code - */ -MPG123_EXPORT int mpg123_read(mpg123_handle *mh -, void *outmemory, size_t outmemsize, size_t *done ); - -/** Feed data for a stream that has been opened with mpg123_open_feed(). - * It's give and take: You provide the bytestream, mpg123 gives you the decoded samples. - * \param mh handle - * \param in input buffer - * \param size number of input bytes - * \return MPG123_OK or error/message code. - */ -MPG123_EXPORT int mpg123_feed( mpg123_handle *mh -, const unsigned char *in, size_t size ); - -/** Decode MPEG Audio from inmemory to outmemory. - * This is very close to a drop-in replacement for old mpglib. - * When you give zero-sized output buffer the input will be parsed until - * decoded data is available. This enables you to get MPG123_NEW_FORMAT (and query it) - * without taking decoded data. - * Think of this function being the union of mpg123_read() and mpg123_feed() (which it actually is, sort of;-). - * You can actually always decide if you want those specialized functions in separate steps or one call this one here. - * - * Note: The type of outmemory changed to a void pointer in mpg123 1.26.0 - * (API version 45). - * - * \param mh handle - * \param inmemory input buffer - * \param inmemsize number of input bytes - * \param outmemory output buffer - * \param outmemsize maximum number of output bytes - * \param done address to store the number of actually decoded bytes to - * \return error/message code (watch out especially for MPG123_NEED_MORE) - */ -MPG123_EXPORT int mpg123_decode( mpg123_handle *mh -, const unsigned char *inmemory, size_t inmemsize -, void *outmemory, size_t outmemsize, size_t *done ); - -/** Decode next MPEG frame to internal buffer - * or read a frame and return after setting a new format. - * \param mh handle - * \param num current frame offset gets stored there - * \param audio This pointer is set to the internal buffer to read the decoded audio from. - * \param bytes number of output bytes ready in the buffer - * \return MPG123_OK or error/message code - */ -MPG123_EXPORT int mpg123_decode_frame( mpg123_handle *mh -, off_t *num, unsigned char **audio, size_t *bytes ); - -/** Decode current MPEG frame to internal buffer. - * Warning: This is experimental API that might change in future releases! - * Please watch mpg123 development closely when using it. - * \param mh handle - * \param num last frame offset gets stored there - * \param audio this pointer is set to the internal buffer to read the decoded audio from. - * \param bytes number of output bytes ready in the buffer - * \return MPG123_OK or error/message code - */ -MPG123_EXPORT int mpg123_framebyframe_decode( mpg123_handle *mh -, off_t *num, unsigned char **audio, size_t *bytes ); - -/** Find, read and parse the next mp3 frame - * Warning: This is experimental API that might change in future releases! - * Please watch mpg123 development closely when using it. - * \param mh handle - * \return MPG123_OK or error/message code - */ -MPG123_EXPORT int mpg123_framebyframe_next(mpg123_handle *mh); - -/** Get access to the raw input data for the last parsed frame. - * This gives you a direct look (and write access) to the frame body data. - * Together with the raw header, you can reconstruct the whole raw MPEG stream without junk and meta data, or play games by actually modifying the frame body data before decoding this frame (mpg123_framebyframe_decode()). - * A more sane use would be to use this for CRC checking (see mpg123_info() and MPG123_CRC), the first two bytes of the body make up the CRC16 checksum, if present. - * You can provide NULL for a parameter pointer when you are not interested in the value. - * - * \param mh handle - * \param header the 4-byte MPEG header - * \param bodydata pointer to the frame body stored in the handle (without the header) - * \param bodybytes size of frame body in bytes (without the header) - * \return MPG123_OK if there was a yet un-decoded frame to get the - * data from, MPG123_BAD_HANDLE or MPG123_ERR otherwise (without further - * explanation, the error state of the mpg123_handle is not modified by - * this function). - */ -MPG123_EXPORT int mpg123_framedata( mpg123_handle *mh -, unsigned long *header, unsigned char **bodydata, size_t *bodybytes ); - -/** Get the input position (byte offset in stream) of the last parsed frame. - * This can be used for external seek index building, for example. - * It just returns the internally stored offset, regardless of validity -- - * you ensure that a valid frame has been parsed before! - * \param mh handle - * \return byte offset in stream - */ -MPG123_EXPORT off_t mpg123_framepos(mpg123_handle *mh); - -/** @} */ - - -/** \defgroup mpg123_seek mpg123 position and seeking - * - * Functions querying and manipulating position in the decoded audio bitstream. - * The position is measured in decoded audio samples or MPEG frame offset for - * the specific functions. The term sample refers to a group of samples for - * multiple channels, normally dubbed PCM frames. The latter term is - * avoided here because frame means something different in the context of MPEG - * audio. Since all samples of a PCM frame occur at the same time, there is only - * very limited ambiguity when talking about playback offset, as counting each - * channel sample individually does not make sense. - * - * If gapless code is in effect, the positions are adjusted to compensate the - * skipped padding/delay - meaning, you should not care about that at all and - * just use the position defined for the samples you get out of the decoder;-) - * The general usage is modelled after stdlib's ftell() and fseek(). - * Especially, the whence parameter for the seek functions has the same meaning - * as the one for fseek() and needs the same constants from stdlib.h: - * - * - SEEK_SET: set position to (or near to) specified offset - * - SEEK_CUR: change position by offset from now - * - SEEK_END: set position to offset from end - * - * Note that sample-accurate seek only works when gapless support has been - * enabled at compile time; seek is frame-accurate otherwise. - * Also, really sample-accurate seeking (meaning that you get the identical - * sample value after seeking compared to plain decoding up to the position) - * is only guaranteed when you do not mess with the position code by using - * #MPG123_UPSPEED, #MPG123_DOWNSPEED or #MPG123_START_FRAME. The first two mainly - * should cause trouble with NtoM resampling, but in any case with these options - * in effect, you have to keep in mind that the sample offset is not the same - * as counting the samples you get from decoding since mpg123 counts the skipped - * samples, too (or the samples played twice only once)! - * - * Short: When you care about the sample position, don't mess with those - * parameters;-) - * - * Streams may be openend in ways that do not support seeking. Also, consider - * the effect of #MPG123_FUZZY. - * - * @{ - */ - -/** Returns the current position in samples. - * On the next successful read, you'd get audio data with that offset. - * \param mh handle - * \return sample (PCM frame) offset or MPG123_ERR (null handle) - */ -MPG123_EXPORT off_t mpg123_tell(mpg123_handle *mh); - -/** Returns the frame number that the next read will give you data from. - * \param mh handle - * \return frame offset or MPG123_ERR (null handle) - */ -MPG123_EXPORT off_t mpg123_tellframe(mpg123_handle *mh); - -/** Returns the current byte offset in the input stream. - * \param mh handle - * \return byte offset or MPG123_ERR (null handle) - */ -MPG123_EXPORT off_t mpg123_tell_stream(mpg123_handle *mh); - -/** Seek to a desired sample offset. - * Usage is modelled afer the standard lseek(). - * \param mh handle - * \param sampleoff offset in samples (PCM frames) - * \param whence one of SEEK_SET, SEEK_CUR or SEEK_END - * \return The resulting offset >= 0 or error/message code - */ -MPG123_EXPORT off_t mpg123_seek( mpg123_handle *mh -, off_t sampleoff, int whence ); - -/** Seek to a desired sample offset in data feeding mode. - * This just prepares things to be right only if you ensure that the next chunk - * of input data will be from input_offset byte position. - * \param mh handle - * \param sampleoff offset in samples (PCM frames) - * \param whence one of SEEK_SET, SEEK_CUR or SEEK_END - * \param input_offset The position it expects to be at the - * next time data is fed to mpg123_decode(). - * \return The resulting offset >= 0 or error/message code - */ -MPG123_EXPORT off_t mpg123_feedseek( mpg123_handle *mh -, off_t sampleoff, int whence, off_t *input_offset ); - -/** Seek to a desired MPEG frame offset. - * Usage is modelled afer the standard lseek(). - * \param mh handle - * \param frameoff offset in MPEG frames - * \param whence one of SEEK_SET, SEEK_CUR or SEEK_END - * \return The resulting offset >= 0 or error/message code */ -MPG123_EXPORT off_t mpg123_seek_frame( mpg123_handle *mh -, off_t frameoff, int whence ); - -/** Return a MPEG frame offset corresponding to an offset in seconds. - * This assumes that the samples per frame do not change in the file/stream, which is a good assumption for any sane file/stream only. - * \return frame offset >= 0 or error/message code */ -MPG123_EXPORT off_t mpg123_timeframe(mpg123_handle *mh, double sec); - -/** Give access to the frame index table that is managed for seeking. - * You are asked not to modify the values... Use mpg123_set_index to set the - * seek index - * \param mh handle - * \param offsets pointer to the index array - * \param step one index byte offset advances this many MPEG frames - * \param fill number of recorded index offsets; size of the array - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_index( mpg123_handle *mh -, off_t **offsets, off_t *step, size_t *fill ); - -/** Set the frame index table - * Setting offsets to NULL and fill > 0 will allocate fill entries. Setting offsets - * to NULL and fill to 0 will clear the index and free the allocated memory used by the index. - * \param mh handle - * \param offsets pointer to the index array - * \param step one index byte offset advances this many MPEG frames - * \param fill number of recorded index offsets; size of the array - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_set_index( mpg123_handle *mh -, off_t *offsets, off_t step, size_t fill ); - -/** An old crutch to keep old mpg123 binaries happy. - * WARNING: This function is there only to avoid runtime linking errors with - * standalone mpg123 before version 1.23.0 (if you strangely update the - * library but not the end-user program) and actually is broken - * for various cases (p.ex. 24 bit output). Do never use. It might eventually - * be purged from the library. - */ -MPG123_EXPORT int mpg123_position( mpg123_handle *mh, off_t frame_offset, off_t buffered_bytes, off_t *current_frame, off_t *frames_left, double *current_seconds, double *seconds_left); - -/** @} */ - - -/** \defgroup mpg123_voleq mpg123 volume and equalizer - * - * @{ - */ - -/** another channel enumeration, for left/right choice */ -enum mpg123_channels -{ - MPG123_LEFT=0x1 /**< The Left Channel. */ - ,MPG123_RIGHT=0x2 /**< The Right Channel. */ - ,MPG123_LR=0x3 /**< Both left and right channel; same as MPG123_LEFT|MPG123_RIGHT */ -}; - -#ifdef MPG123_ENUM_API -/** Set the 32 Band Audio Equalizer settings. - * - * Note that this name is mapped to mpg123_eq2() instead unless - * MPG123_ENUM_API is defined. - * - * \param mh handle - * \param channel Can be #MPG123_LEFT, #MPG123_RIGHT or - * #MPG123_LEFT|#MPG123_RIGHT for both. - * \param band The equaliser band to change (from 0 to 31) - * \param val The (linear) adjustment factor. - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_eq( mpg123_handle *mh -, enum mpg123_channels channel, int band, double val ); -#endif - -/** Set the 32 Band Audio Equalizer settings. No enums. - * - * This is actually called instead of mpg123_eq() unless MPG123_ENUM_API - * is defined. - * - * \param mh handle - * \param channel Can be #MPG123_LEFT, #MPG123_RIGHT or - * #MPG123_LEFT|#MPG123_RIGHT for both. - * \param band The equaliser band to change (from 0 to 31) - * \param val The (linear) adjustment factor. - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_eq2( mpg123_handle *mh -, int channel, int band, double val ); - -#ifdef MPG123_ENUM_API -/** Get the 32 Band Audio Equalizer settings. - * - * Note that this name is mapped to mpg123_geteq2() instead unless - * MPG123_ENUM_API is defined. - * - * \param mh handle - * \param channel Can be #MPG123_LEFT, #MPG123_RIGHT or - * #MPG123_LEFT|MPG123_RIGHT for (arithmetic mean of) both. - * \param band The equaliser band to change (from 0 to 31) - * \return The (linear) adjustment factor (zero for pad parameters) */ -MPG123_EXPORT double mpg123_geteq(mpg123_handle *mh - , enum mpg123_channels channel, int band); -#endif - -/** Get the 32 Band Audio Equalizer settings. - * - * This is actually called instead of mpg123_geteq() unless MPG123_ENUM_API - * is defined. - * - * \param mh handle - * \param channel Can be #MPG123_LEFT, #MPG123_RIGHT or - * #MPG123_LEFT|MPG123_RIGHT for (arithmetic mean of) both. - * \param band The equaliser band to change (from 0 to 31) - * \return The (linear) adjustment factor (zero for pad parameters) */ -MPG123_EXPORT double mpg123_geteq2(mpg123_handle *mh, int channel, int band); - -/** Reset the 32 Band Audio Equalizer settings to flat - * \param mh handle - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_reset_eq(mpg123_handle *mh); - -/** Set the absolute output volume including the RVA setting, - * vol<0 just applies (a possibly changed) RVA setting. - * \param mh handle - * \param vol volume value (linear factor) - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_volume(mpg123_handle *mh, double vol); - -/** Adjust output volume including the RVA setting by chosen amount - * \param mh handle - * \param change volume value (linear factor increment) - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_volume_change(mpg123_handle *mh, double change); - -/** Return current volume setting, the actual value due to RVA, and the RVA - * adjustment itself. It's all as double float value to abstract the sample - * format. The volume values are linear factors / amplitudes (not percent) - * and the RVA value is in decibels. - * \param mh handle - * \param base return address for base volume (linear factor) - * \param really return address for actual volume (linear factor) - * \param rva_db return address for RVA value (decibels) - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_getvolume(mpg123_handle *mh, double *base, double *really, double *rva_db); - -/* TODO: Set some preamp in addition / to replace internal RVA handling? */ - -/** @} */ - - -/** \defgroup mpg123_status mpg123 status and information - * - * @{ - */ - -/** Enumeration of the mode types of Variable Bitrate */ -enum mpg123_vbr { - MPG123_CBR=0, /**< Constant Bitrate Mode (default) */ - MPG123_VBR, /**< Variable Bitrate Mode */ - MPG123_ABR /**< Average Bitrate Mode */ -}; - -/** Enumeration of the MPEG Versions */ -enum mpg123_version { - MPG123_1_0=0, /**< MPEG Version 1.0 */ - MPG123_2_0, /**< MPEG Version 2.0 */ - MPG123_2_5 /**< MPEG Version 2.5 */ -}; - - -/** Enumeration of the MPEG Audio mode. - * Only the mono mode has 1 channel, the others have 2 channels. */ -enum mpg123_mode { - MPG123_M_STEREO=0, /**< Standard Stereo. */ - MPG123_M_JOINT, /**< Joint Stereo. */ - MPG123_M_DUAL, /**< Dual Channel. */ - MPG123_M_MONO /**< Single Channel. */ -}; - - -/** Enumeration of the MPEG Audio flag bits */ -enum mpg123_flags { - MPG123_CRC=0x1, /**< The bitstream is error protected using 16-bit CRC. */ - MPG123_COPYRIGHT=0x2, /**< The bitstream is copyrighted. */ - MPG123_PRIVATE=0x4, /**< The private bit has been set. */ - MPG123_ORIGINAL=0x8 /**< The bitstream is an original, not a copy. */ -}; - -#ifdef MPG123_ENUM_API -/** Data structure for storing information about a frame of MPEG Audio */ -struct mpg123_frameinfo -{ - enum mpg123_version version; /**< The MPEG version (1.0/2.0/2.5). */ - int layer; /**< The MPEG Audio Layer (MP1/MP2/MP3). */ - long rate; /**< The sampling rate in Hz. */ - enum mpg123_mode mode; /**< The audio mode (Mono, Stereo, Joint-stero, Dual Channel). */ - int mode_ext; /**< The mode extension bit flag. */ - int framesize; /**< The size of the frame (in bytes, including header). */ - enum mpg123_flags flags; /**< MPEG Audio flag bits. Just now I realize that it should be declared as int, not enum. It's a bitwise combination of the enum values. */ - int emphasis; /**< The emphasis type. */ - int bitrate; /**< Bitrate of the frame (kbps). */ - int abr_rate; /**< The target average bitrate. */ - enum mpg123_vbr vbr; /**< The VBR mode. */ -}; -#endif - -/** Data structure for storing information about a frame of MPEG Audio without enums */ -struct mpg123_frameinfo2 -{ - int version; /**< The MPEG version (1.0/2.0/2.5), enum mpg123_version. */ - int layer; /**< The MPEG Audio Layer (MP1/MP2/MP3). */ - long rate; /**< The sampling rate in Hz. */ - int mode; /**< The audio mode (enum mpg123_mode, Mono, Stereo, Joint-stero, Dual Channel). */ - int mode_ext; /**< The mode extension bit flag. */ - int framesize; /**< The size of the frame (in bytes, including header). */ - int flags; /**< MPEG Audio flag bits. Bitwise combination of enum mpg123_flags values. */ - int emphasis; /**< The emphasis type. */ - int bitrate; /**< Bitrate of the frame (kbps). */ - int abr_rate; /**< The target average bitrate. */ - int vbr; /**< The VBR mode, enum mpg123_vbr. */ -}; - -/** Data structure for even more detailed information out of the decoder, - * for MPEG layer III only. - * This was added to support the frame analyzer by the Lame project and - * just follows what was used there before. You know what the fields mean - * if you want use this structure. */ -struct mpg123_moreinfo -{ - double xr[2][2][576]; /**< internal data */ - double sfb[2][2][22]; /**< [2][2][SBMAX_l] */ - double sfb_s[2][2][3*13]; /**< [2][2][3*SBMAX_s] */ - int qss[2][2]; /**< internal data */ - int big_values[2][2]; /**< internal data */ - int sub_gain[2][2][3]; /**< internal data */ - int scalefac_scale[2][2]; /**< internal data */ - int preflag[2][2]; /**< internal data */ - int blocktype[2][2]; /**< internal data */ - int mixed[2][2]; /**< internal data */ - int mainbits[2][2]; /**< internal data */ - int sfbits[2][2]; /**< internal data */ - int scfsi[2]; /**< internal data */ - int maindata; /**< internal data */ - int padding; /**< internal data */ -}; - -#ifdef MPG123_ENUM_API -/** Get frame information about the MPEG audio bitstream and store - * it in a mpg123_frameinfo structure. - * - * Note that this name is mapped to mpg123_info2() instead unless - * MPG123_ENUM_API is defined. - * - * \param mh handle - * \param mi address of existing frameinfo structure to write to - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_info(mpg123_handle *mh, struct mpg123_frameinfo *mi); -#endif - -/** Get frame information about the MPEG audio bitstream and store - * it in a mpg123_frameinfo2 structure. - * - * This is actually called instead of mpg123_info() - * unless MPG123_ENUM_API is defined. - * - * \param mh handle - * \param mi address of existing frameinfo structure to write to - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_info2(mpg123_handle *mh, struct mpg123_frameinfo2 *mi); - -/** Trigger collection of additional decoder information while decoding. - * \param mh handle - * \param mi pointer to data storage (NULL to disable collection) - * \return MPG123_OK if the collection was enabled/disabled as desired, MPG123_ERR - * otherwise (e.g. if the feature is disabled) - */ -MPG123_EXPORT int mpg123_set_moreinfo( mpg123_handle *mh -, struct mpg123_moreinfo *mi ); - -/** Get the safe output buffer size for all cases - * (when you want to replace the internal buffer) - * \return safe buffer size - */ -MPG123_EXPORT size_t mpg123_safe_buffer(void); - -/** Make a full parsing scan of each frame in the file. ID3 tags are found. An - * accurate length value is stored. Seek index will be filled. A seek back to - * current position is performed. At all, this function refuses work when - * stream is not seekable. - * \param mh handle - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_scan(mpg123_handle *mh); - -/** Return, if possible, the full (expected) length of current track in - * MPEG frames. - * \param mh handle - * \return length >= 0 or MPG123_ERR if there is no length guess possible. - */ -MPG123_EXPORT off_t mpg123_framelength(mpg123_handle *mh); - -/** Return, if possible, the full (expected) length of current - * track in samples (PCM frames). - * - * This relies either on an Info frame at the beginning or a previous - * call to mpg123_scan() to get the real number of MPEG frames in a - * file. It will guess based on file size if neither Info frame nor - * scan data are present. In any case, there is no guarantee that the - * decoder will not give you more data, for example in case the open - * file gets appended to during decoding. - * \param mh handle - * \return length >= 0 or MPG123_ERR if there is no length guess possible. - */ -MPG123_EXPORT off_t mpg123_length(mpg123_handle *mh); - -/** Override the value for file size in bytes. - * Useful for getting sensible track length values in feed mode or for HTTP streams. - * \param mh handle - * \param size file size in bytes - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_set_filesize(mpg123_handle *mh, off_t size); - -/** Get MPEG frame duration in seconds. - * \param mh handle - * \return frame duration in seconds, <0 on error - */ -MPG123_EXPORT double mpg123_tpf(mpg123_handle *mh); - -/** Get MPEG frame duration in samples. - * \param mh handle - * \return samples per frame for the most recently parsed frame; <0 on errors - */ -MPG123_EXPORT int mpg123_spf(mpg123_handle *mh); - -/** Get and reset the clip count. - * \param mh handle - * \return count of clipped samples - */ -MPG123_EXPORT long mpg123_clip(mpg123_handle *mh); - - -/** The key values for state information from mpg123_getstate(). */ -enum mpg123_state -{ - MPG123_ACCURATE = 1 /**< Query if positons are currently accurate (integer value, 0 if false, 1 if true). */ - ,MPG123_BUFFERFILL /**< Get fill of internal (feed) input buffer as integer byte count returned as long and as double. An error is returned on integer overflow while converting to (signed) long, but the returned floating point value shold still be fine. */ - ,MPG123_FRANKENSTEIN /**< Stream consists of carelessly stitched together files. Seeking may yield unexpected results (also with MPG123_ACCURATE, it may be confused). */ - ,MPG123_FRESH_DECODER /**< Decoder structure has been updated, possibly indicating changed stream (integer value, 0 if false, 1 if true). Flag is cleared after retrieval. */ - ,MPG123_ENC_DELAY /** Encoder delay read from Info tag (layer III, -1 if unknown). */ - ,MPG123_ENC_PADDING /** Encoder padding read from Info tag (layer III, -1 if unknown). */ - ,MPG123_DEC_DELAY /** Decoder delay (for layer III only, -1 otherwise). */ -}; - -#ifdef MPG123_ENUM_API -/** Get various current decoder/stream state information. - * - * Note that this name is mapped to mpg123_getstate2() instead unless - * MPG123_ENUM_API is defined. - * - * \param mh handle - * \param key the key to identify the information to give. - * \param val the address to return (long) integer values to - * \param fval the address to return floating point values to - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_getstate( mpg123_handle *mh -, enum mpg123_state key, long *val, double *fval ); -#endif - -/** Get various current decoder/stream state information. No enums. - * - * This is actually called instead of mpg123_getstate() - * unless MPG123_ENUM_API is defined. - * - * \param mh handle - * \param key the key to identify the information to give (enum mpg123_state) - * \param val the address to return (long) integer values to - * \param fval the address to return floating point values to - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_getstate2( mpg123_handle *mh -, int key, long *val, double *fval ); - -/** @} */ - - -/** \defgroup mpg123_metadata mpg123 metadata handling - * - * Functions to retrieve the metadata from MPEG Audio files and streams. - * Also includes string handling functions. - * - * @{ - */ - -/** Data structure for storing strings in a safer way than a standard C-String. - * Can also hold a number of null-terminated strings. */ -typedef struct -{ - char* p; /**< pointer to the string data */ - size_t size; /**< raw number of bytes allocated */ - size_t fill; /**< number of used bytes (including closing zero byte) */ -} mpg123_string; - -/** Allocate and intialize a new string. - * \param val optional initial string value (can be NULL) - */ -MPG123_EXPORT mpg123_string* mpg123_new_string(const char* val); - -/** Free memory of contents and the string structure itself. - * \param sb string handle - */ -MPG123_EXPORT void mpg123_delete_string(mpg123_string* sb); - -/** Initialize an existing mpg123_string structure to {NULL, 0, 0}. - * If you hand in a NULL pointer here, your program should crash. The other - * string functions are more forgiving, but this one here is too basic. - * \param sb string handle (address of existing structure on your side) - */ -MPG123_EXPORT void mpg123_init_string(mpg123_string* sb); - -/** Free-up memory of the contents of an mpg123_string (not the struct itself). - * This also calls mpg123_init_string() and hence is safe to be called - * repeatedly. - * \param sb string handle - */ -MPG123_EXPORT void mpg123_free_string(mpg123_string* sb); - -/** Change the size of a mpg123_string - * \param sb string handle - * \param news new size in bytes - * \return 0 on error, 1 on success - */ -MPG123_EXPORT int mpg123_resize_string(mpg123_string* sb, size_t news); - -/** Increase size of a mpg123_string if necessary (it may stay larger). - * Note that the functions for adding and setting in current libmpg123 - * use this instead of mpg123_resize_string(). - * That way, you can preallocate memory and safely work afterwards with - * pieces. - * \param sb string handle - * \param news new minimum size - * \return 0 on error, 1 on success - */ -MPG123_EXPORT int mpg123_grow_string(mpg123_string* sb, size_t news); - -/** Copy the contents of one mpg123_string string to another. - * Yes the order of arguments is reversed compated to memcpy(). - * \param from string handle - * \param to string handle - * \return 0 on error, 1 on success - */ -MPG123_EXPORT int mpg123_copy_string(mpg123_string* from, mpg123_string* to); - -/** Move the contents of one mpg123_string string to another. - * This frees any memory associated with the target and moves over the - * pointers from the source, leaving the source without content after - * that. The only possible error is that you hand in NULL pointers. - * If you handed in a valid source, its contents will be gone, even if - * there was no target to move to. If you hand in a valid target, its - * original contents will also always be gone, to be replaced with the - * source's contents if there was some. - * \param from source string handle - * \param to target string handle - * \return 0 on error, 1 on success - */ -MPG123_EXPORT int mpg123_move_string(mpg123_string* from, mpg123_string* to); - -/** Append a C-String to an mpg123_string - * \param sb string handle - * \param stuff to append - * \return 0 on error, 1 on success - */ -MPG123_EXPORT int mpg123_add_string(mpg123_string* sb, const char* stuff); - -/** Append a C-substring to an mpg123 string - * \param sb string handle - * \param stuff content to copy - * \param from offset to copy from - * \param count number of characters to copy (a null-byte is always appended) - * \return 0 on error, 1 on success - */ -MPG123_EXPORT int mpg123_add_substring( mpg123_string *sb -, const char *stuff, size_t from, size_t count ); - -/** Set the content of a mpg123_string to a C-string - * \param sb string handle - * \param stuff content to copy - * \return 0 on error, 1 on success - */ -MPG123_EXPORT int mpg123_set_string(mpg123_string* sb, const char* stuff); - -/** Set the content of a mpg123_string to a C-substring - * \param sb string handle - * \param stuff the future content - * \param from offset to copy from - * \param count number of characters to copy (a null-byte is always appended) - * \return 0 on error, 1 on success - */ -MPG123_EXPORT int mpg123_set_substring( mpg123_string *sb -, const char *stuff, size_t from, size_t count ); - -/** Count characters in a mpg123 string (non-null bytes or Unicode points). - * This function is of limited use, as it does just count code points - * encoded in an UTF-8 string, only loosely related to the count of visible - * characters. Get your full Unicode handling support elsewhere. - * \param sb string handle - * \param utf8 a flag to tell if the string is in utf8 encoding - * \return character count -*/ -MPG123_EXPORT size_t mpg123_strlen(mpg123_string *sb, int utf8); - -/** Remove trailing \\r and \\n, if present. - * \param sb string handle - * \return 0 on error, 1 on success - */ -MPG123_EXPORT int mpg123_chomp_string(mpg123_string *sb); - -/** Determine if two strings contain the same data. - * This only returns 1 if both given handles are non-NULL and - * if they are filled with the same bytes. - * \param a first string handle - * \param b second string handle - * \return 0 for different strings, 1 for identical - */ -MPG123_EXPORT int mpg123_same_string(mpg123_string *a, mpg123_string *b); - -/** The mpg123 text encodings. This contains encodings we encounter in ID3 tags or ICY meta info. */ -enum mpg123_text_encoding -{ - mpg123_text_unknown = 0 /**< Unkown encoding... mpg123_id3_encoding can return that on invalid codes. */ - ,mpg123_text_utf8 = 1 /**< UTF-8 */ - ,mpg123_text_latin1 = 2 /**< ISO-8859-1. Note that sometimes latin1 in ID3 is abused for totally different encodings. */ - ,mpg123_text_icy = 3 /**< ICY metadata encoding, usually CP-1252 but we take it as UTF-8 if it qualifies as such. */ - ,mpg123_text_cp1252 = 4 /**< Really CP-1252 without any guessing. */ - ,mpg123_text_utf16 = 5 /**< Some UTF-16 encoding. The last of a set of leading BOMs (byte order mark) rules. - * When there is no BOM, big endian ordering is used. Note that UCS-2 qualifies as UTF-8 when - * you don't mess with the reserved code points. If you want to decode little endian data - * without BOM you need to prepend 0xff 0xfe yourself. */ - ,mpg123_text_utf16bom = 6 /**< Just an alias for UTF-16, ID3v2 has this as distinct code. */ - ,mpg123_text_utf16be = 7 /**< Another alias for UTF16 from ID3v2. Note, that, because of the mess that is reality, - * BOMs are used if encountered. There really is not much distinction between the UTF16 types for mpg123 - * One exception: Since this is seen in ID3v2 tags, leading null bytes are skipped for all other UTF16 - * types (we expect a BOM before real data there), not so for utf16be!*/ - ,mpg123_text_max = 7 /**< Placeholder for the maximum encoding value. */ -}; - -/** The encoding byte values from ID3v2. */ -enum mpg123_id3_enc -{ - mpg123_id3_latin1 = 0 /**< Note: This sometimes can mean anything in practice... */ - ,mpg123_id3_utf16bom = 1 /**< UTF16, UCS-2 ... it's all the same for practical purposes. */ - ,mpg123_id3_utf16be = 2 /**< Big-endian UTF-16, BOM see note for mpg123_text_utf16be. */ - ,mpg123_id3_utf8 = 3 /**< Our lovely overly ASCII-compatible 8 byte encoding for the world. */ - ,mpg123_id3_enc_max = 3 /**< Placeholder to check valid range of encoding byte. */ -}; - -#ifdef MPG123_ENUM_API -/** Convert ID3 encoding byte to mpg123 encoding index. - * - * Note that this name is mapped to mpg123_enc_from_id3_2() instead unless - * MPG123_ENUM_API is defined. - * - * \param id3_enc_byte the ID3 encoding code - * \return the mpg123 encoding index - */ -MPG123_EXPORT enum mpg123_text_encoding mpg123_enc_from_id3(unsigned char id3_enc_byte); -#endif - -/** Convert ID3 encoding byte to mpg123 encoding index. No enums. - * - * This is actually called instead of mpg123_enc_from_id3() - * unless MPG123_ENUM_API is defined. - * - * \param id3_enc_byte the ID3 encoding code - * \return the mpg123 encoding index - */ -MPG123_EXPORT int mpg123_enc_from_id3_2(unsigned char id3_enc_byte); - -#ifdef MPG123_ENUM_API -/** Store text data in string, after converting to UTF-8 from indicated encoding. - * - * Note that this name is mapped to mpg123_store_utf8_2() instead unless - * MPG123_ENUM_API is defined. - * - * A prominent error can be that you provided an unknown encoding value, or this build of libmpg123 lacks support for certain encodings (ID3 or ICY stuff missing). - * Also, you might want to take a bit of care with preparing the data; for example, strip leading zeroes (I have seen that). - * \param sb target string - * \param enc mpg123 text encoding value - * \param source source buffer with plain unsigned bytes (you might need to cast from signed char) - * \param source_size number of bytes in the source buffer - * \return 0 on error, 1 on success (on error, mpg123_free_string is called on sb) - */ -MPG123_EXPORT int mpg123_store_utf8(mpg123_string *sb, enum mpg123_text_encoding enc, const unsigned char *source, size_t source_size); -#endif - -/** Store text data in string, after converting to UTF-8 from indicated encoding. No enums. - * - * This is actually called instead of mpg123_store_utf8() - * unless MPG123_ENUM_API is defined. - * - * A prominent error can be that you provided an unknown encoding value, or this build of libmpg123 lacks support for certain encodings (ID3 or ICY stuff missing). - * Also, you might want to take a bit of care with preparing the data; for example, strip leading zeroes (I have seen that). - * \param sb target string - * \param enc mpg123 text encoding value (enum mpg123_text_encoding) - * \param source source buffer with plain unsigned bytes (you might need to cast from signed char) - * \param source_size number of bytes in the source buffer - * \return 0 on error, 1 on success (on error, mpg123_free_string is called on sb) - */ -MPG123_EXPORT int mpg123_store_utf8_2(mpg123_string *sb -, int enc, const unsigned char *source, size_t source_size); - -/** Sub data structure for ID3v2, for storing various text fields (including comments). - * This is for ID3v2 COMM, TXXX and all the other text fields. - * Only COMM, TXXX and USLT may have a description, only COMM and USLT - * have a language. - * You should consult the ID3v2 specification for the use of the various text fields - * ("frames" in ID3v2 documentation, I use "fields" here to separate from MPEG frames). */ -typedef struct -{ - char lang[3]; /**< Three-letter language code (not terminated). */ - char id[4]; /**< The ID3v2 text field id, like TALB, TPE2, ... (4 characters, no string termination). */ - mpg123_string description; /**< Empty for the generic comment... */ - mpg123_string text; /**< ... */ -} mpg123_text; - -/** The picture type values from ID3v2. */ -enum mpg123_id3_pic_type -{ - mpg123_id3_pic_other = 0 /**< see ID3v2 docs */ - ,mpg123_id3_pic_icon = 1 /**< see ID3v2 docs */ - ,mpg123_id3_pic_other_icon = 2 /**< see ID3v2 docs */ - ,mpg123_id3_pic_front_cover = 3 /**< see ID3v2 docs */ - ,mpg123_id3_pic_back_cover = 4 /**< see ID3v2 docs */ - ,mpg123_id3_pic_leaflet = 5 /**< see ID3v2 docs */ - ,mpg123_id3_pic_media = 6 /**< see ID3v2 docs */ - ,mpg123_id3_pic_lead = 7 /**< see ID3v2 docs */ - ,mpg123_id3_pic_artist = 8 /**< see ID3v2 docs */ - ,mpg123_id3_pic_conductor = 9 /**< see ID3v2 docs */ - ,mpg123_id3_pic_orchestra = 10 /**< see ID3v2 docs */ - ,mpg123_id3_pic_composer = 11 /**< see ID3v2 docs */ - ,mpg123_id3_pic_lyricist = 12 /**< see ID3v2 docs */ - ,mpg123_id3_pic_location = 13 /**< see ID3v2 docs */ - ,mpg123_id3_pic_recording = 14 /**< see ID3v2 docs */ - ,mpg123_id3_pic_performance = 15 /**< see ID3v2 docs */ - ,mpg123_id3_pic_video = 16 /**< see ID3v2 docs */ - ,mpg123_id3_pic_fish = 17 /**< see ID3v2 docs */ - ,mpg123_id3_pic_illustration = 18 /**< see ID3v2 docs */ - ,mpg123_id3_pic_artist_logo = 19 /**< see ID3v2 docs */ - ,mpg123_id3_pic_publisher_logo = 20 /**< see ID3v2 docs */ -}; - -/** Sub data structure for ID3v2, for storing picture data including comment. - * This is for the ID3v2 APIC field. You should consult the ID3v2 specification - * for the use of the APIC field ("frames" in ID3v2 documentation, I use "fields" - * here to separate from MPEG frames). */ -typedef struct -{ - char type; /**< mpg123_id3_pic_type value */ - mpg123_string description; /**< description string */ - mpg123_string mime_type; /**< MIME type */ - size_t size; /**< size in bytes */ - unsigned char* data; /**< pointer to the image data */ -} mpg123_picture; - -/** Data structure for storing IDV3v2 tags. - * This structure is not a direct binary mapping with the file contents. - * The ID3v2 text frames are allowed to contain multiple strings. - * So check for null bytes until you reach the mpg123_string fill. - * All text is encoded in UTF-8. */ -typedef struct -{ - unsigned char version; /**< 3 or 4 for ID3v2.3 or ID3v2.4. */ - mpg123_string *title; /**< Title string (pointer into text_list). */ - mpg123_string *artist; /**< Artist string (pointer into text_list). */ - mpg123_string *album; /**< Album string (pointer into text_list). */ - mpg123_string *year; /**< The year as a string (pointer into text_list). */ - mpg123_string *genre; /**< Genre String (pointer into text_list). The genre string(s) may very well need postprocessing, esp. for ID3v2.3. */ - mpg123_string *comment; /**< Pointer to last encountered comment text with empty description. */ - /* Encountered ID3v2 fields are appended to these lists. - There can be multiple occurences, the pointers above always point to the last encountered data. */ - mpg123_text *comment_list; /**< Array of comments. */ - size_t comments; /**< Number of comments. */ - mpg123_text *text; /**< Array of ID3v2 text fields (including USLT) */ - size_t texts; /**< Numer of text fields. */ - mpg123_text *extra; /**< The array of extra (TXXX) fields. */ - size_t extras; /**< Number of extra text (TXXX) fields. */ - mpg123_picture *picture; /**< Array of ID3v2 pictures fields (APIC). - Only populated if MPG123_PICTURE flag is set! */ - size_t pictures; /**< Number of picture (APIC) fields. */ -} mpg123_id3v2; - -/** Data structure for ID3v1 tags (the last 128 bytes of a file). - * Don't take anything for granted (like string termination)! - * Also note the change ID3v1.1 did: comment[28] = 0; comment[29] = track_number - * It is your task to support ID3v1 only or ID3v1.1 ...*/ -typedef struct -{ - char tag[3]; /**< Always the string "TAG", the classic intro. */ - char title[30]; /**< Title string. */ - char artist[30]; /**< Artist string. */ - char album[30]; /**< Album string. */ - char year[4]; /**< Year string. */ - char comment[30]; /**< Comment string. */ - unsigned char genre; /**< Genre index. */ -} mpg123_id3v1; - -#define MPG123_ID3 0x3 /**< 0011 There is some ID3 info. Also matches 0010 or NEW_ID3. */ -#define MPG123_NEW_ID3 0x1 /**< 0001 There is ID3 info that changed since last call to mpg123_id3. */ -#define MPG123_ICY 0xc /**< 1100 There is some ICY info. Also matches 0100 or NEW_ICY.*/ -#define MPG123_NEW_ICY 0x4 /**< 0100 There is ICY info that changed since last call to mpg123_icy. */ - -/** Query if there is (new) meta info, be it ID3 or ICY (or something new in future). - * \param mh handle - * \return combination of flags, 0 on error (same as "nothing new") - */ -MPG123_EXPORT int mpg123_meta_check(mpg123_handle *mh); - -/** Clean up meta data storage (ID3v2 and ICY), freeing memory. - * \param mh handle - */ -MPG123_EXPORT void mpg123_meta_free(mpg123_handle *mh); - -/** Point v1 and v2 to existing data structures wich may change on any next read/decode function call. - * v1 and/or v2 can be set to NULL when there is no corresponding data. - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_id3( mpg123_handle *mh -, mpg123_id3v1 **v1, mpg123_id3v2 **v2 ); - -/** Return pointers to and size of stored raw ID3 data if storage has - * been configured with MPG123_RAW_ID3 and stream parsing passed the - * metadata already. Null value with zero size is a possibility! - * The storage can change at any next API call. - * - * \param mh mpg123 handle - * \param v1 address to store pointer to v1 tag - * \param v1_size size of v1 data in bytes - * \param v2 address to store pointer to v2 tag - * \param v2_size size of v2 data in bytes - * \return MPG123_OK or MPG123_ERR. Only on MPG123_OK the output - * values are set. - */ -MPG123_EXPORT int mpg123_id3_raw( mpg123_handle *mh -, unsigned char **v1, size_t *v1_size -, unsigned char **v2, size_t *v2_size ); - -/** Point icy_meta to existing data structure wich may change on any next read/decode function call. - * \param mh handle - * \param icy_meta return address for ICY meta string (set to NULL if nothing there) - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_icy(mpg123_handle *mh, char **icy_meta); - -/** Decode from windows-1252 (the encoding ICY metainfo used) to UTF-8. - * Note that this is very similar to mpg123_store_utf8(&sb, mpg123_text_icy, icy_text, strlen(icy_text+1)) . - * \param icy_text The input data in ICY encoding - * \return pointer to newly allocated buffer with UTF-8 data (You free() it!) */ -MPG123_EXPORT char* mpg123_icy2utf8(const char* icy_text); - - -/** @} */ - - -/** \defgroup mpg123_advpar mpg123 advanced parameter API - * - * Direct access to a parameter set without full handle around it. - * Possible uses: - * - Influence behaviour of library _during_ initialization of handle (MPG123_VERBOSE). - * - Use one set of parameters for multiple handles. - * - * The functions for handling mpg123_pars (mpg123_par() and mpg123_fmt() - * family) directly return a fully qualified mpg123 error code, the ones - * operating on full handles normally MPG123_OK or MPG123_ERR, storing the - * specific error code itseld inside the handle. - * - * @{ - */ - -/** Opaque structure for the libmpg123 decoder parameters. */ -struct mpg123_pars_struct; - -/** Opaque structure for the libmpg123 decoder parameters. */ -typedef struct mpg123_pars_struct mpg123_pars; - -/** Create a handle with preset parameters. - * \param mp parameter handle - * \param decoder decoder choice - * \param error error code return address - * \return mpg123 handle - */ -MPG123_EXPORT mpg123_handle *mpg123_parnew( mpg123_pars *mp -, const char* decoder, int *error ); - -/** Allocate memory for and return a pointer to a new mpg123_pars - * \param error error code return address - * \return new parameter handle - */ -MPG123_EXPORT mpg123_pars *mpg123_new_pars(int *error); - -/** Delete and free up memory used by a mpg123_pars data structure - * \param mp parameter handle - */ -MPG123_EXPORT void mpg123_delete_pars(mpg123_pars* mp); - -/** Configure mpg123 parameters to accept no output format at all, - * use before specifying supported formats with mpg123_format - * \param mp parameter handle - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_fmt_none(mpg123_pars *mp); - -/** Configure mpg123 parameters to accept all formats - * (also any custom rate you may set) -- this is default. - * \param mp parameter handle - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_fmt_all(mpg123_pars *mp); - -/** Set the audio format support of a mpg123_pars in detail: - * \param mp parameter handle - * \param rate The sample rate value (in Hertz). - * \param channels A combination of MPG123_STEREO and MPG123_MONO. - * \param encodings A combination of accepted encodings for rate and channels, - * p.ex MPG123_ENC_SIGNED16|MPG123_ENC_ULAW_8 (or 0 for no - * support). - * \return MPG123_OK on success -*/ -MPG123_EXPORT int mpg123_fmt(mpg123_pars *mp -, long rate, int channels, int encodings); - -/** Set the audio format support of a mpg123_pars in detail: - * \param mp parameter handle - * \param rate The sample rate value (in Hertz). Special value 0 means - * all rates (reason for this variant of mpg123_fmt). - * \param channels A combination of MPG123_STEREO and MPG123_MONO. - * \param encodings A combination of accepted encodings for rate and channels, - * p.ex MPG123_ENC_SIGNED16|MPG123_ENC_ULAW_8 (or 0 for no - * support). - * \return MPG123_OK on success -*/ -MPG123_EXPORT int mpg123_fmt2(mpg123_pars *mp -, long rate, int channels, int encodings); - -/** Check to see if a specific format at a specific rate is supported - * by mpg123_pars. - * \param mp parameter handle - * \param rate sampling rate - * \param encoding encoding - * \return 0 for no support (that includes invalid parameters), MPG123_STEREO, - * MPG123_MONO or MPG123_STEREO|MPG123_MONO. */ -MPG123_EXPORT int mpg123_fmt_support(mpg123_pars *mp, long rate, int encoding); - -#ifdef MPG123_ENUM_API -/** Set a specific parameter in a par handle. - * - * Note that this name is mapped to mpg123_par2() instead unless - * MPG123_ENUM_API is defined. - * - * \param mp parameter handle - * \param type parameter choice - * \param value integer value - * \param fvalue floating point value - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_par( mpg123_pars *mp -, enum mpg123_parms type, long value, double fvalue ); -#endif - -/** Set a specific parameter in a par handle. No enums. - * - * This is actually called instead of mpg123_par() - * unless MPG123_ENUM_API is defined. - * - * \param mp parameter handle - * \param type parameter choice (enum mpg123_parms) - * \param value integer value - * \param fvalue floating point value - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_par2( mpg123_pars *mp -, int type, long value, double fvalue ); - -#ifdef MPG123_ENUM_API -/** Get a specific parameter from a par handle. - * - * Note that this name is mapped to mpg123_getpar2() instead unless - * MPG123_ENUM_API is defined. - * - * \param mp parameter handle - * \param type parameter choice - * \param value integer value return address - * \param fvalue floating point value return address - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_getpar( mpg123_pars *mp -, enum mpg123_parms type, long *value, double *fvalue ); -#endif - -/** Get a specific parameter from a par handle. No enums. - * - * This is actually called instead of mpg123_getpar() - * unless MPG123_ENUM_API is defined. - * - * \param mp parameter handle - * \param type parameter choice (enum mpg123_parms) - * \param value integer value return address - * \param fvalue floating point value return address - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_getpar2( mpg123_pars *mp -, int type, long *value, double *fvalue ); - -/** @} */ - - -/** \defgroup mpg123_lowio mpg123 low level I/O - * You may want to do tricky stuff with I/O that does not work with mpg123's default file access or you want to make it decode into your own pocket... - * - * @{ */ - -/** Replace default internal buffer with user-supplied buffer. - * Instead of working on it's own private buffer, mpg123 will directly use the one you provide for storing decoded audio. - * Note that the required buffer size could be bigger than expected from output - * encoding if libmpg123 has to convert from primary decoder output (p.ex. 32 bit - * storage for 24 bit output). - * - * Note: The type of data changed to a void pointer in mpg123 1.26.0 - * (API version 45). - * - * \param mh handle - * \param data pointer to user buffer - * \param size of buffer in bytes - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_replace_buffer(mpg123_handle *mh -, void *data, size_t size); - -/** The max size of one frame's decoded output with current settings. - * Use that to determine an appropriate minimum buffer size for decoding one frame. - * \param mh handle - * \return maximum decoded data size in bytes - */ -MPG123_EXPORT size_t mpg123_outblock(mpg123_handle *mh); - -/** Replace low-level stream access functions; read and lseek as known in POSIX. - * You can use this to make any fancy file opening/closing yourself, - * using mpg123_open_fd() to set the file descriptor for your read/lseek - * (doesn't need to be a "real" file descriptor...). - * Setting a function to NULL means that the default internal read is - * used (active from next mpg123_open call on). - * Note: As it would be troublesome to mess with this while having a file open, - * this implies mpg123_close(). - * \param mh handle - * \param r_read callback for reading (behaviour like POSIX read) - * \param r_lseek callback for seeking (like POSIX lseek) - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_replace_reader( mpg123_handle *mh -, mpg123_ssize_t (*r_read) (int, void *, size_t) -, off_t (*r_lseek)(int, off_t, int) -); - -/** Replace I/O functions with your own ones operating on some kind of - * handle instead of integer descriptors. - * The handle is a void pointer, so you can pass any data you want... - * mpg123_open_handle() is the call you make to use the I/O defined here. - * There is no fallback to internal read/seek here. - * Note: As it would be troublesome to mess with this while having a file open, - * this mpg123_close() is implied here. - * \param mh handle - * \param r_read callback for reading (behaviour like POSIX read) - * \param r_lseek callback for seeking (like POSIX lseek) - * \param cleanup A callback to clean up an I/O handle on mpg123_close, - * can be NULL for none (you take care of cleaning your handles). - * \return MPG123_OK on success - */ -MPG123_EXPORT int mpg123_replace_reader_handle( mpg123_handle *mh -, mpg123_ssize_t (*r_read) (void *, void *, size_t) -, off_t (*r_lseek)(void *, off_t, int) -, void (*cleanup)(void*) ); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libs/include/opus/opus.h b/libs/include/opus/opus.h index d282f21d..eadeda75 100644 --- a/libs/include/opus/opus.h +++ b/libs/include/opus/opus.h @@ -103,7 +103,7 @@ extern "C" { * @endcode * * where opus_encoder_get_size() returns the required size for the encoder state. Note that - * future versions of this code may change the size, so no assuptions should be made about it. + * future versions of this code may change the size, so no assumptions should be made about it. * * The encoder state is always continuous in memory and only a shallow copy is sufficient * to copy it (e.g. memcpy()) @@ -198,7 +198,7 @@ OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_encoder_get_size(int channels); * This must be one of 8000, 12000, 16000, * 24000, or 48000. * @param [in] channels int: Number of channels (1 or 2) in input signal - * @param [in] application int: Coding mode (@ref OPUS_APPLICATION_VOIP/@ref OPUS_APPLICATION_AUDIO/@ref OPUS_APPLICATION_RESTRICTED_LOWDELAY) + * @param [in] application int: Coding mode (one of @ref OPUS_APPLICATION_VOIP, @ref OPUS_APPLICATION_AUDIO, or @ref OPUS_APPLICATION_RESTRICTED_LOWDELAY) * @param [out] error int*: @ref opus_errorcodes * @note Regardless of the sampling rate and number channels selected, the Opus encoder * can switch to a lower audio bandwidth or number of channels if the bitrate @@ -222,7 +222,7 @@ OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusEncoder *opus_encoder_create( * This must be one of 8000, 12000, 16000, * 24000, or 48000. * @param [in] channels int: Number of channels (1 or 2) in input signal - * @param [in] application int: Coding mode (OPUS_APPLICATION_VOIP/OPUS_APPLICATION_AUDIO/OPUS_APPLICATION_RESTRICTED_LOWDELAY) + * @param [in] application int: Coding mode (one of OPUS_APPLICATION_VOIP, OPUS_APPLICATION_AUDIO, or OPUS_APPLICATION_RESTRICTED_LOWDELAY) * @retval #OPUS_OK Success or @ref opus_errorcodes */ OPUS_EXPORT int opus_encoder_init( @@ -357,7 +357,7 @@ OPUS_EXPORT int opus_encoder_ctl(OpusEncoder *st, int request, ...) OPUS_ARG_NON * error = opus_decoder_init(dec, Fs, channels); * @endcode * where opus_decoder_get_size() returns the required size for the decoder state. Note that - * future versions of this code may change the size, so no assuptions should be made about it. + * future versions of this code may change the size, so no assumptions should be made about it. * * The decoder state is always continuous in memory and only a shallow copy is sufficient * to copy it (e.g. memcpy()) @@ -398,6 +398,21 @@ OPUS_EXPORT int opus_encoder_ctl(OpusEncoder *st, int request, ...) OPUS_ARG_NON */ typedef struct OpusDecoder OpusDecoder; +/** Opus DRED decoder. + * This contains the complete state of an Opus DRED decoder. + * It is position independent and can be freely copied. + * @see opus_dred_decoder_create,opus_dred_decoder_init + */ +typedef struct OpusDREDDecoder OpusDREDDecoder; + + +/** Opus DRED state. + * This contains the complete state of an Opus DRED packet. + * It is position independent and can be freely copied. + * @see opus_dred_create,opus_dred_init + */ +typedef struct OpusDRED OpusDRED; + /** Gets the size of an OpusDecoder structure. * @param [in] channels int: Number of channels. * This must be 1 or 2. @@ -511,6 +526,101 @@ OPUS_EXPORT int opus_decoder_ctl(OpusDecoder *st, int request, ...) OPUS_ARG_NON */ OPUS_EXPORT void opus_decoder_destroy(OpusDecoder *st); +/** Gets the size of an OpusDREDDecoder structure. + * @returns The size in bytes. + */ +OPUS_EXPORT int opus_dred_decoder_get_size(void); + +/** Allocates and initializes an OpusDREDDecoder state. + * @param [out] error int*: #OPUS_OK Success or @ref opus_errorcodes + */ +OPUS_EXPORT OpusDREDDecoder *opus_dred_decoder_create(int *error); + +/** Initializes an OpusDREDDecoder state. + * @param[in] dec OpusDREDDecoder*: State to be initialized. + */ +OPUS_EXPORT int opus_dred_decoder_init(OpusDREDDecoder *dec); + +/** Frees an OpusDREDDecoder allocated by opus_dred_decoder_create(). + * @param[in] dec OpusDREDDecoder*: State to be freed. + */ +OPUS_EXPORT void opus_dred_decoder_destroy(OpusDREDDecoder *dec); + +/** Perform a CTL function on an Opus DRED decoder. + * + * Generally the request and subsequent arguments are generated + * by a convenience macro. + * @param dred_dec OpusDREDDecoder*: DRED Decoder state. + * @param request This and all remaining parameters should be replaced by one + * of the convenience macros in @ref opus_genericctls or + * @ref opus_decoderctls. + * @see opus_genericctls + * @see opus_decoderctls + */ +OPUS_EXPORT int opus_dred_decoder_ctl(OpusDREDDecoder *dred_dec, int request, ...); + +/** Gets the size of an OpusDRED structure. + * @returns The size in bytes. + */ +OPUS_EXPORT int opus_dred_get_size(void); + +/** Allocates and initializes a DRED state. + * @param [out] error int*: #OPUS_OK Success or @ref opus_errorcodes + */ +OPUS_EXPORT OpusDRED *opus_dred_alloc(int *error); + +/** Frees an OpusDRED allocated by opus_dred_create(). + * @param[in] dec OpusDRED*: State to be freed. + */ +OPUS_EXPORT void opus_dred_free(OpusDRED *dec); + +/** Decode an Opus DRED packet. + * @param [in] dred_dec OpusDRED*: DRED Decoder state + * @param [in] dred OpusDRED*: DRED state + * @param [in] data char*: Input payload + * @param [in] len opus_int32: Number of bytes in payload + * @param [in] max_dred_samples opus_int32: Maximum number of DRED samples that may be needed (if available in the packet). + * @param [in] sampling_rate opus_int32: Sampling rate used for max_dred_samples argument. Needs not match the actual sampling rate of the decoder. + * @param [out] dred_end opus_int32*: Number of non-encoded (silence) samples between the DRED timestamp and the last DRED sample. + * @param [in] defer_processing int: Flag (0 or 1). If set to one, the CPU-intensive part of the DRED decoding is deferred until opus_dred_process() is called. + * @returns Offset (positive) of the first decoded DRED samples, zero if no DRED is present, or @ref opus_errorcodes + */ +OPUS_EXPORT int opus_dred_parse(OpusDREDDecoder *dred_dec, OpusDRED *dred, const unsigned char *data, opus_int32 len, opus_int32 max_dred_samples, opus_int32 sampling_rate, int *dred_end, int defer_processing) OPUS_ARG_NONNULL(1); + +/** Finish decoding an Opus DRED packet. The function only needs to be called if opus_dred_parse() was called with defer_processing=1. + * The source and destination will often be the same DRED state. + * @param [in] dred_dec OpusDRED*: DRED Decoder state + * @param [in] src OpusDRED*: Source DRED state to start the processing from. + * @param [out] dst OpusDRED*: Destination DRED state to store the updated state after processing. + * @returns @ref opus_errorcodes + */ +OPUS_EXPORT int opus_dred_process(OpusDREDDecoder *dred_dec, const OpusDRED *src, OpusDRED *dst); + +/** Decode audio from an Opus DRED packet with floating point output. + * @param [in] st OpusDecoder*: Decoder state + * @param [in] dred OpusDRED*: DRED state + * @param [in] dred_offset opus_int32: position of the redundancy to decode (in samples before the beginning of the real audio data in the packet). + * @param [out] pcm opus_int16*: Output signal (interleaved if 2 channels). length + * is frame_size*channels*sizeof(opus_int16) + * @param [in] frame_size Number of samples per channel to decode in \a pcm. + * frame_size must be a multiple of 2.5 ms. + * @returns Number of decoded samples or @ref opus_errorcodes + */ +OPUS_EXPORT int opus_decoder_dred_decode(OpusDecoder *st, const OpusDRED *dred, opus_int32 dred_offset, opus_int16 *pcm, opus_int32 frame_size); + +/** Decode audio from an Opus DRED packet with floating point output. + * @param [in] st OpusDecoder*: Decoder state + * @param [in] dred OpusDRED*: DRED state + * @param [in] dred_offset opus_int32: position of the redundancy to decode (in samples before the beginning of the real audio data in the packet). + * @param [out] pcm float*: Output signal (interleaved if 2 channels). length + * is frame_size*channels*sizeof(float) + * @param [in] frame_size Number of samples per channel to decode in \a pcm. + * frame_size must be a multiple of 2.5 ms. + * @returns Number of decoded samples or @ref opus_errorcodes + */ +OPUS_EXPORT int opus_decoder_dred_decode_float(OpusDecoder *st, const OpusDRED *dred, opus_int32 dred_offset, float *pcm, opus_int32 frame_size); + + /** Parse an opus packet into one or more frames. * Opus_decode will perform this operation internally so most applications do * not need to use this function. @@ -583,6 +693,14 @@ OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_frames(const unsigned */ OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_samples(const unsigned char packet[], opus_int32 len, opus_int32 Fs) OPUS_ARG_NONNULL(1); +/** Checks whether an Opus packet has LBRR. + * @param [in] packet char*: Opus packet + * @param [in] len opus_int32: Length of packet + * @returns 1 is LBRR is present, 0 otherwise + * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_has_lbrr(const unsigned char packet[], opus_int32 len); + /** Gets the number of samples of an Opus packet. * @param [in] dec OpusDecoder*: Decoder state * @param [in] packet char*: Opus packet diff --git a/libs/include/opus/opus_defines.h b/libs/include/opus/opus_defines.h index d141418b..cd8f4dde 100644 --- a/libs/include/opus/opus_defines.h +++ b/libs/include/opus/opus_defines.h @@ -64,7 +64,7 @@ extern "C" { /**Export control for opus functions */ #ifndef OPUS_EXPORT -# if defined(WIN32) +# if defined(_WIN32) # if defined(OPUS_BUILD) && defined(DLL_EXPORT) # define OPUS_EXPORT __declspec(dllexport) # else @@ -169,15 +169,32 @@ extern "C" { #define OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST 4046 #define OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST 4047 #define OPUS_GET_IN_DTX_REQUEST 4049 +#define OPUS_SET_DRED_DURATION_REQUEST 4050 +#define OPUS_GET_DRED_DURATION_REQUEST 4051 +#define OPUS_SET_DNN_BLOB_REQUEST 4052 +/*#define OPUS_GET_DNN_BLOB_REQUEST 4053 */ /** Defines for the presence of extended APIs. */ #define OPUS_HAVE_OPUS_PROJECTION_H /* Macros to trigger compilation errors when the wrong types are provided to a CTL */ #define __opus_check_int(x) (((void)((x) == (opus_int32)0)), (opus_int32)(x)) + +#ifdef DISABLE_PTR_CHECK +/* Disable checks to prevent ubsan from complaining about NULL checks + in test_opus_api. */ +#define __opus_check_int_ptr(ptr) (ptr) +#define __opus_check_uint_ptr(ptr) (ptr) +#define __opus_check_uint8_ptr(ptr) (ptr) +#define __opus_check_val16_ptr(ptr) (ptr) +#define __opus_check_void_ptr(ptr) (ptr) +#else #define __opus_check_int_ptr(ptr) ((ptr) + ((ptr) - (opus_int32*)(ptr))) #define __opus_check_uint_ptr(ptr) ((ptr) + ((ptr) - (opus_uint32*)(ptr))) +#define __opus_check_uint8_ptr(ptr) ((ptr) + ((ptr) - (opus_uint8*)(ptr))) #define __opus_check_val16_ptr(ptr) ((ptr) + ((ptr) - (opus_val16*)(ptr))) +#define __opus_check_void_ptr(x) ((void)((void *)0 == (x)), (x)) +#endif /** @endcond */ /** @defgroup opus_ctlvalues Pre-defined values for CTL interface @@ -482,7 +499,8 @@ extern "C" { * @param[in] x opus_int32: Allowed values: *
*
0
Disable inband FEC (default).
- *
1
Enable inband FEC.
+ *
1
Inband FEC enabled. If the packet loss rate is sufficiently high, Opus will automatically switch to SILK even at high rates to enable use of that FEC.
+ *
2
Inband FEC enabled, but does not necessarily switch to SILK if we have music.
*
* @hideinitializer */ #define OPUS_SET_INBAND_FEC(x) OPUS_SET_INBAND_FEC_REQUEST, __opus_check_int(x) @@ -491,7 +509,8 @@ extern "C" { * @param[out] x opus_int32 *: Returns one of the following values: *
*
0
Inband FEC disabled (default).
- *
1
Inband FEC enabled.
+ *
1
Inband FEC enabled. If the packet loss rate is sufficiently high, Opus will automatically switch to SILK even at high rates to enable use of that FEC.
+ *
2
Inband FEC enabled, but does not necessarily switch to SILK if we have music.
*
* @hideinitializer */ #define OPUS_GET_INBAND_FEC(x) OPUS_GET_INBAND_FEC_REQUEST, __opus_check_int_ptr(x) @@ -618,6 +637,18 @@ extern "C" { * @hideinitializer */ #define OPUS_GET_PREDICTION_DISABLED(x) OPUS_GET_PREDICTION_DISABLED_REQUEST, __opus_check_int_ptr(x) +/** If non-zero, enables Deep Redundancy (DRED) and use the specified maximum number of 10-ms redundant frames + * @hideinitializer */ +#define OPUS_SET_DRED_DURATION(x) OPUS_SET_DRED_DURATION_REQUEST, __opus_check_int(x) +/** Gets the encoder's configured Deep Redundancy (DRED) maximum number of frames. + * @hideinitializer */ +#define OPUS_GET_DRED_DURATION(x) OPUS_GET_DRED_DURATION_REQUEST, __opus_check_int_ptr(x) + +/** Provide external DNN weights from binary object (only when explicitly built without the weights) + * @hideinitializer */ +#define OPUS_SET_DNN_BLOB(data, len) OPUS_SET_DNN_BLOB_REQUEST, __opus_check_void_ptr(data), __opus_check_int(len) + + /**@}*/ /** @defgroup opus_genericctls Generic CTLs diff --git a/libs/include/opus/opus_multistream.h b/libs/include/opus/opus_multistream.h index babcee69..824cc55a 100644 --- a/libs/include/opus/opus_multistream.h +++ b/libs/include/opus/opus_multistream.h @@ -143,7 +143,7 @@ extern "C" { * Vorbis * channel ordering. A decoder may wish to apply an additional permutation * to the mapping the encoder used to achieve a different output channel - * order (e.g. for outputing in WAV order). + * order (e.g. for outputting in WAV order). * * Each multistream packet contains an Opus packet for each stream, and all of * the Opus packets in a single multistream packet must have the same diff --git a/libs/include/turbojpeg/jconfig.h b/libs/include/turbojpeg/jconfig.h deleted file mode 100644 index 04ca8da3..00000000 --- a/libs/include/turbojpeg/jconfig.h +++ /dev/null @@ -1,74 +0,0 @@ -/* jconfig.h. Generated from jconfig.h.in by configure. */ -/* Version ID for the JPEG library. - * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60". - */ -#define JPEG_LIB_VERSION 62 - -/* libjpeg-turbo version */ -#define LIBJPEG_TURBO_VERSION 1.5.3 - -/* libjpeg-turbo version in integer form */ -#define LIBJPEG_TURBO_VERSION_NUMBER 1005003 - -/* Support arithmetic encoding */ -#define C_ARITH_CODING_SUPPORTED 1 - -/* Support arithmetic decoding */ -#define D_ARITH_CODING_SUPPORTED 1 - -/* - * Define BITS_IN_JSAMPLE as either - * 8 for 8-bit sample values (the usual setting) - * 12 for 12-bit sample values - * Only 8 and 12 are legal data precisions for lossy JPEG according to the - * JPEG standard, and the IJG code does not support anything else! - * We do not support run-time selection of data precision, sorry. - */ - -#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */ - -/* Define to 1 if you have the header file. */ -#define HAVE_LOCALE_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDDEF_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define to 1 if the system has the type `unsigned char'. */ -#define HAVE_UNSIGNED_CHAR 1 - -/* Define to 1 if the system has the type `unsigned short'. */ -#define HAVE_UNSIGNED_SHORT 1 - -/* Compiler does not support pointers to undefined structures. */ -/* #undef INCOMPLETE_TYPES_BROKEN */ - -/* Support in-memory source/destination managers */ -#define MEM_SRCDST_SUPPORTED 1 - -/* Define if you have BSD-like bzero and bcopy in rather than - memset/memcpy in . */ -/* #undef NEED_BSD_STRINGS */ - -/* Define if you need to include to get size_t. */ -#define NEED_SYS_TYPES_H 1 - -/* Define if your (broken) compiler shifts signed values as if they were - unsigned. */ -/* #undef RIGHT_SHIFT_IS_UNSIGNED */ - -/* Use accelerated SIMD routines. */ -/* #undef WITH_SIMD */ - -/* Define to 1 if type `char' is unsigned and you are not using gcc. */ -#ifndef __CHAR_UNSIGNED__ -/* # undef __CHAR_UNSIGNED__ */ -#endif - -/* Define to empty if `const' does not conform to ANSI C. */ -/* #undef const */ - -/* Define to `unsigned int' if does not define. */ -/* #undef size_t */ diff --git a/libs/include/turbojpeg/turbojpeg.h b/libs/include/turbojpeg/turbojpeg.h deleted file mode 100644 index 307dc6f0..00000000 --- a/libs/include/turbojpeg/turbojpeg.h +++ /dev/null @@ -1,1545 +0,0 @@ -/* - * Copyright (C)2009-2015, 2017 D. R. Commander. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - Neither the name of the libjpeg-turbo Project nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __TURBOJPEG_H__ -#define __TURBOJPEG_H__ - -#if defined(_WIN32) && defined(DLLDEFINE) -#define DLLEXPORT __declspec(dllexport) -#else -#define DLLEXPORT -#endif -#define DLLCALL - - -/** - * @addtogroup TurboJPEG - * TurboJPEG API. This API provides an interface for generating, decoding, and - * transforming planar YUV and JPEG images in memory. - * - * @anchor YUVnotes - * YUV Image Format Notes - * ---------------------- - * Technically, the JPEG format uses the YCbCr colorspace (which is technically - * not a colorspace but a color transform), but per the convention of the - * digital video community, the TurboJPEG API uses "YUV" to refer to an image - * format consisting of Y, Cb, and Cr image planes. - * - * Each plane is simply a 2D array of bytes, each byte representing the value - * of one of the components (Y, Cb, or Cr) at a particular location in the - * image. The width and height of each plane are determined by the image - * width, height, and level of chrominance subsampling. The luminance plane - * width is the image width padded to the nearest multiple of the horizontal - * subsampling factor (2 in the case of 4:2:0 and 4:2:2, 4 in the case of - * 4:1:1, 1 in the case of 4:4:4 or grayscale.) Similarly, the luminance plane - * height is the image height padded to the nearest multiple of the vertical - * subsampling factor (2 in the case of 4:2:0 or 4:4:0, 1 in the case of 4:4:4 - * or grayscale.) This is irrespective of any additional padding that may be - * specified as an argument to the various YUV functions. The chrominance - * plane width is equal to the luminance plane width divided by the horizontal - * subsampling factor, and the chrominance plane height is equal to the - * luminance plane height divided by the vertical subsampling factor. - * - * For example, if the source image is 35 x 35 pixels and 4:2:2 subsampling is - * used, then the luminance plane would be 36 x 35 bytes, and each of the - * chrominance planes would be 18 x 35 bytes. If you specify a line padding of - * 4 bytes on top of this, then the luminance plane would be 36 x 35 bytes, and - * each of the chrominance planes would be 20 x 35 bytes. - * - * @{ - */ - - -/** - * The number of chrominance subsampling options - */ -#define TJ_NUMSAMP 6 - -/** - * Chrominance subsampling options. - * When pixels are converted from RGB to YCbCr (see #TJCS_YCbCr) or from CMYK - * to YCCK (see #TJCS_YCCK) as part of the JPEG compression process, some of - * the Cb and Cr (chrominance) components can be discarded or averaged together - * to produce a smaller image with little perceptible loss of image clarity - * (the human eye is more sensitive to small changes in brightness than to - * small changes in color.) This is called "chrominance subsampling". - */ -enum TJSAMP -{ - /** - * 4:4:4 chrominance subsampling (no chrominance subsampling). The JPEG or - * YUV image will contain one chrominance component for every pixel in the - * source image. - */ - TJSAMP_444=0, - /** - * 4:2:2 chrominance subsampling. The JPEG or YUV image will contain one - * chrominance component for every 2x1 block of pixels in the source image. - */ - TJSAMP_422, - /** - * 4:2:0 chrominance subsampling. The JPEG or YUV image will contain one - * chrominance component for every 2x2 block of pixels in the source image. - */ - TJSAMP_420, - /** - * Grayscale. The JPEG or YUV image will contain no chrominance components. - */ - TJSAMP_GRAY, - /** - * 4:4:0 chrominance subsampling. The JPEG or YUV image will contain one - * chrominance component for every 1x2 block of pixels in the source image. - * - * @note 4:4:0 subsampling is not fully accelerated in libjpeg-turbo. - */ - TJSAMP_440, - /** - * 4:1:1 chrominance subsampling. The JPEG or YUV image will contain one - * chrominance component for every 4x1 block of pixels in the source image. - * JPEG images compressed with 4:1:1 subsampling will be almost exactly the - * same size as those compressed with 4:2:0 subsampling, and in the - * aggregate, both subsampling methods produce approximately the same - * perceptual quality. However, 4:1:1 is better able to reproduce sharp - * horizontal features. - * - * @note 4:1:1 subsampling is not fully accelerated in libjpeg-turbo. - */ - TJSAMP_411 -}; - -/** - * MCU block width (in pixels) for a given level of chrominance subsampling. - * MCU block sizes: - * - 8x8 for no subsampling or grayscale - * - 16x8 for 4:2:2 - * - 8x16 for 4:4:0 - * - 16x16 for 4:2:0 - * - 32x8 for 4:1:1 - */ -static const int tjMCUWidth[TJ_NUMSAMP] = {8, 16, 16, 8, 8, 32}; - -/** - * MCU block height (in pixels) for a given level of chrominance subsampling. - * MCU block sizes: - * - 8x8 for no subsampling or grayscale - * - 16x8 for 4:2:2 - * - 8x16 for 4:4:0 - * - 16x16 for 4:2:0 - * - 32x8 for 4:1:1 - */ -static const int tjMCUHeight[TJ_NUMSAMP] = {8, 8, 16, 8, 16, 8}; - - -/** - * The number of pixel formats - */ -#define TJ_NUMPF 12 - -/** - * Pixel formats - */ -enum TJPF -{ - /** - * RGB pixel format. The red, green, and blue components in the image are - * stored in 3-byte pixels in the order R, G, B from lowest to highest byte - * address within each pixel. - */ - TJPF_RGB=0, - /** - * BGR pixel format. The red, green, and blue components in the image are - * stored in 3-byte pixels in the order B, G, R from lowest to highest byte - * address within each pixel. - */ - TJPF_BGR, - /** - * RGBX pixel format. The red, green, and blue components in the image are - * stored in 4-byte pixels in the order R, G, B from lowest to highest byte - * address within each pixel. The X component is ignored when compressing - * and undefined when decompressing. - */ - TJPF_RGBX, - /** - * BGRX pixel format. The red, green, and blue components in the image are - * stored in 4-byte pixels in the order B, G, R from lowest to highest byte - * address within each pixel. The X component is ignored when compressing - * and undefined when decompressing. - */ - TJPF_BGRX, - /** - * XBGR pixel format. The red, green, and blue components in the image are - * stored in 4-byte pixels in the order R, G, B from highest to lowest byte - * address within each pixel. The X component is ignored when compressing - * and undefined when decompressing. - */ - TJPF_XBGR, - /** - * XRGB pixel format. The red, green, and blue components in the image are - * stored in 4-byte pixels in the order B, G, R from highest to lowest byte - * address within each pixel. The X component is ignored when compressing - * and undefined when decompressing. - */ - TJPF_XRGB, - /** - * Grayscale pixel format. Each 1-byte pixel represents a luminance - * (brightness) level from 0 to 255. - */ - TJPF_GRAY, - /** - * RGBA pixel format. This is the same as @ref TJPF_RGBX, except that when - * decompressing, the X component is guaranteed to be 0xFF, which can be - * interpreted as an opaque alpha channel. - */ - TJPF_RGBA, - /** - * BGRA pixel format. This is the same as @ref TJPF_BGRX, except that when - * decompressing, the X component is guaranteed to be 0xFF, which can be - * interpreted as an opaque alpha channel. - */ - TJPF_BGRA, - /** - * ABGR pixel format. This is the same as @ref TJPF_XBGR, except that when - * decompressing, the X component is guaranteed to be 0xFF, which can be - * interpreted as an opaque alpha channel. - */ - TJPF_ABGR, - /** - * ARGB pixel format. This is the same as @ref TJPF_XRGB, except that when - * decompressing, the X component is guaranteed to be 0xFF, which can be - * interpreted as an opaque alpha channel. - */ - TJPF_ARGB, - /** - * CMYK pixel format. Unlike RGB, which is an additive color model used - * primarily for display, CMYK (Cyan/Magenta/Yellow/Key) is a subtractive - * color model used primarily for printing. In the CMYK color model, the - * value of each color component typically corresponds to an amount of cyan, - * magenta, yellow, or black ink that is applied to a white background. In - * order to convert between CMYK and RGB, it is necessary to use a color - * management system (CMS.) A CMS will attempt to map colors within the - * printer's gamut to perceptually similar colors in the display's gamut and - * vice versa, but the mapping is typically not 1:1 or reversible, nor can it - * be defined with a simple formula. Thus, such a conversion is out of scope - * for a codec library. However, the TurboJPEG API allows for compressing - * CMYK pixels into a YCCK JPEG image (see #TJCS_YCCK) and decompressing YCCK - * JPEG images into CMYK pixels. - */ - TJPF_CMYK -}; - - -/** - * Red offset (in bytes) for a given pixel format. This specifies the number - * of bytes that the red component is offset from the start of the pixel. For - * instance, if a pixel of format TJ_BGRX is stored in char pixel[], - * then the red component will be pixel[tjRedOffset[TJ_BGRX]]. - */ -static const int tjRedOffset[TJ_NUMPF] = {0, 2, 0, 2, 3, 1, 0, 0, 2, 3, 1, -1}; -/** - * Green offset (in bytes) for a given pixel format. This specifies the number - * of bytes that the green component is offset from the start of the pixel. - * For instance, if a pixel of format TJ_BGRX is stored in - * char pixel[], then the green component will be - * pixel[tjGreenOffset[TJ_BGRX]]. - */ -static const int tjGreenOffset[TJ_NUMPF] = {1, 1, 1, 1, 2, 2, 0, 1, 1, 2, 2, -1}; -/** - * Blue offset (in bytes) for a given pixel format. This specifies the number - * of bytes that the Blue component is offset from the start of the pixel. For - * instance, if a pixel of format TJ_BGRX is stored in char pixel[], - * then the blue component will be pixel[tjBlueOffset[TJ_BGRX]]. - */ -static const int tjBlueOffset[TJ_NUMPF] = {2, 0, 2, 0, 1, 3, 0, 2, 0, 1, 3, -1}; -/** - * Pixel size (in bytes) for a given pixel format. - */ -static const int tjPixelSize[TJ_NUMPF] = {3, 3, 4, 4, 4, 4, 1, 4, 4, 4, 4, 4}; - - -/** - * The number of JPEG colorspaces - */ -#define TJ_NUMCS 5 - -/** - * JPEG colorspaces - */ -enum TJCS -{ - /** - * RGB colorspace. When compressing the JPEG image, the R, G, and B - * components in the source image are reordered into image planes, but no - * colorspace conversion or subsampling is performed. RGB JPEG images can be - * decompressed to any of the extended RGB pixel formats or grayscale, but - * they cannot be decompressed to YUV images. - */ - TJCS_RGB=0, - /** - * YCbCr colorspace. YCbCr is not an absolute colorspace but rather a - * mathematical transformation of RGB designed solely for storage and - * transmission. YCbCr images must be converted to RGB before they can - * actually be displayed. In the YCbCr colorspace, the Y (luminance) - * component represents the black & white portion of the original image, and - * the Cb and Cr (chrominance) components represent the color portion of the - * original image. Originally, the analog equivalent of this transformation - * allowed the same signal to drive both black & white and color televisions, - * but JPEG images use YCbCr primarily because it allows the color data to be - * optionally subsampled for the purposes of reducing bandwidth or disk - * space. YCbCr is the most common JPEG colorspace, and YCbCr JPEG images - * can be compressed from and decompressed to any of the extended RGB pixel - * formats or grayscale, or they can be decompressed to YUV planar images. - */ - TJCS_YCbCr, - /** - * Grayscale colorspace. The JPEG image retains only the luminance data (Y - * component), and any color data from the source image is discarded. - * Grayscale JPEG images can be compressed from and decompressed to any of - * the extended RGB pixel formats or grayscale, or they can be decompressed - * to YUV planar images. - */ - TJCS_GRAY, - /** - * CMYK colorspace. When compressing the JPEG image, the C, M, Y, and K - * components in the source image are reordered into image planes, but no - * colorspace conversion or subsampling is performed. CMYK JPEG images can - * only be decompressed to CMYK pixels. - */ - TJCS_CMYK, - /** - * YCCK colorspace. YCCK (AKA "YCbCrK") is not an absolute colorspace but - * rather a mathematical transformation of CMYK designed solely for storage - * and transmission. It is to CMYK as YCbCr is to RGB. CMYK pixels can be - * reversibly transformed into YCCK, and as with YCbCr, the chrominance - * components in the YCCK pixels can be subsampled without incurring major - * perceptual loss. YCCK JPEG images can only be compressed from and - * decompressed to CMYK pixels. - */ - TJCS_YCCK -}; - - -/** - * The uncompressed source/destination image is stored in bottom-up (Windows, - * OpenGL) order, not top-down (X11) order. - */ -#define TJFLAG_BOTTOMUP 2 -/** - * When decompressing an image that was compressed using chrominance - * subsampling, use the fastest chrominance upsampling algorithm available in - * the underlying codec. The default is to use smooth upsampling, which - * creates a smooth transition between neighboring chrominance components in - * order to reduce upsampling artifacts in the decompressed image. - */ -#define TJFLAG_FASTUPSAMPLE 256 -/** - * Disable buffer (re)allocation. If passed to one of the JPEG compression or - * transform functions, this flag will cause those functions to generate an - * error if the JPEG image buffer is invalid or too small rather than - * attempting to allocate or reallocate that buffer. This reproduces the - * behavior of earlier versions of TurboJPEG. - */ -#define TJFLAG_NOREALLOC 1024 -/** - * Use the fastest DCT/IDCT algorithm available in the underlying codec. The - * default if this flag is not specified is implementation-specific. For - * example, the implementation of TurboJPEG for libjpeg[-turbo] uses the fast - * algorithm by default when compressing, because this has been shown to have - * only a very slight effect on accuracy, but it uses the accurate algorithm - * when decompressing, because this has been shown to have a larger effect. - */ -#define TJFLAG_FASTDCT 2048 -/** - * Use the most accurate DCT/IDCT algorithm available in the underlying codec. - * The default if this flag is not specified is implementation-specific. For - * example, the implementation of TurboJPEG for libjpeg[-turbo] uses the fast - * algorithm by default when compressing, because this has been shown to have - * only a very slight effect on accuracy, but it uses the accurate algorithm - * when decompressing, because this has been shown to have a larger effect. - */ -#define TJFLAG_ACCURATEDCT 4096 - - -/** - * The number of transform operations - */ -#define TJ_NUMXOP 8 - -/** - * Transform operations for #tjTransform() - */ -enum TJXOP -{ - /** - * Do not transform the position of the image pixels - */ - TJXOP_NONE=0, - /** - * Flip (mirror) image horizontally. This transform is imperfect if there - * are any partial MCU blocks on the right edge (see #TJXOPT_PERFECT.) - */ - TJXOP_HFLIP, - /** - * Flip (mirror) image vertically. This transform is imperfect if there are - * any partial MCU blocks on the bottom edge (see #TJXOPT_PERFECT.) - */ - TJXOP_VFLIP, - /** - * Transpose image (flip/mirror along upper left to lower right axis.) This - * transform is always perfect. - */ - TJXOP_TRANSPOSE, - /** - * Transverse transpose image (flip/mirror along upper right to lower left - * axis.) This transform is imperfect if there are any partial MCU blocks in - * the image (see #TJXOPT_PERFECT.) - */ - TJXOP_TRANSVERSE, - /** - * Rotate image clockwise by 90 degrees. This transform is imperfect if - * there are any partial MCU blocks on the bottom edge (see - * #TJXOPT_PERFECT.) - */ - TJXOP_ROT90, - /** - * Rotate image 180 degrees. This transform is imperfect if there are any - * partial MCU blocks in the image (see #TJXOPT_PERFECT.) - */ - TJXOP_ROT180, - /** - * Rotate image counter-clockwise by 90 degrees. This transform is imperfect - * if there are any partial MCU blocks on the right edge (see - * #TJXOPT_PERFECT.) - */ - TJXOP_ROT270 -}; - - -/** - * This option will cause #tjTransform() to return an error if the transform is - * not perfect. Lossless transforms operate on MCU blocks, whose size depends - * on the level of chrominance subsampling used (see #tjMCUWidth - * and #tjMCUHeight.) If the image's width or height is not evenly divisible - * by the MCU block size, then there will be partial MCU blocks on the right - * and/or bottom edges. It is not possible to move these partial MCU blocks to - * the top or left of the image, so any transform that would require that is - * "imperfect." If this option is not specified, then any partial MCU blocks - * that cannot be transformed will be left in place, which will create - * odd-looking strips on the right or bottom edge of the image. - */ -#define TJXOPT_PERFECT 1 -/** - * This option will cause #tjTransform() to discard any partial MCU blocks that - * cannot be transformed. - */ -#define TJXOPT_TRIM 2 -/** - * This option will enable lossless cropping. See #tjTransform() for more - * information. - */ -#define TJXOPT_CROP 4 -/** - * This option will discard the color data in the input image and produce - * a grayscale output image. - */ -#define TJXOPT_GRAY 8 -/** - * This option will prevent #tjTransform() from outputting a JPEG image for - * this particular transform (this can be used in conjunction with a custom - * filter to capture the transformed DCT coefficients without transcoding - * them.) - */ -#define TJXOPT_NOOUTPUT 16 - - -/** - * Scaling factor - */ -typedef struct -{ - /** - * Numerator - */ - int num; - /** - * Denominator - */ - int denom; -} tjscalingfactor; - -/** - * Cropping region - */ -typedef struct -{ - /** - * The left boundary of the cropping region. This must be evenly divisible - * by the MCU block width (see #tjMCUWidth.) - */ - int x; - /** - * The upper boundary of the cropping region. This must be evenly divisible - * by the MCU block height (see #tjMCUHeight.) - */ - int y; - /** - * The width of the cropping region. Setting this to 0 is the equivalent of - * setting it to the width of the source JPEG image - x. - */ - int w; - /** - * The height of the cropping region. Setting this to 0 is the equivalent of - * setting it to the height of the source JPEG image - y. - */ - int h; -} tjregion; - -/** - * Lossless transform - */ -typedef struct tjtransform -{ - /** - * Cropping region - */ - tjregion r; - /** - * One of the @ref TJXOP "transform operations" - */ - int op; - /** - * The bitwise OR of one of more of the @ref TJXOPT_CROP "transform options" - */ - int options; - /** - * Arbitrary data that can be accessed within the body of the callback - * function - */ - void *data; - /** - * A callback function that can be used to modify the DCT coefficients - * after they are losslessly transformed but before they are transcoded to a - * new JPEG image. This allows for custom filters or other transformations - * to be applied in the frequency domain. - * - * @param coeffs pointer to an array of transformed DCT coefficients. (NOTE: - * this pointer is not guaranteed to be valid once the callback returns, so - * applications wishing to hand off the DCT coefficients to another function - * or library should make a copy of them within the body of the callback.) - * - * @param arrayRegion #tjregion structure containing the width and height of - * the array pointed to by coeffs as well as its offset relative to - * the component plane. TurboJPEG implementations may choose to split each - * component plane into multiple DCT coefficient arrays and call the callback - * function once for each array. - * - * @param planeRegion #tjregion structure containing the width and height of - * the component plane to which coeffs belongs - * - * @param componentID ID number of the component plane to which - * coeffs belongs (Y, Cb, and Cr have, respectively, ID's of 0, 1, - * and 2 in typical JPEG images.) - * - * @param transformID ID number of the transformed image to which - * coeffs belongs. This is the same as the index of the transform - * in the transforms array that was passed to #tjTransform(). - * - * @param transform a pointer to a #tjtransform structure that specifies the - * parameters and/or cropping region for this transform - * - * @return 0 if the callback was successful, or -1 if an error occurred. - */ - int (*customFilter)(short *coeffs, tjregion arrayRegion, - tjregion planeRegion, int componentIndex, int transformIndex, - struct tjtransform *transform); -} tjtransform; - -/** - * TurboJPEG instance handle - */ -typedef void* tjhandle; - - -/** - * Pad the given width to the nearest 32-bit boundary - */ -#define TJPAD(width) (((width)+3)&(~3)) - -/** - * Compute the scaled value of dimension using the given scaling - * factor. This macro performs the integer equivalent of ceil(dimension * - * scalingFactor). - */ -#define TJSCALED(dimension, scalingFactor) ((dimension * scalingFactor.num \ - + scalingFactor.denom - 1) / scalingFactor.denom) - - -#ifdef __cplusplus -extern "C" { -#endif - - -/** - * Create a TurboJPEG compressor instance. - * - * @return a handle to the newly-created instance, or NULL if an error - * occurred (see #tjGetErrorStr().) - */ -DLLEXPORT tjhandle DLLCALL tjInitCompress(void); - - -/** - * Compress an RGB, grayscale, or CMYK image into a JPEG image. - * - * @param handle a handle to a TurboJPEG compressor or transformer instance - * - * @param srcBuf pointer to an image buffer containing RGB, grayscale, or - * CMYK pixels to be compressed - * - * @param width width (in pixels) of the source image - * - * @param pitch bytes per line in the source image. Normally, this should be - * width * #tjPixelSize[pixelFormat] if the image is unpadded, or - * #TJPAD(width * #tjPixelSize[pixelFormat]) if each line of the image - * is padded to the nearest 32-bit boundary, as is the case for Windows - * bitmaps. You can also be clever and use this parameter to skip lines, etc. - * Setting this parameter to 0 is the equivalent of setting it to - * width * #tjPixelSize[pixelFormat]. - * - * @param height height (in pixels) of the source image - * - * @param pixelFormat pixel format of the source image (see @ref TJPF - * "Pixel formats".) - * - * @param jpegBuf address of a pointer to an image buffer that will receive the - * JPEG image. TurboJPEG has the ability to reallocate the JPEG buffer - * to accommodate the size of the JPEG image. Thus, you can choose to: - * -# pre-allocate the JPEG buffer with an arbitrary size using #tjAlloc() and - * let TurboJPEG grow the buffer as needed, - * -# set *jpegBuf to NULL to tell TurboJPEG to allocate the buffer - * for you, or - * -# pre-allocate the buffer to a "worst case" size determined by calling - * #tjBufSize(). This should ensure that the buffer never has to be - * re-allocated (setting #TJFLAG_NOREALLOC guarantees that it won't be.) - * . - * If you choose option 1, *jpegSize should be set to the size of your - * pre-allocated buffer. In any case, unless you have set #TJFLAG_NOREALLOC, - * you should always check *jpegBuf upon return from this function, as - * it may have changed. - * - * @param jpegSize pointer to an unsigned long variable that holds the size of - * the JPEG image buffer. If *jpegBuf points to a pre-allocated - * buffer, then *jpegSize should be set to the size of the buffer. - * Upon return, *jpegSize will contain the size of the JPEG image (in - * bytes.) If *jpegBuf points to a JPEG image buffer that is being - * reused from a previous call to one of the JPEG compression functions, then - * *jpegSize is ignored. - * - * @param jpegSubsamp the level of chrominance subsampling to be used when - * generating the JPEG image (see @ref TJSAMP - * "Chrominance subsampling options".) - * - * @param jpegQual the image quality of the generated JPEG image (1 = worst, - * 100 = best) - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) -*/ -DLLEXPORT int DLLCALL tjCompress2(tjhandle handle, const unsigned char *srcBuf, - int width, int pitch, int height, int pixelFormat, unsigned char **jpegBuf, - unsigned long *jpegSize, int jpegSubsamp, int jpegQual, int flags); - - -/** - * Compress a YUV planar image into a JPEG image. - * - * @param handle a handle to a TurboJPEG compressor or transformer instance - * - * @param srcBuf pointer to an image buffer containing a YUV planar image to be - * compressed. The size of this buffer should match the value returned by - * #tjBufSizeYUV2() for the given image width, height, padding, and level of - * chrominance subsampling. The Y, U (Cb), and V (Cr) image planes should be - * stored sequentially in the source buffer (refer to @ref YUVnotes - * "YUV Image Format Notes".) - * - * @param width width (in pixels) of the source image. If the width is not an - * even multiple of the MCU block width (see #tjMCUWidth), then an intermediate - * buffer copy will be performed within TurboJPEG. - * - * @param pad the line padding used in the source image. For instance, if each - * line in each plane of the YUV image is padded to the nearest multiple of 4 - * bytes, then pad should be set to 4. - * - * @param height height (in pixels) of the source image. If the height is not - * an even multiple of the MCU block height (see #tjMCUHeight), then an - * intermediate buffer copy will be performed within TurboJPEG. - * - * @param subsamp the level of chrominance subsampling used in the source - * image (see @ref TJSAMP "Chrominance subsampling options".) - * - * @param jpegBuf address of a pointer to an image buffer that will receive the - * JPEG image. TurboJPEG has the ability to reallocate the JPEG buffer to - * accommodate the size of the JPEG image. Thus, you can choose to: - * -# pre-allocate the JPEG buffer with an arbitrary size using #tjAlloc() and - * let TurboJPEG grow the buffer as needed, - * -# set *jpegBuf to NULL to tell TurboJPEG to allocate the buffer - * for you, or - * -# pre-allocate the buffer to a "worst case" size determined by calling - * #tjBufSize(). This should ensure that the buffer never has to be - * re-allocated (setting #TJFLAG_NOREALLOC guarantees that it won't be.) - * . - * If you choose option 1, *jpegSize should be set to the size of your - * pre-allocated buffer. In any case, unless you have set #TJFLAG_NOREALLOC, - * you should always check *jpegBuf upon return from this function, as - * it may have changed. - * - * @param jpegSize pointer to an unsigned long variable that holds the size of - * the JPEG image buffer. If *jpegBuf points to a pre-allocated - * buffer, then *jpegSize should be set to the size of the buffer. - * Upon return, *jpegSize will contain the size of the JPEG image (in - * bytes.) If *jpegBuf points to a JPEG image buffer that is being - * reused from a previous call to one of the JPEG compression functions, then - * *jpegSize is ignored. - * - * @param jpegQual the image quality of the generated JPEG image (1 = worst, - * 100 = best) - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) -*/ -DLLEXPORT int DLLCALL tjCompressFromYUV(tjhandle handle, - const unsigned char *srcBuf, int width, int pad, int height, int subsamp, - unsigned char **jpegBuf, unsigned long *jpegSize, int jpegQual, int flags); - - -/** - * Compress a set of Y, U (Cb), and V (Cr) image planes into a JPEG image. - * - * @param handle a handle to a TurboJPEG compressor or transformer instance - * - * @param srcPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes - * (or just a Y plane, if compressing a grayscale image) that contain a YUV - * image to be compressed. These planes can be contiguous or non-contiguous in - * memory. The size of each plane should match the value returned by - * #tjPlaneSizeYUV() for the given image width, height, strides, and level of - * chrominance subsampling. Refer to @ref YUVnotes "YUV Image Format Notes" - * for more details. - * - * @param width width (in pixels) of the source image. If the width is not an - * even multiple of the MCU block width (see #tjMCUWidth), then an intermediate - * buffer copy will be performed within TurboJPEG. - * - * @param strides an array of integers, each specifying the number of bytes per - * line in the corresponding plane of the YUV source image. Setting the stride - * for any plane to 0 is the same as setting it to the plane width (see - * @ref YUVnotes "YUV Image Format Notes".) If strides is NULL, then - * the strides for all planes will be set to their respective plane widths. - * You can adjust the strides in order to specify an arbitrary amount of line - * padding in each plane or to create a JPEG image from a subregion of a larger - * YUV planar image. - * - * @param height height (in pixels) of the source image. If the height is not - * an even multiple of the MCU block height (see #tjMCUHeight), then an - * intermediate buffer copy will be performed within TurboJPEG. - * - * @param subsamp the level of chrominance subsampling used in the source - * image (see @ref TJSAMP "Chrominance subsampling options".) - * - * @param jpegBuf address of a pointer to an image buffer that will receive the - * JPEG image. TurboJPEG has the ability to reallocate the JPEG buffer to - * accommodate the size of the JPEG image. Thus, you can choose to: - * -# pre-allocate the JPEG buffer with an arbitrary size using #tjAlloc() and - * let TurboJPEG grow the buffer as needed, - * -# set *jpegBuf to NULL to tell TurboJPEG to allocate the buffer - * for you, or - * -# pre-allocate the buffer to a "worst case" size determined by calling - * #tjBufSize(). This should ensure that the buffer never has to be - * re-allocated (setting #TJFLAG_NOREALLOC guarantees that it won't be.) - * . - * If you choose option 1, *jpegSize should be set to the size of your - * pre-allocated buffer. In any case, unless you have set #TJFLAG_NOREALLOC, - * you should always check *jpegBuf upon return from this function, as - * it may have changed. - * - * @param jpegSize pointer to an unsigned long variable that holds the size of - * the JPEG image buffer. If *jpegBuf points to a pre-allocated - * buffer, then *jpegSize should be set to the size of the buffer. - * Upon return, *jpegSize will contain the size of the JPEG image (in - * bytes.) If *jpegBuf points to a JPEG image buffer that is being - * reused from a previous call to one of the JPEG compression functions, then - * *jpegSize is ignored. - * - * @param jpegQual the image quality of the generated JPEG image (1 = worst, - * 100 = best) - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) -*/ -DLLEXPORT int DLLCALL tjCompressFromYUVPlanes(tjhandle handle, - const unsigned char **srcPlanes, int width, const int *strides, int height, - int subsamp, unsigned char **jpegBuf, unsigned long *jpegSize, int jpegQual, - int flags); - - -/** - * The maximum size of the buffer (in bytes) required to hold a JPEG image with - * the given parameters. The number of bytes returned by this function is - * larger than the size of the uncompressed source image. The reason for this - * is that the JPEG format uses 16-bit coefficients, and it is thus possible - * for a very high-quality JPEG image with very high-frequency content to - * expand rather than compress when converted to the JPEG format. Such images - * represent a very rare corner case, but since there is no way to predict the - * size of a JPEG image prior to compression, the corner case has to be - * handled. - * - * @param width width (in pixels) of the image - * - * @param height height (in pixels) of the image - * - * @param jpegSubsamp the level of chrominance subsampling to be used when - * generating the JPEG image (see @ref TJSAMP - * "Chrominance subsampling options".) - * - * @return the maximum size of the buffer (in bytes) required to hold the - * image, or -1 if the arguments are out of bounds. - */ -DLLEXPORT unsigned long DLLCALL tjBufSize(int width, int height, - int jpegSubsamp); - - -/** - * The size of the buffer (in bytes) required to hold a YUV planar image with - * the given parameters. - * - * @param width width (in pixels) of the image - * - * @param pad the width of each line in each plane of the image is padded to - * the nearest multiple of this number of bytes (must be a power of 2.) - * - * @param height height (in pixels) of the image - * - * @param subsamp level of chrominance subsampling in the image (see - * @ref TJSAMP "Chrominance subsampling options".) - * - * @return the size of the buffer (in bytes) required to hold the image, or - * -1 if the arguments are out of bounds. - */ -DLLEXPORT unsigned long DLLCALL tjBufSizeYUV2(int width, int pad, int height, - int subsamp); - - -/** - * The size of the buffer (in bytes) required to hold a YUV image plane with - * the given parameters. - * - * @param componentID ID number of the image plane (0 = Y, 1 = U/Cb, 2 = V/Cr) - * - * @param width width (in pixels) of the YUV image. NOTE: this is the width of - * the whole image, not the plane width. - * - * @param stride bytes per line in the image plane. Setting this to 0 is the - * equivalent of setting it to the plane width. - * - * @param height height (in pixels) of the YUV image. NOTE: this is the height - * of the whole image, not the plane height. - * - * @param subsamp level of chrominance subsampling in the image (see - * @ref TJSAMP "Chrominance subsampling options".) - * - * @return the size of the buffer (in bytes) required to hold the YUV image - * plane, or -1 if the arguments are out of bounds. - */ -DLLEXPORT unsigned long DLLCALL tjPlaneSizeYUV(int componentID, int width, - int stride, int height, int subsamp); - - -/** - * The plane width of a YUV image plane with the given parameters. Refer to - * @ref YUVnotes "YUV Image Format Notes" for a description of plane width. - * - * @param componentID ID number of the image plane (0 = Y, 1 = U/Cb, 2 = V/Cr) - * - * @param width width (in pixels) of the YUV image - * - * @param subsamp level of chrominance subsampling in the image (see - * @ref TJSAMP "Chrominance subsampling options".) - * - * @return the plane width of a YUV image plane with the given parameters, or - * -1 if the arguments are out of bounds. - */ -DLLEXPORT int tjPlaneWidth(int componentID, int width, int subsamp); - - -/** - * The plane height of a YUV image plane with the given parameters. Refer to - * @ref YUVnotes "YUV Image Format Notes" for a description of plane height. - * - * @param componentID ID number of the image plane (0 = Y, 1 = U/Cb, 2 = V/Cr) - * - * @param height height (in pixels) of the YUV image - * - * @param subsamp level of chrominance subsampling in the image (see - * @ref TJSAMP "Chrominance subsampling options".) - * - * @return the plane height of a YUV image plane with the given parameters, or - * -1 if the arguments are out of bounds. - */ -DLLEXPORT int tjPlaneHeight(int componentID, int height, int subsamp); - - -/** - * Encode an RGB or grayscale image into a YUV planar image. This function - * uses the accelerated color conversion routines in the underlying - * codec but does not execute any of the other steps in the JPEG compression - * process. - * - * @param handle a handle to a TurboJPEG compressor or transformer instance - * - * @param srcBuf pointer to an image buffer containing RGB or grayscale pixels - * to be encoded - * - * @param width width (in pixels) of the source image - * - * @param pitch bytes per line in the source image. Normally, this should be - * width * #tjPixelSize[pixelFormat] if the image is unpadded, or - * #TJPAD(width * #tjPixelSize[pixelFormat]) if each line of the image - * is padded to the nearest 32-bit boundary, as is the case for Windows - * bitmaps. You can also be clever and use this parameter to skip lines, etc. - * Setting this parameter to 0 is the equivalent of setting it to - * width * #tjPixelSize[pixelFormat]. - * - * @param height height (in pixels) of the source image - * - * @param pixelFormat pixel format of the source image (see @ref TJPF - * "Pixel formats".) - * - * @param dstBuf pointer to an image buffer that will receive the YUV image. - * Use #tjBufSizeYUV2() to determine the appropriate size for this buffer based - * on the image width, height, padding, and level of chrominance subsampling. - * The Y, U (Cb), and V (Cr) image planes will be stored sequentially in the - * buffer (refer to @ref YUVnotes "YUV Image Format Notes".) - * - * @param pad the width of each line in each plane of the YUV image will be - * padded to the nearest multiple of this number of bytes (must be a power of - * 2.) To generate images suitable for X Video, pad should be set to - * 4. - * - * @param subsamp the level of chrominance subsampling to be used when - * generating the YUV image (see @ref TJSAMP - * "Chrominance subsampling options".) To generate images suitable for X - * Video, subsamp should be set to @ref TJSAMP_420. This produces an - * image compatible with the I420 (AKA "YUV420P") format. - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) -*/ -DLLEXPORT int DLLCALL tjEncodeYUV3(tjhandle handle, - const unsigned char *srcBuf, int width, int pitch, int height, - int pixelFormat, unsigned char *dstBuf, int pad, int subsamp, int flags); - - -/** - * Encode an RGB or grayscale image into separate Y, U (Cb), and V (Cr) image - * planes. This function uses the accelerated color conversion routines in the - * underlying codec but does not execute any of the other steps in the JPEG - * compression process. - * - * @param handle a handle to a TurboJPEG compressor or transformer instance - * - * @param srcBuf pointer to an image buffer containing RGB or grayscale pixels - * to be encoded - * - * @param width width (in pixels) of the source image - * - * @param pitch bytes per line in the source image. Normally, this should be - * width * #tjPixelSize[pixelFormat] if the image is unpadded, or - * #TJPAD(width * #tjPixelSize[pixelFormat]) if each line of the image - * is padded to the nearest 32-bit boundary, as is the case for Windows - * bitmaps. You can also be clever and use this parameter to skip lines, etc. - * Setting this parameter to 0 is the equivalent of setting it to - * width * #tjPixelSize[pixelFormat]. - * - * @param height height (in pixels) of the source image - * - * @param pixelFormat pixel format of the source image (see @ref TJPF - * "Pixel formats".) - * - * @param dstPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes - * (or just a Y plane, if generating a grayscale image) that will receive the - * encoded image. These planes can be contiguous or non-contiguous in memory. - * Use #tjPlaneSizeYUV() to determine the appropriate size for each plane based - * on the image width, height, strides, and level of chrominance subsampling. - * Refer to @ref YUVnotes "YUV Image Format Notes" for more details. - * - * @param strides an array of integers, each specifying the number of bytes per - * line in the corresponding plane of the output image. Setting the stride for - * any plane to 0 is the same as setting it to the plane width (see - * @ref YUVnotes "YUV Image Format Notes".) If strides is NULL, then - * the strides for all planes will be set to their respective plane widths. - * You can adjust the strides in order to add an arbitrary amount of line - * padding to each plane or to encode an RGB or grayscale image into a - * subregion of a larger YUV planar image. - * - * @param subsamp the level of chrominance subsampling to be used when - * generating the YUV image (see @ref TJSAMP - * "Chrominance subsampling options".) To generate images suitable for X - * Video, subsamp should be set to @ref TJSAMP_420. This produces an - * image compatible with the I420 (AKA "YUV420P") format. - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) -*/ -DLLEXPORT int DLLCALL tjEncodeYUVPlanes(tjhandle handle, - const unsigned char *srcBuf, int width, int pitch, int height, - int pixelFormat, unsigned char **dstPlanes, int *strides, int subsamp, - int flags); - - -/** - * Create a TurboJPEG decompressor instance. - * - * @return a handle to the newly-created instance, or NULL if an error - * occurred (see #tjGetErrorStr().) -*/ -DLLEXPORT tjhandle DLLCALL tjInitDecompress(void); - - -/** - * Retrieve information about a JPEG image without decompressing it. - * - * @param handle a handle to a TurboJPEG decompressor or transformer instance - * - * @param jpegBuf pointer to a buffer containing a JPEG image - * - * @param jpegSize size of the JPEG image (in bytes) - * - * @param width pointer to an integer variable that will receive the width (in - * pixels) of the JPEG image - * - * @param height pointer to an integer variable that will receive the height - * (in pixels) of the JPEG image - * - * @param jpegSubsamp pointer to an integer variable that will receive the - * level of chrominance subsampling used when the JPEG image was compressed - * (see @ref TJSAMP "Chrominance subsampling options".) - * - * @param jpegColorspace pointer to an integer variable that will receive one - * of the JPEG colorspace constants, indicating the colorspace of the JPEG - * image (see @ref TJCS "JPEG colorspaces".) - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) -*/ -DLLEXPORT int DLLCALL tjDecompressHeader3(tjhandle handle, - const unsigned char *jpegBuf, unsigned long jpegSize, int *width, - int *height, int *jpegSubsamp, int *jpegColorspace); - - -/** - * Returns a list of fractional scaling factors that the JPEG decompressor in - * this implementation of TurboJPEG supports. - * - * @param numscalingfactors pointer to an integer variable that will receive - * the number of elements in the list - * - * @return a pointer to a list of fractional scaling factors, or NULL if an - * error is encountered (see #tjGetErrorStr().) -*/ -DLLEXPORT tjscalingfactor* DLLCALL tjGetScalingFactors(int *numscalingfactors); - - -/** - * Decompress a JPEG image to an RGB, grayscale, or CMYK image. - * - * @param handle a handle to a TurboJPEG decompressor or transformer instance - * - * @param jpegBuf pointer to a buffer containing the JPEG image to decompress - * - * @param jpegSize size of the JPEG image (in bytes) - * - * @param dstBuf pointer to an image buffer that will receive the decompressed - * image. This buffer should normally be pitch * scaledHeight bytes - * in size, where scaledHeight can be determined by calling - * #TJSCALED() with the JPEG image height and one of the scaling factors - * returned by #tjGetScalingFactors(). The dstBuf pointer may also be - * used to decompress into a specific region of a larger buffer. - * - * @param width desired width (in pixels) of the destination image. If this is - * different than the width of the JPEG image being decompressed, then - * TurboJPEG will use scaling in the JPEG decompressor to generate the largest - * possible image that will fit within the desired width. If width is - * set to 0, then only the height will be considered when determining the - * scaled image size. - * - * @param pitch bytes per line in the destination image. Normally, this is - * scaledWidth * #tjPixelSize[pixelFormat] if the decompressed image - * is unpadded, else #TJPAD(scaledWidth * #tjPixelSize[pixelFormat]) - * if each line of the decompressed image is padded to the nearest 32-bit - * boundary, as is the case for Windows bitmaps. (NOTE: scaledWidth - * can be determined by calling #TJSCALED() with the JPEG image width and one - * of the scaling factors returned by #tjGetScalingFactors().) You can also be - * clever and use the pitch parameter to skip lines, etc. Setting this - * parameter to 0 is the equivalent of setting it to - * scaledWidth * #tjPixelSize[pixelFormat]. - * - * @param height desired height (in pixels) of the destination image. If this - * is different than the height of the JPEG image being decompressed, then - * TurboJPEG will use scaling in the JPEG decompressor to generate the largest - * possible image that will fit within the desired height. If height - * is set to 0, then only the width will be considered when determining the - * scaled image size. - * - * @param pixelFormat pixel format of the destination image (see @ref - * TJPF "Pixel formats".) - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) - */ -DLLEXPORT int DLLCALL tjDecompress2(tjhandle handle, - const unsigned char *jpegBuf, unsigned long jpegSize, unsigned char *dstBuf, - int width, int pitch, int height, int pixelFormat, int flags); - - -/** - * Decompress a JPEG image to a YUV planar image. This function performs JPEG - * decompression but leaves out the color conversion step, so a planar YUV - * image is generated instead of an RGB image. - * - * @param handle a handle to a TurboJPEG decompressor or transformer instance - * - * @param jpegBuf pointer to a buffer containing the JPEG image to decompress - * - * @param jpegSize size of the JPEG image (in bytes) - * - * @param dstBuf pointer to an image buffer that will receive the YUV image. - * Use #tjBufSizeYUV2() to determine the appropriate size for this buffer based - * on the image width, height, padding, and level of subsampling. The Y, - * U (Cb), and V (Cr) image planes will be stored sequentially in the buffer - * (refer to @ref YUVnotes "YUV Image Format Notes".) - * - * @param width desired width (in pixels) of the YUV image. If this is - * different than the width of the JPEG image being decompressed, then - * TurboJPEG will use scaling in the JPEG decompressor to generate the largest - * possible image that will fit within the desired width. If width is - * set to 0, then only the height will be considered when determining the - * scaled image size. If the scaled width is not an even multiple of the MCU - * block width (see #tjMCUWidth), then an intermediate buffer copy will be - * performed within TurboJPEG. - * - * @param pad the width of each line in each plane of the YUV image will be - * padded to the nearest multiple of this number of bytes (must be a power of - * 2.) To generate images suitable for X Video, pad should be set to - * 4. - * - * @param height desired height (in pixels) of the YUV image. If this is - * different than the height of the JPEG image being decompressed, then - * TurboJPEG will use scaling in the JPEG decompressor to generate the largest - * possible image that will fit within the desired height. If height - * is set to 0, then only the width will be considered when determining the - * scaled image size. If the scaled height is not an even multiple of the MCU - * block height (see #tjMCUHeight), then an intermediate buffer copy will be - * performed within TurboJPEG. - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) - */ -DLLEXPORT int DLLCALL tjDecompressToYUV2(tjhandle handle, - const unsigned char *jpegBuf, unsigned long jpegSize, unsigned char *dstBuf, - int width, int pad, int height, int flags); - - -/** - * Decompress a JPEG image into separate Y, U (Cb), and V (Cr) image - * planes. This function performs JPEG decompression but leaves out the color - * conversion step, so a planar YUV image is generated instead of an RGB image. - * - * @param handle a handle to a TurboJPEG decompressor or transformer instance - * - * @param jpegBuf pointer to a buffer containing the JPEG image to decompress - * - * @param jpegSize size of the JPEG image (in bytes) - * - * @param dstPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes - * (or just a Y plane, if decompressing a grayscale image) that will receive - * the YUV image. These planes can be contiguous or non-contiguous in memory. - * Use #tjPlaneSizeYUV() to determine the appropriate size for each plane based - * on the scaled image width, scaled image height, strides, and level of - * chrominance subsampling. Refer to @ref YUVnotes "YUV Image Format Notes" - * for more details. - * - * @param width desired width (in pixels) of the YUV image. If this is - * different than the width of the JPEG image being decompressed, then - * TurboJPEG will use scaling in the JPEG decompressor to generate the largest - * possible image that will fit within the desired width. If width is - * set to 0, then only the height will be considered when determining the - * scaled image size. If the scaled width is not an even multiple of the MCU - * block width (see #tjMCUWidth), then an intermediate buffer copy will be - * performed within TurboJPEG. - * - * @param strides an array of integers, each specifying the number of bytes per - * line in the corresponding plane of the output image. Setting the stride for - * any plane to 0 is the same as setting it to the scaled plane width (see - * @ref YUVnotes "YUV Image Format Notes".) If strides is NULL, then - * the strides for all planes will be set to their respective scaled plane - * widths. You can adjust the strides in order to add an arbitrary amount of - * line padding to each plane or to decompress the JPEG image into a subregion - * of a larger YUV planar image. - * - * @param height desired height (in pixels) of the YUV image. If this is - * different than the height of the JPEG image being decompressed, then - * TurboJPEG will use scaling in the JPEG decompressor to generate the largest - * possible image that will fit within the desired height. If height - * is set to 0, then only the width will be considered when determining the - * scaled image size. If the scaled height is not an even multiple of the MCU - * block height (see #tjMCUHeight), then an intermediate buffer copy will be - * performed within TurboJPEG. - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) - */ -DLLEXPORT int DLLCALL tjDecompressToYUVPlanes(tjhandle handle, - const unsigned char *jpegBuf, unsigned long jpegSize, - unsigned char **dstPlanes, int width, int *strides, int height, int flags); - - -/** - * Decode a YUV planar image into an RGB or grayscale image. This function - * uses the accelerated color conversion routines in the underlying - * codec but does not execute any of the other steps in the JPEG decompression - * process. - * - * @param handle a handle to a TurboJPEG decompressor or transformer instance - * - * @param srcBuf pointer to an image buffer containing a YUV planar image to be - * decoded. The size of this buffer should match the value returned by - * #tjBufSizeYUV2() for the given image width, height, padding, and level of - * chrominance subsampling. The Y, U (Cb), and V (Cr) image planes should be - * stored sequentially in the source buffer (refer to @ref YUVnotes - * "YUV Image Format Notes".) - * - * @param pad Use this parameter to specify that the width of each line in each - * plane of the YUV source image is padded to the nearest multiple of this - * number of bytes (must be a power of 2.) - * - * @param subsamp the level of chrominance subsampling used in the YUV source - * image (see @ref TJSAMP "Chrominance subsampling options".) - * - * @param dstBuf pointer to an image buffer that will receive the decoded - * image. This buffer should normally be pitch * height bytes in - * size, but the dstBuf pointer can also be used to decode into a - * specific region of a larger buffer. - * - * @param width width (in pixels) of the source and destination images - * - * @param pitch bytes per line in the destination image. Normally, this should - * be width * #tjPixelSize[pixelFormat] if the destination image is - * unpadded, or #TJPAD(width * #tjPixelSize[pixelFormat]) if each line - * of the destination image should be padded to the nearest 32-bit boundary, as - * is the case for Windows bitmaps. You can also be clever and use the pitch - * parameter to skip lines, etc. Setting this parameter to 0 is the equivalent - * of setting it to width * #tjPixelSize[pixelFormat]. - * - * @param height height (in pixels) of the source and destination images - * - * @param pixelFormat pixel format of the destination image (see @ref TJPF - * "Pixel formats".) - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) - */ -DLLEXPORT int DLLCALL tjDecodeYUV(tjhandle handle, const unsigned char *srcBuf, - int pad, int subsamp, unsigned char *dstBuf, int width, int pitch, - int height, int pixelFormat, int flags); - - -/** - * Decode a set of Y, U (Cb), and V (Cr) image planes into an RGB or grayscale - * image. This function uses the accelerated color conversion routines in the - * underlying codec but does not execute any of the other steps in the JPEG - * decompression process. - * - * @param handle a handle to a TurboJPEG decompressor or transformer instance - * - * @param srcPlanes an array of pointers to Y, U (Cb), and V (Cr) image planes - * (or just a Y plane, if decoding a grayscale image) that contain a YUV image - * to be decoded. These planes can be contiguous or non-contiguous in memory. - * The size of each plane should match the value returned by #tjPlaneSizeYUV() - * for the given image width, height, strides, and level of chrominance - * subsampling. Refer to @ref YUVnotes "YUV Image Format Notes" for more - * details. - * - * @param strides an array of integers, each specifying the number of bytes per - * line in the corresponding plane of the YUV source image. Setting the stride - * for any plane to 0 is the same as setting it to the plane width (see - * @ref YUVnotes "YUV Image Format Notes".) If strides is NULL, then - * the strides for all planes will be set to their respective plane widths. - * You can adjust the strides in order to specify an arbitrary amount of line - * padding in each plane or to decode a subregion of a larger YUV planar image. - * - * @param subsamp the level of chrominance subsampling used in the YUV source - * image (see @ref TJSAMP "Chrominance subsampling options".) - * - * @param dstBuf pointer to an image buffer that will receive the decoded - * image. This buffer should normally be pitch * height bytes in - * size, but the dstBuf pointer can also be used to decode into a - * specific region of a larger buffer. - * - * @param width width (in pixels) of the source and destination images - * - * @param pitch bytes per line in the destination image. Normally, this should - * be width * #tjPixelSize[pixelFormat] if the destination image is - * unpadded, or #TJPAD(width * #tjPixelSize[pixelFormat]) if each line - * of the destination image should be padded to the nearest 32-bit boundary, as - * is the case for Windows bitmaps. You can also be clever and use the pitch - * parameter to skip lines, etc. Setting this parameter to 0 is the equivalent - * of setting it to width * #tjPixelSize[pixelFormat]. - * - * @param height height (in pixels) of the source and destination images - * - * @param pixelFormat pixel format of the destination image (see @ref TJPF - * "Pixel formats".) - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) - */ -DLLEXPORT int DLLCALL tjDecodeYUVPlanes(tjhandle handle, - const unsigned char **srcPlanes, const int *strides, int subsamp, - unsigned char *dstBuf, int width, int pitch, int height, int pixelFormat, - int flags); - - -/** - * Create a new TurboJPEG transformer instance. - * - * @return a handle to the newly-created instance, or NULL if an error - * occurred (see #tjGetErrorStr().) - */ -DLLEXPORT tjhandle DLLCALL tjInitTransform(void); - - -/** - * Losslessly transform a JPEG image into another JPEG image. Lossless - * transforms work by moving the raw DCT coefficients from one JPEG image - * structure to another without altering the values of the coefficients. While - * this is typically faster than decompressing the image, transforming it, and - * re-compressing it, lossless transforms are not free. Each lossless - * transform requires reading and performing Huffman decoding on all of the - * coefficients in the source image, regardless of the size of the destination - * image. Thus, this function provides a means of generating multiple - * transformed images from the same source or applying multiple - * transformations simultaneously, in order to eliminate the need to read the - * source coefficients multiple times. - * - * @param handle a handle to a TurboJPEG transformer instance - * - * @param jpegBuf pointer to a buffer containing the JPEG source image to - * transform - * - * @param jpegSize size of the JPEG source image (in bytes) - * - * @param n the number of transformed JPEG images to generate - * - * @param dstBufs pointer to an array of n image buffers. dstBufs[i] - * will receive a JPEG image that has been transformed using the parameters in - * transforms[i]. TurboJPEG has the ability to reallocate the JPEG - * buffer to accommodate the size of the JPEG image. Thus, you can choose to: - * -# pre-allocate the JPEG buffer with an arbitrary size using #tjAlloc() and - * let TurboJPEG grow the buffer as needed, - * -# set dstBufs[i] to NULL to tell TurboJPEG to allocate the buffer - * for you, or - * -# pre-allocate the buffer to a "worst case" size determined by calling - * #tjBufSize() with the transformed or cropped width and height. Under normal - * circumstances, this should ensure that the buffer never has to be - * re-allocated (setting #TJFLAG_NOREALLOC guarantees that it won't be.) Note, - * however, that there are some rare cases (such as transforming images with a - * large amount of embedded EXIF or ICC profile data) in which the output image - * will be larger than the worst-case size, and #TJFLAG_NOREALLOC cannot be - * used in those cases. - * . - * If you choose option 1, dstSizes[i] should be set to the size of - * your pre-allocated buffer. In any case, unless you have set - * #TJFLAG_NOREALLOC, you should always check dstBufs[i] upon return - * from this function, as it may have changed. - * - * @param dstSizes pointer to an array of n unsigned long variables that will - * receive the actual sizes (in bytes) of each transformed JPEG image. If - * dstBufs[i] points to a pre-allocated buffer, then - * dstSizes[i] should be set to the size of the buffer. Upon return, - * dstSizes[i] will contain the size of the JPEG image (in bytes.) - * - * @param transforms pointer to an array of n #tjtransform structures, each of - * which specifies the transform parameters and/or cropping region for the - * corresponding transformed output image. - * - * @param flags the bitwise OR of one or more of the @ref TJFLAG_ACCURATEDCT - * "flags" - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) - */ -DLLEXPORT int DLLCALL tjTransform(tjhandle handle, - const unsigned char *jpegBuf, unsigned long jpegSize, int n, - unsigned char **dstBufs, unsigned long *dstSizes, tjtransform *transforms, - int flags); - - -/** - * Destroy a TurboJPEG compressor, decompressor, or transformer instance. - * - * @param handle a handle to a TurboJPEG compressor, decompressor or - * transformer instance - * - * @return 0 if successful, or -1 if an error occurred (see #tjGetErrorStr().) - */ -DLLEXPORT int DLLCALL tjDestroy(tjhandle handle); - - -/** - * Allocate an image buffer for use with TurboJPEG. You should always use - * this function to allocate the JPEG destination buffer(s) for the compression - * and transform functions unless you are disabling automatic buffer - * (re)allocation (by setting #TJFLAG_NOREALLOC.) - * - * @param bytes the number of bytes to allocate - * - * @return a pointer to a newly-allocated buffer with the specified number of - * bytes. - * - * @sa tjFree() - */ -DLLEXPORT unsigned char* DLLCALL tjAlloc(int bytes); - - -/** - * Free an image buffer previously allocated by TurboJPEG. You should always - * use this function to free JPEG destination buffer(s) that were automatically - * (re)allocated by the compression and transform functions or that were - * manually allocated using #tjAlloc(). - * - * @param buffer address of the buffer to free - * - * @sa tjAlloc() - */ -DLLEXPORT void DLLCALL tjFree(unsigned char *buffer); - - -/** - * Returns a descriptive error message explaining why the last command failed. - * - * @return a descriptive error message explaining why the last command failed. - */ -DLLEXPORT char* DLLCALL tjGetErrorStr(void); - - -/* Deprecated functions and macros */ -#define TJFLAG_FORCEMMX 8 -#define TJFLAG_FORCESSE 16 -#define TJFLAG_FORCESSE2 32 -#define TJFLAG_FORCESSE3 128 - - -/* Backward compatibility functions and macros (nothing to see here) */ -#define NUMSUBOPT TJ_NUMSAMP -#define TJ_444 TJSAMP_444 -#define TJ_422 TJSAMP_422 -#define TJ_420 TJSAMP_420 -#define TJ_411 TJSAMP_420 -#define TJ_GRAYSCALE TJSAMP_GRAY - -#define TJ_BGR 1 -#define TJ_BOTTOMUP TJFLAG_BOTTOMUP -#define TJ_FORCEMMX TJFLAG_FORCEMMX -#define TJ_FORCESSE TJFLAG_FORCESSE -#define TJ_FORCESSE2 TJFLAG_FORCESSE2 -#define TJ_ALPHAFIRST 64 -#define TJ_FORCESSE3 TJFLAG_FORCESSE3 -#define TJ_FASTUPSAMPLE TJFLAG_FASTUPSAMPLE -#define TJ_YUV 512 - -DLLEXPORT unsigned long DLLCALL TJBUFSIZE(int width, int height); - -DLLEXPORT unsigned long DLLCALL TJBUFSIZEYUV(int width, int height, - int jpegSubsamp); - -DLLEXPORT unsigned long DLLCALL tjBufSizeYUV(int width, int height, - int subsamp); - -DLLEXPORT int DLLCALL tjCompress(tjhandle handle, unsigned char *srcBuf, - int width, int pitch, int height, int pixelSize, unsigned char *dstBuf, - unsigned long *compressedSize, int jpegSubsamp, int jpegQual, int flags); - -DLLEXPORT int DLLCALL tjEncodeYUV(tjhandle handle, - unsigned char *srcBuf, int width, int pitch, int height, int pixelSize, - unsigned char *dstBuf, int subsamp, int flags); - -DLLEXPORT int DLLCALL tjEncodeYUV2(tjhandle handle, - unsigned char *srcBuf, int width, int pitch, int height, int pixelFormat, - unsigned char *dstBuf, int subsamp, int flags); - -DLLEXPORT int DLLCALL tjDecompressHeader(tjhandle handle, - unsigned char *jpegBuf, unsigned long jpegSize, int *width, int *height); - -DLLEXPORT int DLLCALL tjDecompressHeader2(tjhandle handle, - unsigned char *jpegBuf, unsigned long jpegSize, int *width, int *height, - int *jpegSubsamp); - -DLLEXPORT int DLLCALL tjDecompress(tjhandle handle, - unsigned char *jpegBuf, unsigned long jpegSize, unsigned char *dstBuf, - int width, int pitch, int height, int pixelSize, int flags); - -DLLEXPORT int DLLCALL tjDecompressToYUV(tjhandle handle, - unsigned char *jpegBuf, unsigned long jpegSize, unsigned char *dstBuf, - int flags); - - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libs/include/xmp.h b/libs/include/xmp.h deleted file mode 100644 index e3d223e9..00000000 --- a/libs/include/xmp.h +++ /dev/null @@ -1,358 +0,0 @@ -#ifndef XMP_H -#define XMP_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define XMP_VERSION "4.4.1" -#define XMP_VERCODE 0x040401 -#define XMP_VER_MAJOR 4 -#define XMP_VER_MINOR 4 -#define XMP_VER_RELEASE 1 - -#if defined(_WIN32) && !defined(__CYGWIN__) -# if defined(BUILDING_STATIC) -# define EXPORT -# elif defined(BUILDING_DLL) -# define EXPORT __declspec(dllexport) -# else -# define EXPORT __declspec(dllimport) -# endif -#elif __GNUC__ >= 4 || defined(__HP_cc) -# define EXPORT __attribute__((visibility ("default"))) -#elif defined(__SUNPRO_C) -# define EXPORT __global -#elif defined(EMSCRIPTEN) -# define EXPORT EMSCRIPTEN_KEEPALIVE -#else -# define EXPORT -#endif - -#define XMP_NAME_SIZE 64 /* Size of module name and type */ - -#define XMP_KEY_OFF 0x81 /* Note number for key off event */ -#define XMP_KEY_CUT 0x82 /* Note number for key cut event */ -#define XMP_KEY_FADE 0x83 /* Note number for fade event */ - -/* mixer parameter macros */ - -/* sample format flags */ -#define XMP_FORMAT_8BIT (1 << 0) /* Mix to 8-bit instead of 16 */ -#define XMP_FORMAT_UNSIGNED (1 << 1) /* Mix to unsigned samples */ -#define XMP_FORMAT_MONO (1 << 2) /* Mix to mono instead of stereo */ - -/* player parameters */ -#define XMP_PLAYER_AMP 0 /* Amplification factor */ -#define XMP_PLAYER_MIX 1 /* Stereo mixing */ -#define XMP_PLAYER_INTERP 2 /* Interpolation type */ -#define XMP_PLAYER_DSP 3 /* DSP effect flags */ -#define XMP_PLAYER_FLAGS 4 /* Player flags */ -#define XMP_PLAYER_CFLAGS 5 /* Player flags for current module */ -#define XMP_PLAYER_SMPCTL 6 /* Sample control flags */ -#define XMP_PLAYER_VOLUME 7 /* Player module volume */ -#define XMP_PLAYER_STATE 8 /* Internal player state (read only) */ -#define XMP_PLAYER_SMIX_VOLUME 9 /* SMIX volume */ -#define XMP_PLAYER_DEFPAN 10 /* Default pan setting */ -#define XMP_PLAYER_MODE 11 /* Player personality */ -#define XMP_PLAYER_MIXER_TYPE 12 /* Current mixer (read only) */ -#define XMP_PLAYER_VOICES 13 /* Maximum number of mixer voices */ - -/* interpolation types */ -#define XMP_INTERP_NEAREST 0 /* Nearest neighbor */ -#define XMP_INTERP_LINEAR 1 /* Linear (default) */ -#define XMP_INTERP_SPLINE 2 /* Cubic spline */ - -/* dsp effect types */ -#define XMP_DSP_LOWPASS (1 << 0) /* Lowpass filter effect */ -#define XMP_DSP_ALL (XMP_DSP_LOWPASS) - -/* player state */ -#define XMP_STATE_UNLOADED 0 /* Context created */ -#define XMP_STATE_LOADED 1 /* Module loaded */ -#define XMP_STATE_PLAYING 2 /* Module playing */ - -/* player flags */ -#define XMP_FLAGS_VBLANK (1 << 0) /* Use vblank timing */ -#define XMP_FLAGS_FX9BUG (1 << 1) /* Emulate FX9 bug */ -#define XMP_FLAGS_FIXLOOP (1 << 2) /* Emulate sample loop bug */ -#define XMP_FLAGS_A500 (1 << 3) /* Use Paula mixer in Amiga modules */ - -/* player modes */ -#define XMP_MODE_AUTO 0 /* Autodetect mode (default) */ -#define XMP_MODE_MOD 1 /* Play as a generic MOD player */ -#define XMP_MODE_NOISETRACKER 2 /* Play using Noisetracker quirks */ -#define XMP_MODE_PROTRACKER 3 /* Play using Protracker quirks */ -#define XMP_MODE_S3M 4 /* Play as a generic S3M player */ -#define XMP_MODE_ST3 5 /* Play using ST3 bug emulation */ -#define XMP_MODE_ST3GUS 6 /* Play using ST3+GUS quirks */ -#define XMP_MODE_XM 7 /* Play as a generic XM player */ -#define XMP_MODE_FT2 8 /* Play using FT2 bug emulation */ -#define XMP_MODE_IT 9 /* Play using IT quirks */ -#define XMP_MODE_ITSMP 10 /* Play using IT sample mode quirks */ - -/* mixer types */ -#define XMP_MIXER_STANDARD 0 /* Standard mixer */ -#define XMP_MIXER_A500 1 /* Amiga 500 */ -#define XMP_MIXER_A500F 2 /* Amiga 500 with led filter */ - -/* sample flags */ -#define XMP_SMPCTL_SKIP (1 << 0) /* Don't load samples */ - -/* limits */ -#define XMP_MAX_KEYS 121 /* Number of valid keys */ -#define XMP_MAX_ENV_POINTS 32 /* Max number of envelope points */ -#define XMP_MAX_MOD_LENGTH 256 /* Max number of patterns in module */ -#define XMP_MAX_CHANNELS 64 /* Max number of channels in module */ -#define XMP_MAX_SRATE 49170 /* max sampling rate (Hz) */ -#define XMP_MIN_SRATE 4000 /* min sampling rate (Hz) */ -#define XMP_MIN_BPM 20 /* min BPM */ -/* frame rate = (50 * bpm / 125) Hz */ -/* frame size = (sampling rate * channels * size) / frame rate */ -#define XMP_MAX_FRAMESIZE (5 * XMP_MAX_SRATE * 2 / XMP_MIN_BPM) - -/* error codes */ -#define XMP_END 1 -#define XMP_ERROR_INTERNAL 2 /* Internal error */ -#define XMP_ERROR_FORMAT 3 /* Unsupported module format */ -#define XMP_ERROR_LOAD 4 /* Error loading file */ -#define XMP_ERROR_DEPACK 5 /* Error depacking file */ -#define XMP_ERROR_SYSTEM 6 /* System error */ -#define XMP_ERROR_INVALID 7 /* Invalid parameter */ -#define XMP_ERROR_STATE 8 /* Invalid player state */ - -struct xmp_channel { - int pan; /* Channel pan (0x80 is center) */ - int vol; /* Channel volume */ -#define XMP_CHANNEL_SYNTH (1 << 0) /* Channel is synthesized */ -#define XMP_CHANNEL_MUTE (1 << 1) /* Channel is muted */ -#define XMP_CHANNEL_SPLIT (1 << 2) /* Split Amiga channel in bits 5-4 */ -#define XMP_CHANNEL_SURROUND (1 << 4) /* Surround channel */ - int flg; /* Channel flags */ -}; - -struct xmp_pattern { - int rows; /* Number of rows */ - int index[1]; /* Track index */ -}; - -struct xmp_event { - unsigned char note; /* Note number (0 means no note) */ - unsigned char ins; /* Patch number */ - unsigned char vol; /* Volume (0 to basevol) */ - unsigned char fxt; /* Effect type */ - unsigned char fxp; /* Effect parameter */ - unsigned char f2t; /* Secondary effect type */ - unsigned char f2p; /* Secondary effect parameter */ - unsigned char _flag; /* Internal (reserved) flags */ -}; - -struct xmp_track { - int rows; /* Number of rows */ - struct xmp_event event[1]; /* Event data */ -}; - -struct xmp_envelope { -#define XMP_ENVELOPE_ON (1 << 0) /* Envelope is enabled */ -#define XMP_ENVELOPE_SUS (1 << 1) /* Envelope has sustain point */ -#define XMP_ENVELOPE_LOOP (1 << 2) /* Envelope has loop */ -#define XMP_ENVELOPE_FLT (1 << 3) /* Envelope is used for filter */ -#define XMP_ENVELOPE_SLOOP (1 << 4) /* Envelope has sustain loop */ -#define XMP_ENVELOPE_CARRY (1 << 5) /* Don't reset envelope position */ - int flg; /* Flags */ - int npt; /* Number of envelope points */ - int scl; /* Envelope scaling */ - int sus; /* Sustain start point */ - int sue; /* Sustain end point */ - int lps; /* Loop start point */ - int lpe; /* Loop end point */ - short data[XMP_MAX_ENV_POINTS * 2]; -}; - -struct xmp_instrument { - char name[32]; /* Instrument name */ - int vol; /* Instrument volume */ - int nsm; /* Number of samples */ - int rls; /* Release (fadeout) */ - struct xmp_envelope aei; /* Amplitude envelope info */ - struct xmp_envelope pei; /* Pan envelope info */ - struct xmp_envelope fei; /* Frequency envelope info */ - - struct { - unsigned char ins; /* Instrument number for each key */ - signed char xpo; /* Instrument transpose for each key */ - } map[XMP_MAX_KEYS]; - - struct xmp_subinstrument { - int vol; /* Default volume */ - int gvl; /* Global volume */ - int pan; /* Pan */ - int xpo; /* Transpose */ - int fin; /* Finetune */ - int vwf; /* Vibrato waveform */ - int vde; /* Vibrato depth */ - int vra; /* Vibrato rate */ - int vsw; /* Vibrato sweep */ - int rvv; /* Random volume/pan variation (IT) */ - int sid; /* Sample number */ -#define XMP_INST_NNA_CUT 0x00 -#define XMP_INST_NNA_CONT 0x01 -#define XMP_INST_NNA_OFF 0x02 -#define XMP_INST_NNA_FADE 0x03 - int nna; /* New note action */ -#define XMP_INST_DCT_OFF 0x00 -#define XMP_INST_DCT_NOTE 0x01 -#define XMP_INST_DCT_SMP 0x02 -#define XMP_INST_DCT_INST 0x03 - int dct; /* Duplicate check type */ -#define XMP_INST_DCA_CUT XMP_INST_NNA_CUT -#define XMP_INST_DCA_OFF XMP_INST_NNA_OFF -#define XMP_INST_DCA_FADE XMP_INST_NNA_FADE - int dca; /* Duplicate check action */ - int ifc; /* Initial filter cutoff */ - int ifr; /* Initial filter resonance */ - } *sub; - - void *extra; /* Extra fields */ -}; - -struct xmp_sample { - char name[32]; /* Sample name */ - int len; /* Sample length */ - int lps; /* Loop start */ - int lpe; /* Loop end */ -#define XMP_SAMPLE_16BIT (1 << 0) /* 16bit sample */ -#define XMP_SAMPLE_LOOP (1 << 1) /* Sample is looped */ -#define XMP_SAMPLE_LOOP_BIDIR (1 << 2) /* Bidirectional sample loop */ -#define XMP_SAMPLE_LOOP_REVERSE (1 << 3) /* Backwards sample loop */ -#define XMP_SAMPLE_LOOP_FULL (1 << 4) /* Play full sample before looping */ -#define XMP_SAMPLE_SLOOP (1 << 5) /* Sample has sustain loop */ -#define XMP_SAMPLE_SLOOP_BIDIR (1 << 6) /* Bidirectional sustain loop */ -#define XMP_SAMPLE_SYNTH (1 << 15) /* Data contains synth patch */ - int flg; /* Flags */ - unsigned char *data; /* Sample data */ -}; - -struct xmp_sequence { - int entry_point; - int duration; -}; - -struct xmp_module { - char name[XMP_NAME_SIZE]; /* Module title */ - char type[XMP_NAME_SIZE]; /* Module format */ - int pat; /* Number of patterns */ - int trk; /* Number of tracks */ - int chn; /* Tracks per pattern */ - int ins; /* Number of instruments */ - int smp; /* Number of samples */ - int spd; /* Initial speed */ - int bpm; /* Initial BPM */ - int len; /* Module length in patterns */ - int rst; /* Restart position */ - int gvl; /* Global volume */ - - struct xmp_pattern **xxp; /* Patterns */ - struct xmp_track **xxt; /* Tracks */ - struct xmp_instrument *xxi; /* Instruments */ - struct xmp_sample *xxs; /* Samples */ - struct xmp_channel xxc[XMP_MAX_CHANNELS]; /* Channel info */ - unsigned char xxo[XMP_MAX_MOD_LENGTH]; /* Orders */ -}; - -struct xmp_test_info { - char name[XMP_NAME_SIZE]; /* Module title */ - char type[XMP_NAME_SIZE]; /* Module format */ -}; - -struct xmp_module_info { - unsigned char md5[16]; /* MD5 message digest */ - int vol_base; /* Volume scale */ - struct xmp_module *mod; /* Pointer to module data */ - char *comment; /* Comment text, if any */ - int num_sequences; /* Number of valid sequences */ - struct xmp_sequence *seq_data; /* Pointer to sequence data */ -}; - -struct xmp_frame_info { /* Current frame information */ - int pos; /* Current position */ - int pattern; /* Current pattern */ - int row; /* Current row in pattern */ - int num_rows; /* Number of rows in current pattern */ - int frame; /* Current frame */ - int speed; /* Current replay speed */ - int bpm; /* Current bpm */ - int time; /* Current module time in ms */ - int total_time; /* Estimated replay time in ms*/ - int frame_time; /* Frame replay time in us */ - void *buffer; /* Pointer to sound buffer */ - int buffer_size; /* Used buffer size */ - int total_size; /* Total buffer size */ - int volume; /* Current master volume */ - int loop_count; /* Loop counter */ - int virt_channels; /* Number of virtual channels */ - int virt_used; /* Used virtual channels */ - int sequence; /* Current sequence */ - - struct xmp_channel_info { /* Current channel information */ - unsigned int period; /* Sample period (* 4096) */ - unsigned int position; /* Sample position */ - short pitchbend; /* Linear bend from base note*/ - unsigned char note; /* Current base note number */ - unsigned char instrument; /* Current instrument number */ - unsigned char sample; /* Current sample number */ - unsigned char volume; /* Current volume */ - unsigned char pan; /* Current stereo pan */ - unsigned char reserved; /* Reserved */ - struct xmp_event event; /* Current track event */ - } channel_info[XMP_MAX_CHANNELS]; -}; - - -typedef char *xmp_context; - -EXPORT extern const char *xmp_version; -EXPORT extern const unsigned int xmp_vercode; - -EXPORT xmp_context xmp_create_context (void); -EXPORT void xmp_free_context (xmp_context); -EXPORT int xmp_test_module (char *, struct xmp_test_info *); -EXPORT int xmp_load_module (xmp_context, char *); -EXPORT void xmp_scan_module (xmp_context); -EXPORT void xmp_release_module (xmp_context); -EXPORT int xmp_start_player (xmp_context, int, int); -EXPORT int xmp_play_frame (xmp_context); -EXPORT int xmp_play_buffer (xmp_context, void *, int, int); -EXPORT void xmp_get_frame_info (xmp_context, struct xmp_frame_info *); -EXPORT void xmp_end_player (xmp_context); -EXPORT void xmp_inject_event (xmp_context, int, struct xmp_event *); -EXPORT void xmp_get_module_info (xmp_context, struct xmp_module_info *); -EXPORT char **xmp_get_format_list (void); -EXPORT int xmp_next_position (xmp_context); -EXPORT int xmp_prev_position (xmp_context); -EXPORT int xmp_set_position (xmp_context, int); -EXPORT void xmp_stop_module (xmp_context); -EXPORT void xmp_restart_module (xmp_context); -EXPORT int xmp_seek_time (xmp_context, int); -EXPORT int xmp_channel_mute (xmp_context, int, int); -EXPORT int xmp_channel_vol (xmp_context, int, int); -EXPORT int xmp_set_player (xmp_context, int, int); -EXPORT int xmp_get_player (xmp_context, int); -EXPORT int xmp_set_instrument_path (xmp_context, char *); -EXPORT int xmp_load_module_from_memory (xmp_context, void *, long); -EXPORT int xmp_load_module_from_file (xmp_context, void *, long); - -/* External sample mixer API */ -EXPORT int xmp_start_smix (xmp_context, int, int); -EXPORT void xmp_end_smix (xmp_context); -EXPORT int xmp_smix_play_instrument(xmp_context, int, int, int, int); -EXPORT int xmp_smix_play_sample (xmp_context, int, int, int, int); -EXPORT int xmp_smix_channel_pan (xmp_context, int, int); -EXPORT int xmp_smix_load_sample (xmp_context, int, char *); -EXPORT int xmp_smix_release_sample (xmp_context, int); - -#ifdef __cplusplus -} -#endif - -#endif /* XMP_H */ diff --git a/libs/lib/libFLAC.a b/libs/lib/libFLAC.a deleted file mode 100644 index 006c4124..00000000 Binary files a/libs/lib/libFLAC.a and /dev/null differ diff --git a/libs/lib/libglib2d.a b/libs/lib/libglib2d.a index 7fb71b73..487cfc1e 100644 Binary files a/libs/lib/libglib2d.a and b/libs/lib/libglib2d.a differ diff --git a/libs/lib/liblzma.a b/libs/lib/liblzma.a deleted file mode 100644 index 90459e4f..00000000 Binary files a/libs/lib/liblzma.a and /dev/null differ diff --git a/libs/lib/libmpg123.a b/libs/lib/libmpg123.a deleted file mode 100644 index c607ca0d..00000000 Binary files a/libs/lib/libmpg123.a and /dev/null differ diff --git a/libs/lib/libopus.a b/libs/lib/libopus.a index 840b674e..e44d159f 100644 Binary files a/libs/lib/libopus.a and b/libs/lib/libopus.a differ diff --git a/libs/libnsbmp/libnsbmp.c b/libs/libnsbmp/libnsbmp.c index f6ebd6c2..b4da553e 100644 --- a/libs/libnsbmp/libnsbmp.c +++ b/libs/libnsbmp/libnsbmp.c @@ -530,7 +530,7 @@ static bmp_result bmp_decode_rgb32(bmp_image *bmp, uint8_t **start, int bytes) assert(bmp->bpp == 32); data = *start; - swidth = bmp->bitmap_callbacks.bitmap_get_bpp(bmp->bitmap) * bmp->width; + swidth = sizeof(uint32_t) * bmp->width; top = bmp->bitmap_callbacks.bitmap_get_buffer(bmp->bitmap); if (!top) return BMP_INSUFFICIENT_MEMORY; @@ -612,7 +612,7 @@ static bmp_result bmp_decode_rgb24(bmp_image *bmp, uint8_t **start, int bytes) assert(bmp->bpp == 24); data = *start; - swidth = bmp->bitmap_callbacks.bitmap_get_bpp(bmp->bitmap) * bmp->width; + swidth = sizeof(uint32_t) * bmp->width; top = bmp->bitmap_callbacks.bitmap_get_buffer(bmp->bitmap); if (!top) { return BMP_INSUFFICIENT_MEMORY; @@ -683,7 +683,7 @@ static bmp_result bmp_decode_rgb16(bmp_image *bmp, uint8_t **start, int bytes) uint16_t word; data = *start; - swidth = bmp->bitmap_callbacks.bitmap_get_bpp(bmp->bitmap) * bmp->width; + swidth = sizeof(uint32_t) * bmp->width; top = bmp->bitmap_callbacks.bitmap_get_buffer(bmp->bitmap); if (!top) return BMP_INSUFFICIENT_MEMORY; @@ -777,7 +777,7 @@ static bmp_result bmp_decode_rgb(bmp_image *bmp, uint8_t **start, int bytes) bit_shifts[i] = 8 - ((i + 1) * bmp->bpp); data = *start; - swidth = bmp->bitmap_callbacks.bitmap_get_bpp(bmp->bitmap) * bmp->width; + swidth = sizeof(uint32_t) * bmp->width; top = bmp->bitmap_callbacks.bitmap_get_buffer(bmp->bitmap); if (!top) return BMP_INSUFFICIENT_MEMORY; @@ -842,7 +842,7 @@ static bmp_result bmp_decode_mask(bmp_image *bmp, uint8_t *data, int bytes) uint32_t x, y, swidth; uint32_t cur_byte = 0; - swidth = bmp->bitmap_callbacks.bitmap_get_bpp(bmp->bitmap) * bmp->width; + swidth = sizeof(uint32_t) * bmp->width; top = bmp->bitmap_callbacks.bitmap_get_buffer(bmp->bitmap); if (!top) return BMP_INSUFFICIENT_MEMORY; @@ -897,7 +897,7 @@ bmp_decode_rle8(bmp_image *bmp, uint8_t *data, int bytes) if (bmp->ico) return BMP_DATA_ERROR; - swidth = bmp->bitmap_callbacks.bitmap_get_bpp(bmp->bitmap) * bmp->width; + swidth = sizeof(uint32_t) * bmp->width; top = bmp->bitmap_callbacks.bitmap_get_buffer(bmp->bitmap); if (!top) return BMP_INSUFFICIENT_MEMORY; @@ -1051,7 +1051,7 @@ bmp_decode_rle4(bmp_image *bmp, uint8_t *data, int bytes) if (bmp->ico) return BMP_DATA_ERROR; - swidth = bmp->bitmap_callbacks.bitmap_get_bpp(bmp->bitmap) * bmp->width; + swidth = sizeof(uint32_t) * bmp->width; top = bmp->bitmap_callbacks.bitmap_get_buffer(bmp->bitmap); if (!top) return BMP_INSUFFICIENT_MEMORY; diff --git a/libs/libnsbmp/libnsbmp.h b/libs/libnsbmp/libnsbmp.h index 71e79096..74ab31b2 100644 --- a/libs/libnsbmp/libnsbmp.h +++ b/libs/libnsbmp/libnsbmp.h @@ -66,8 +66,6 @@ typedef struct bmp_bitmap_callback_vt_s { bmp_bitmap_cb_destroy bitmap_destroy; /** Return a pointer to the pixel data in a bitmap. */ bmp_bitmap_cb_get_buffer bitmap_get_buffer; - /** Find the width of a pixel row in bytes. */ - bmp_bitmap_cb_get_bpp bitmap_get_bpp; } bmp_bitmap_callback_vt; /** diff --git a/libs/libnsgif/gif.c b/libs/libnsgif/gif.c new file mode 100755 index 00000000..73814bf3 --- /dev/null +++ b/libs/libnsgif/gif.c @@ -0,0 +1,2076 @@ +/* + * Copyright 2004 Richard Wilson + * Copyright 2008 Sean Fox + * Copyright 2013-2022 Michael Drake + * + * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/ + * Licenced under the MIT License, + * http://www.opensource.org/licenses/mit-license.php + */ + +#include +#include +#include +#include +#include + +#include "lzw.h" +#include "nsgif.h" + +/** Default minimum allowable frame delay in cs. */ +#define NSGIF_FRAME_DELAY_MIN 2 + +/** + * Default frame delay to apply. + * + * Used when a frame delay lower than the minimum is requested. + */ +#define NSGIF_FRAME_DELAY_DEFAULT 10 + +/** GIF frame data */ +typedef struct nsgif_frame { + struct nsgif_frame_info info; + + /** offset (in bytes) to the GIF frame data */ + size_t frame_offset; + /** whether the frame has previously been decoded. */ + bool decoded; + /** whether the frame is totally opaque */ + bool opaque; + /** whether a full image redraw is required */ + bool redraw_required; + + /** Amount of LZW data found in scan */ + uint32_t lzw_data_length; + + /** the index designating a transparent pixel */ + uint32_t transparency_index; + + /** offset to frame colour table */ + uint32_t colour_table_offset; + + /* Frame flags */ + uint32_t flags; +} nsgif_frame; + +/** Pixel format: colour component order. */ +struct nsgif_colour_layout { + uint8_t r; /**< Byte offset within pixel to red component. */ + uint8_t g; /**< Byte offset within pixel to green component. */ + uint8_t b; /**< Byte offset within pixel to blue component. */ + uint8_t a; /**< Byte offset within pixel to alpha component. */ +}; + +/** GIF animation data */ +struct nsgif { + struct nsgif_info info; + + /** LZW decode context */ + void *lzw_ctx; + /** callbacks for bitmap functions */ + nsgif_bitmap_cb_vt bitmap; + /** decoded frames */ + nsgif_frame *frames; + /** current frame */ + uint32_t frame; + /** current frame decoded to bitmap */ + uint32_t decoded_frame; + + /** currently decoded image; stored as bitmap from bitmap_create callback */ + nsgif_bitmap_t *frame_image; + /** Row span of frame_image in pixels. */ + uint32_t rowspan; + + /** Minimum allowable frame delay. */ + uint16_t delay_min; + + /** Frame delay to apply when delay is less than \ref delay_min. */ + uint16_t delay_default; + + /** number of animation loops so far */ + int loop_count; + + /** number of frames partially decoded */ + uint32_t frame_count_partial; + + /** + * Whether all the GIF data has been supplied, or if there may be + * more to come. + */ + bool data_complete; + + /** pointer to GIF data */ + const uint8_t *buf; + /** current index into GIF data */ + size_t buf_pos; + /** total number of bytes of GIF data available */ + size_t buf_len; + + /** current number of frame holders */ + uint32_t frame_holders; + /** background index */ + uint32_t bg_index; + /** image aspect ratio (ignored) */ + uint32_t aspect_ratio; + /** size of global colour table (in entries) */ + uint32_t colour_table_size; + + /** current colour table */ + uint32_t *colour_table; + /** Client's colour component order. */ + struct nsgif_colour_layout colour_layout; + /** global colour table */ + uint32_t global_colour_table[NSGIF_MAX_COLOURS]; + /** local colour table */ + uint32_t local_colour_table[NSGIF_MAX_COLOURS]; + + /** previous frame for NSGIF_FRAME_RESTORE */ + void *prev_frame; + /** previous frame index */ + uint32_t prev_index; +}; + +/** + * Helper macro to get number of elements in an array. + * + * \param[in] _a Array to count elements of. + * \return NUlber of elements in array. + */ +#define NSGIF_ARRAY_LEN(_a) ((sizeof(_a)) / (sizeof(*_a))) + +/** + * + * \file + * \brief GIF image decoder + * + * The GIF format is thoroughly documented; a full description can be found at + * http://www.w3.org/Graphics/GIF/spec-gif89a.txt + * + * \todo Plain text and comment extensions should be implemented. + */ + +/** Internal flag that the colour table needs to be processed */ +#define NSGIF_PROCESS_COLOURS 0xaa000000 + +/** Internal flag that a frame is invalid/unprocessed */ +#define NSGIF_FRAME_INVALID UINT32_MAX + +/** Transparent colour */ +#define NSGIF_TRANSPARENT_COLOUR 0x00 + +/** No transparency */ +#define NSGIF_NO_TRANSPARENCY (0xFFFFFFFFu) + +/* GIF Flags */ +#define NSGIF_COLOUR_TABLE_MASK 0x80 +#define NSGIF_COLOUR_TABLE_SIZE_MASK 0x07 +#define NSGIF_BLOCK_TERMINATOR 0x00 +#define NSGIF_TRAILER 0x3b + +/** + * Convert an LZW result code to equivalent GIF result code. + * + * \param[in] l_res LZW response code. + * \return GIF result code. + */ +static nsgif_error nsgif__error_from_lzw(lzw_result l_res) +{ + static const nsgif_error g_res[] = { + [LZW_OK] = NSGIF_OK, + [LZW_NO_MEM] = NSGIF_ERR_OOM, + [LZW_OK_EOD] = NSGIF_ERR_END_OF_DATA, + [LZW_NO_DATA] = NSGIF_ERR_END_OF_DATA, + [LZW_EOI_CODE] = NSGIF_ERR_DATA_FRAME, + [LZW_BAD_ICODE] = NSGIF_ERR_DATA_FRAME, + [LZW_BAD_CODE] = NSGIF_ERR_DATA_FRAME, + }; + assert(l_res != LZW_BAD_PARAM); + assert(l_res != LZW_NO_COLOUR); + return g_res[l_res]; +} + +/** + * Updates the sprite memory size + * + * \param gif The animation context + * \param width The width of the sprite + * \param height The height of the sprite + * \return NSGIF_ERR_OOM for a memory error NSGIF_OK for success + */ +static nsgif_error nsgif__initialise_sprite( + struct nsgif *gif, + uint32_t width, + uint32_t height) +{ + /* Already allocated? */ + if (gif->frame_image) { + return NSGIF_OK; + } + + assert(gif->bitmap.create); + gif->frame_image = gif->bitmap.create(width, height); + if (gif->frame_image == NULL) { + return NSGIF_ERR_OOM; + } + + return NSGIF_OK; +} + +/** + * Helper to get the rendering bitmap for a gif. + * + * \param[in] gif The gif object we're decoding. + * \return Client pixel buffer for rendering into. + */ +static inline uint32_t* nsgif__bitmap_get( + struct nsgif *gif) +{ + nsgif_error ret; + + /* Make sure we have a buffer to decode to. */ + ret = nsgif__initialise_sprite(gif, gif->info.width, gif->info.height); + if (ret != NSGIF_OK) { + return NULL; + } + + gif->rowspan = gif->info.width; + if (gif->bitmap.get_rowspan) { + gif->rowspan = gif->bitmap.get_rowspan(gif->frame_image); + } + + /* Get the frame data */ + assert(gif->bitmap.get_buffer); + return (void *)gif->bitmap.get_buffer(gif->frame_image); +} + +/** + * Helper to tell the client that their bitmap was modified. + * + * \param[in] gif The gif object we're decoding. + */ +static inline void nsgif__bitmap_modified( + const struct nsgif *gif) +{ + if (gif->bitmap.modified) { + gif->bitmap.modified(gif->frame_image); + } +} + +/** + * Helper to tell the client that whether the bitmap is opaque. + * + * \param[in] gif The gif object we're decoding. + * \param[in] frame The frame that has been decoded. + */ +static inline void nsgif__bitmap_set_opaque( + const struct nsgif *gif, + const struct nsgif_frame *frame) +{ + if (gif->bitmap.set_opaque) { + gif->bitmap.set_opaque( + gif->frame_image, frame->opaque); + } +} + +/** + * Helper to get the client to determine if the bitmap is opaque. + * + * \todo: We don't really need to get the client to do this for us. + * + * \param[in] gif The gif object we're decoding. + * \return true if the bitmap is opaque, false otherwise. + */ +static inline bool nsgif__bitmap_get_opaque( + const struct nsgif *gif) +{ + if (gif->bitmap.test_opaque) { + return gif->bitmap.test_opaque( + gif->frame_image); + } + + return false; +} + +static void nsgif__record_frame( + struct nsgif *gif, + const uint32_t *bitmap) +{ + size_t pixel_bytes = sizeof(*bitmap); + size_t height = gif->info.height; + size_t width = gif->info.width; + uint32_t *prev_frame; + + if (gif->decoded_frame == NSGIF_FRAME_INVALID || + gif->decoded_frame == gif->prev_index) { + /* No frame to copy, or already have this frame recorded. */ + return; + } + + bitmap = nsgif__bitmap_get(gif); + if (bitmap == NULL) { + return; + } + + if (gif->prev_frame == NULL) { + prev_frame = realloc(gif->prev_frame, + width * height * pixel_bytes); + if (prev_frame == NULL) { + return; + } + } else { + prev_frame = gif->prev_frame; + } + + memcpy(prev_frame, bitmap, width * height * pixel_bytes); + + gif->prev_frame = prev_frame; + gif->prev_index = gif->decoded_frame; +} + +static nsgif_error nsgif__recover_frame( + const struct nsgif *gif, + uint32_t *bitmap) +{ + const uint32_t *prev_frame = gif->prev_frame; + size_t pixel_bytes = sizeof(*bitmap); + size_t height = gif->info.height; + size_t width = gif->info.width; + + memcpy(bitmap, prev_frame, height * width * pixel_bytes); + + return NSGIF_OK; +} + +/** + * Get the next line for GIF decode. + * + * Note that the step size must be initialised to 24 at the start of the frame + * (when y == 0). This is because of the first two passes of the frame have + * the same step size of 8, and the step size is used to determine the current + * pass. + * + * \param[in] height Frame height in pixels. + * \param[in,out] y Current row, starting from 0, updated on exit. + * \param[in,out] step Current step starting with 24, updated on exit. + * \return true if there is a row to process, false at the end of the frame. + */ +static inline bool nsgif__deinterlace(uint32_t height, uint32_t *y, uint8_t *step) +{ + *y += *step & 0xf; + + if (*y < height) return true; + + switch (*step) { + case 24: *y = 4; *step = 8; if (*y < height) return true; + /* Fall through. */ + case 8: *y = 2; *step = 4; if (*y < height) return true; + /* Fall through. */ + case 4: *y = 1; *step = 2; if (*y < height) return true; + /* Fall through. */ + default: + break; + } + + return false; +} + +/** + * Get the next line for GIF decode. + * + * \param[in] interlace Non-zero if the frame is not interlaced. + * \param[in] height Frame height in pixels. + * \param[in,out] y Current row, starting from 0, updated on exit. + * \param[in,out] step Current step starting with 24, updated on exit. + * \return true if there is a row to process, false at the end of the frame. + */ +static inline bool nsgif__next_row(uint32_t interlace, + uint32_t height, uint32_t *y, uint8_t *step) +{ + if (!interlace) { + return (++*y != height); + } else { + return nsgif__deinterlace(height, y, step); + } +} + +/** + * Get any frame clip adjustment for the image extent. + * + * \param[in] frame_off Frame's X or Y offset. + * \param[in] frame_dim Frame width or height. + * \param[in] image_ext Image width or height constraint. + * \return the amount the frame needs to be clipped to fit the image in given + * dimension. + */ +static inline uint32_t gif__clip( + uint32_t frame_off, + uint32_t frame_dim, + uint32_t image_ext) +{ + uint32_t frame_ext = frame_off + frame_dim; + + if (frame_ext <= image_ext) { + return 0; + } + + return frame_ext - image_ext; +} + +/** + * Perform any jump over decoded data, to accommodate clipped portion of frame. + * + * \param[in,out] skip Number of pixels of data to jump. + * \param[in,out] available Number of pixels of data currently available. + * \param[in,out] pos Position in decoded pixel value data. + */ +static inline void gif__jump_data( + uint32_t *skip, + uint32_t *available, + const uint8_t **pos) +{ + uint32_t jump = (*skip < *available) ? *skip : *available; + + *skip -= jump; + *available -= jump; + *pos += jump; +} + +static nsgif_error nsgif__decode_complex( + struct nsgif *gif, + uint32_t width, + uint32_t height, + uint32_t offset_x, + uint32_t offset_y, + uint32_t interlace, + const uint8_t *data, + uint32_t transparency_index, + uint32_t *restrict frame_data, + uint32_t *restrict colour_table) +{ + lzw_result res; + nsgif_error ret = NSGIF_OK; + uint32_t clip_x = gif__clip(offset_x, width, gif->info.width); + uint32_t clip_y = gif__clip(offset_y, height, gif->info.height); + const uint8_t *uncompressed; + uint32_t available = 0; + uint8_t step = 24; + uint32_t skip = 0; + uint32_t y = 0; + + if (offset_x >= gif->info.width || + offset_y >= gif->info.height) { + return NSGIF_OK; + } + + width -= clip_x; + height -= clip_y; + + if (width == 0 || height == 0) { + return NSGIF_OK; + } + + /* Initialise the LZW decoding */ + res = lzw_decode_init(gif->lzw_ctx, data[0], + gif->buf, gif->buf_len, + data + 1 - gif->buf); + if (res != LZW_OK) { + return nsgif__error_from_lzw(res); + } + + do { + uint32_t x; + uint32_t *frame_scanline; + + frame_scanline = frame_data + offset_x + + (y + offset_y) * gif->rowspan; + + x = width; + while (x > 0) { + unsigned row_available; + while (available == 0) { + if (res != LZW_OK) { + /* Unexpected end of frame, try to recover */ + if (res == LZW_OK_EOD || + res == LZW_EOI_CODE) { + ret = NSGIF_OK; + } else { + ret = nsgif__error_from_lzw(res); + } + return ret; + } + res = lzw_decode(gif->lzw_ctx, + &uncompressed, &available); + + if (available == 0) { + return NSGIF_OK; + } + gif__jump_data(&skip, &available, &uncompressed); + } + + row_available = x < available ? x : available; + x -= row_available; + available -= row_available; + if (transparency_index > 0xFF) { + while (row_available-- > 0) { + *frame_scanline++ = + colour_table[*uncompressed++]; + } + } else { + while (row_available-- > 0) { + register uint32_t colour; + colour = *uncompressed++; + if (colour != transparency_index) { + *frame_scanline = + colour_table[colour]; + } + frame_scanline++; + } + } + } + + skip = clip_x; + gif__jump_data(&skip, &available, &uncompressed); + } while (nsgif__next_row(interlace, height, &y, &step)); + + return ret; +} + +static nsgif_error nsgif__decode_simple( + struct nsgif *gif, + uint32_t height, + uint32_t offset_y, + const uint8_t *data, + uint32_t transparency_index, + uint32_t *restrict frame_data, + uint32_t *restrict colour_table) +{ + uint32_t pixels; + uint32_t written = 0; + nsgif_error ret = NSGIF_OK; + lzw_result res; + + if (offset_y >= gif->info.height) { + return NSGIF_OK; + } + + height -= gif__clip(offset_y, height, gif->info.height); + + if (height == 0) { + return NSGIF_OK; + } + + /* Initialise the LZW decoding */ + res = lzw_decode_init_map(gif->lzw_ctx, data[0], + transparency_index, colour_table, + gif->buf, gif->buf_len, + data + 1 - gif->buf); + if (res != LZW_OK) { + return nsgif__error_from_lzw(res); + } + + frame_data += (offset_y * gif->info.width); + pixels = gif->info.width * height; + + while (pixels > 0) { + res = lzw_decode_map(gif->lzw_ctx, + frame_data, pixels, &written); + pixels -= written; + frame_data += written; + if (res != LZW_OK) { + /* Unexpected end of frame, try to recover */ + if (res == LZW_OK_EOD || res == LZW_EOI_CODE) { + ret = NSGIF_OK; + } else { + ret = nsgif__error_from_lzw(res); + } + break; + } + } + + if (pixels == 0) { + ret = NSGIF_OK; + } + + return ret; +} + +static inline nsgif_error nsgif__decode( + struct nsgif *gif, + struct nsgif_frame *frame, + const uint8_t *data, + uint32_t *restrict frame_data) +{ + nsgif_error ret; + uint32_t width = frame->info.rect.x1 - frame->info.rect.x0; + uint32_t height = frame->info.rect.y1 - frame->info.rect.y0; + uint32_t offset_x = frame->info.rect.x0; + uint32_t offset_y = frame->info.rect.y0; + uint32_t transparency_index = frame->transparency_index; + uint32_t *restrict colour_table = gif->colour_table; + + if (frame->info.interlaced == false && offset_x == 0 && + width == gif->info.width && + width == gif->rowspan) { + ret = nsgif__decode_simple(gif, height, offset_y, + data, transparency_index, + frame_data, colour_table); + } else { + ret = nsgif__decode_complex(gif, width, height, + offset_x, offset_y, frame->info.interlaced, + data, transparency_index, + frame_data, colour_table); + } + + if (gif->data_complete && ret == NSGIF_ERR_END_OF_DATA) { + /* This is all the data there is, so make do. */ + ret = NSGIF_OK; + } + + return ret; +} + +/** + * Restore a GIF to the background colour. + * + * \param[in] gif The gif object we're decoding. + * \param[in] frame The frame to clear, or NULL. + * \param[in] bitmap The bitmap to clear the frame in. + */ +static void nsgif__restore_bg( + struct nsgif *gif, + struct nsgif_frame *frame, + uint32_t *bitmap) +{ + size_t pixel_bytes = sizeof(*bitmap); + + if (frame == NULL) { + size_t width = gif->info.width; + size_t height = gif->info.height; + + memset(bitmap, NSGIF_TRANSPARENT_COLOUR, + width * height * pixel_bytes); + } else { + uint32_t width = frame->info.rect.x1 - frame->info.rect.x0; + uint32_t height = frame->info.rect.y1 - frame->info.rect.y0; + uint32_t offset_x = frame->info.rect.x0; + uint32_t offset_y = frame->info.rect.y0; + + if (frame->info.display == false || + frame->info.rect.x0 >= gif->info.width || + frame->info.rect.y0 >= gif->info.height) { + return; + } + + width -= gif__clip(offset_x, width, gif->info.width); + height -= gif__clip(offset_y, height, gif->info.height); + + if (frame->info.transparency) { + for (uint32_t y = 0; y < height; y++) { + uint32_t *scanline = bitmap + offset_x + + (offset_y + y) * gif->info.width; + memset(scanline, NSGIF_TRANSPARENT_COLOUR, + width * pixel_bytes); + } + } else { + for (uint32_t y = 0; y < height; y++) { + uint32_t *scanline = bitmap + offset_x + + (offset_y + y) * gif->info.width; + for (uint32_t x = 0; x < width; x++) { + scanline[x] = gif->info.background; + } + } + } + } +} + +static nsgif_error nsgif__update_bitmap( + struct nsgif *gif, + struct nsgif_frame *frame, + const uint8_t *data, + uint32_t frame_idx) +{ + nsgif_error ret; + uint32_t *bitmap; + + gif->decoded_frame = frame_idx; + + bitmap = nsgif__bitmap_get(gif); + if (bitmap == NULL) { + return NSGIF_ERR_OOM; + } + + /* Handle any bitmap clearing/restoration required before decoding this + * frame. */ + if (frame_idx == 0 || gif->decoded_frame == NSGIF_FRAME_INVALID) { + nsgif__restore_bg(gif, NULL, bitmap); + + } else { + struct nsgif_frame *prev = &gif->frames[frame_idx - 1]; + + if (prev->info.disposal == NSGIF_DISPOSAL_RESTORE_BG) { + nsgif__restore_bg(gif, prev, bitmap); + + } else if (prev->info.disposal == NSGIF_DISPOSAL_RESTORE_PREV) { + ret = nsgif__recover_frame(gif, bitmap); + if (ret != NSGIF_OK) { + nsgif__restore_bg(gif, prev, bitmap); + } + } + } + + if (frame->info.disposal == NSGIF_DISPOSAL_RESTORE_PREV) { + /* Store the previous frame for later restoration */ + nsgif__record_frame(gif, bitmap); + } + + ret = nsgif__decode(gif, frame, data, bitmap); + + nsgif__bitmap_modified(gif); + + if (!frame->decoded) { + frame->opaque = nsgif__bitmap_get_opaque(gif); + frame->decoded = true; + } + nsgif__bitmap_set_opaque(gif, frame); + + return ret; +} + +/** + * Parse the graphic control extension + * + * \param[in] frame The gif frame object we're decoding. + * \param[in] data The data to decode. + * \param[in] len Byte length of data. + * \return NSGIF_ERR_END_OF_DATA if more data is needed, + * NSGIF_OK for success. + */ +static nsgif_error nsgif__parse_extension_graphic_control( + struct nsgif_frame *frame, + const uint8_t *data, + size_t len) +{ + enum { + GIF_MASK_TRANSPARENCY = 0x01, + GIF_MASK_DISPOSAL = 0x1c, + }; + + /* 6-byte Graphic Control Extension is: + * + * +0 CHAR Graphic Control Label + * +1 CHAR Block Size + * +2 CHAR __Packed Fields__ + * 3BITS Reserved + * 3BITS Disposal Method + * 1BIT User Input Flag + * 1BIT Transparent Color Flag + * +3 SHORT Delay Time + * +5 CHAR Transparent Color Index + */ + if (len < 6) { + return NSGIF_ERR_END_OF_DATA; + } + + frame->info.delay = data[3] | (data[4] << 8); + + if (data[2] & GIF_MASK_TRANSPARENCY) { + frame->info.transparency = true; + frame->transparency_index = data[5]; + } + + frame->info.disposal = ((data[2] & GIF_MASK_DISPOSAL) >> 2); + /* I have encountered documentation and GIFs in the + * wild that use 0x04 to restore the previous frame, + * rather than the officially documented 0x03. I + * believe some (older?) software may even actually + * export this way. We handle this as a type of + * "quirks" mode. */ + if (frame->info.disposal == NSGIF_DISPOSAL_RESTORE_QUIRK) { + frame->info.disposal = NSGIF_DISPOSAL_RESTORE_PREV; + } + + /* if we are clearing the background then we need to + * redraw enough to cover the previous frame too. */ + frame->redraw_required = + frame->info.disposal == NSGIF_DISPOSAL_RESTORE_BG || + frame->info.disposal == NSGIF_DISPOSAL_RESTORE_PREV; + + return NSGIF_OK; +} + +/** + * Check an app ext identifier and authentication code for loop count extension. + * + * \param[in] data The data to decode. + * \param[in] len Byte length of data. + * \return true if extension is a loop count extension. + */ +static bool nsgif__app_ext_is_loop_count( + const uint8_t *data, + size_t len) +{ + enum { + EXT_LOOP_COUNT_BLOCK_SIZE = 0x0b, + }; + + assert(len > 13); + (void)(len); + + if (data[1] == EXT_LOOP_COUNT_BLOCK_SIZE) { + if (strncmp((const char *)data + 2, "NETSCAPE2.0", 11) == 0 || + strncmp((const char *)data + 2, "ANIMEXTS1.0", 11) == 0) { + return true; + } + } + + return false; +} + +/** + * Parse the application extension + * + * \param[in] gif The gif object we're decoding. + * \param[in] data The data to decode. + * \param[in] len Byte length of data. + * \return NSGIF_ERR_END_OF_DATA if more data is needed, + * NSGIF_OK for success. + */ +static nsgif_error nsgif__parse_extension_application( + struct nsgif *gif, + const uint8_t *data, + size_t len) +{ + /* 14-byte+ Application Extension is: + * + * +0 CHAR Application Extension Label + * +1 CHAR Block Size + * +2 8CHARS Application Identifier + * +10 3CHARS Appl. Authentication Code + * +13 1-256 Application Data (Data sub-blocks) + */ + if (len < 17) { + return NSGIF_ERR_END_OF_DATA; + } + + if (nsgif__app_ext_is_loop_count(data, len)) { + enum { + EXT_LOOP_COUNT_SUB_BLOCK_SIZE = 0x03, + EXT_LOOP_COUNT_SUB_BLOCK_ID = 0x01, + }; + if ((data[13] == EXT_LOOP_COUNT_SUB_BLOCK_SIZE) && + (data[14] == EXT_LOOP_COUNT_SUB_BLOCK_ID)) { + gif->info.loop_max = data[15] | (data[16] << 8); + + /* The value in the source data means repeat N times + * after the first implied play. A value of zero has + * the special meaning of loop forever. (The only way + * to play the animation once is not to have this + * extension at all. */ + if (gif->info.loop_max > 0) { + gif->info.loop_max++; + } + } + } + + return NSGIF_OK; +} + +/** + * Parse the frame's extensions + * + * \param[in] gif The gif object we're decoding. + * \param[in] frame The frame to parse extensions for. + * \param[in] pos Current position in data, updated on exit. + * \param[in] decode Whether to decode or skip over the extension. + * \return NSGIF_ERR_END_OF_DATA if more data is needed, + * NSGIF_OK for success. + */ +static nsgif_error nsgif__parse_frame_extensions( + struct nsgif *gif, + struct nsgif_frame *frame, + const uint8_t **pos, + bool decode) +{ + enum { + GIF_EXT_INTRODUCER = 0x21, + GIF_EXT_GRAPHIC_CONTROL = 0xf9, + GIF_EXT_COMMENT = 0xfe, + GIF_EXT_PLAIN_TEXT = 0x01, + GIF_EXT_APPLICATION = 0xff, + }; + const uint8_t *nsgif_data = *pos; + const uint8_t *nsgif_end = gif->buf + gif->buf_len; + int nsgif_bytes = nsgif_end - nsgif_data; + + /* Initialise the extensions */ + while (nsgif_bytes > 0 && nsgif_data[0] == GIF_EXT_INTRODUCER) { + bool block_step = true; + nsgif_error ret; + + nsgif_data++; + nsgif_bytes--; + + if (nsgif_bytes == 0) { + return NSGIF_ERR_END_OF_DATA; + } + + /* Switch on extension label */ + switch (nsgif_data[0]) { + case GIF_EXT_GRAPHIC_CONTROL: + if (decode) { + ret = nsgif__parse_extension_graphic_control( + frame, + nsgif_data, + nsgif_bytes); + if (ret != NSGIF_OK) { + return ret; + } + } + break; + + case GIF_EXT_APPLICATION: + if (decode) { + ret = nsgif__parse_extension_application( + gif, nsgif_data, nsgif_bytes); + if (ret != NSGIF_OK) { + return ret; + } + } + break; + + case GIF_EXT_COMMENT: + /* Move the pointer to the first data sub-block Skip 1 + * byte for the extension label. */ + ++nsgif_data; + block_step = false; + break; + + default: + break; + } + + if (block_step) { + /* Move the pointer to the first data sub-block Skip 2 + * bytes for the extension label and size fields Skip + * the extension size itself + */ + if (nsgif_bytes < 2) { + return NSGIF_ERR_END_OF_DATA; + } + nsgif_data += 2 + nsgif_data[1]; + } + + /* Repeatedly skip blocks until we get a zero block or run out + * of data. This data is ignored by this gif decoder. */ + while (nsgif_data < nsgif_end && nsgif_data[0] != NSGIF_BLOCK_TERMINATOR) { + nsgif_data += nsgif_data[0] + 1; + if (nsgif_data >= nsgif_end) { + return NSGIF_ERR_END_OF_DATA; + } + } + nsgif_data++; + nsgif_bytes = nsgif_end - nsgif_data; + } + + if (nsgif_data > nsgif_end) { + nsgif_data = nsgif_end; + } + + /* Set buffer position and return */ + *pos = nsgif_data; + return NSGIF_OK; +} + +/** + * Parse a GIF Image Descriptor. + * + * The format is: + * + * +0 CHAR Image Separator (0x2c) + * +1 SHORT Image Left Position + * +3 SHORT Image Top Position + * +5 SHORT Width + * +7 SHORT Height + * +9 CHAR __Packed Fields__ + * 1BIT Local Colour Table Flag + * 1BIT Interlace Flag + * 1BIT Sort Flag + * 2BITS Reserved + * 3BITS Size of Local Colour Table + * + * \param[in] gif The gif object we're decoding. + * \param[in] frame The frame to parse an image descriptor for. + * \param[in] pos Current position in data, updated on exit. + * \param[in] decode Whether to decode the image descriptor. + * \return NSGIF_OK on success, appropriate error otherwise. + */ +static nsgif_error nsgif__parse_image_descriptor( + struct nsgif *gif, + struct nsgif_frame *frame, + const uint8_t **pos, + bool decode) +{ + const uint8_t *data = *pos; + size_t len = gif->buf + gif->buf_len - data; + enum { + NSGIF_IMAGE_DESCRIPTOR_LEN = 10u, + NSGIF_IMAGE_SEPARATOR = 0x2Cu, + NSGIF_MASK_INTERLACE = 0x40u, + }; + + assert(gif != NULL); + assert(frame != NULL); + + if (len < NSGIF_IMAGE_DESCRIPTOR_LEN) { + return NSGIF_ERR_END_OF_DATA; + } + + if (decode) { + uint32_t x, y, w, h; + + if (data[0] != NSGIF_IMAGE_SEPARATOR) { + return NSGIF_ERR_DATA_FRAME; + } + + x = data[1] | (data[2] << 8); + y = data[3] | (data[4] << 8); + w = data[5] | (data[6] << 8); + h = data[7] | (data[8] << 8); + frame->flags = data[9]; + + frame->info.rect.x0 = x; + frame->info.rect.y0 = y; + frame->info.rect.x1 = x + w; + frame->info.rect.y1 = y + h; + + frame->info.interlaced = frame->flags & NSGIF_MASK_INTERLACE; + + /* Allow first frame to grow image dimensions. */ + if (gif->info.frame_count == 0) { + if (x + w > gif->info.width) { + gif->info.width = x + w; + } + if (y + h > gif->info.height) { + gif->info.height = y + h; + } + } + } + + *pos += NSGIF_IMAGE_DESCRIPTOR_LEN; + return NSGIF_OK; +} + +/** + * Extract a GIF colour table into a LibNSGIF colour table buffer. + * + * \param[in] colour_table The colour table to populate. + * \param[in] layout la. + * \param[in] colour_table_entries The number of colour table entries. + * \param[in] data Raw colour table data. + */ +static void nsgif__colour_table_decode( + uint32_t colour_table[NSGIF_MAX_COLOURS], + const struct nsgif_colour_layout *layout, + size_t colour_table_entries, + const uint8_t *data) +{ + uint8_t *entry = (uint8_t *)colour_table; + + while (colour_table_entries--) { + /* Gif colour map contents are r,g,b. + * + * We want to pack them bytewise into the colour table, + * according to the client colour layout. + */ + + entry[layout->r] = *data++; + entry[layout->g] = *data++; + entry[layout->b] = *data++; + entry[layout->a] = 0xff; + + entry += sizeof(uint32_t); + } +} + +/** + * Extract a GIF colour table into a LibNSGIF colour table buffer. + * + * \param[in] colour_table The colour table to populate. + * \param[in] layout The target pixel format to decode to. + * \param[in] colour_table_entries The number of colour table entries. + * \param[in] data Current position in data. + * \param[in] data_len The available length of `data`. + * \param[out] used Number of colour table bytes read. + * \param[in] decode Whether to decode the colour table. + * \return NSGIF_OK on success, appropriate error otherwise. + */ +static inline nsgif_error nsgif__colour_table_extract( + uint32_t colour_table[NSGIF_MAX_COLOURS], + const struct nsgif_colour_layout *layout, + size_t colour_table_entries, + const uint8_t *data, + size_t data_len, + size_t *used, + bool decode) +{ + if (data_len < colour_table_entries * 3) { + return NSGIF_ERR_END_OF_DATA; + } + + if (decode) { + nsgif__colour_table_decode(colour_table, layout, + colour_table_entries, data); + } + + *used = colour_table_entries * 3; + return NSGIF_OK; +} + +/** + * Get a frame's colour table. + * + * Sets up gif->colour_table for the frame. + * + * \param[in] gif The gif object we're decoding. + * \param[in] frame The frame to get the colour table for. + * \param[in] pos Current position in data, updated on exit. + * \param[in] decode Whether to decode the colour table. + * \return NSGIF_OK on success, appropriate error otherwise. + */ +static nsgif_error nsgif__parse_colour_table( + struct nsgif *gif, + struct nsgif_frame *frame, + const uint8_t **pos, + bool decode) +{ + nsgif_error ret; + const uint8_t *data = *pos; + size_t len = gif->buf + gif->buf_len - data; + size_t used_bytes; + + assert(gif != NULL); + assert(frame != NULL); + + if ((frame->flags & NSGIF_COLOUR_TABLE_MASK) == 0) { + gif->colour_table = gif->global_colour_table; + return NSGIF_OK; + } + + if (decode == false) { + frame->colour_table_offset = *pos - gif->buf; + } + + ret = nsgif__colour_table_extract( + gif->local_colour_table, &gif->colour_layout, + 2 << (frame->flags & NSGIF_COLOUR_TABLE_SIZE_MASK), + data, len, &used_bytes, decode); + if (ret != NSGIF_OK) { + return ret; + } + *pos += used_bytes; + + if (decode) { + gif->colour_table = gif->local_colour_table; + } else { + frame->info.local_palette = true; + } + + return NSGIF_OK; +} + +/** + * Parse the image data for a gif frame. + * + * Sets up gif->colour_table for the frame. + * + * \param[in] gif The gif object we're decoding. + * \param[in] frame The frame to parse image data for. + * \param[in] pos Current position in data, updated on exit. + * \param[in] decode Whether to decode the image data. + * \return NSGIF_OK on success, appropriate error otherwise. + */ +static nsgif_error nsgif__parse_image_data( + struct nsgif *gif, + struct nsgif_frame *frame, + const uint8_t **pos, + bool decode) +{ + const uint8_t *data = *pos; + size_t len = gif->buf + gif->buf_len - data; + uint32_t frame_idx = frame - gif->frames; + uint8_t minimum_code_size; + nsgif_error ret; + + assert(gif != NULL); + assert(frame != NULL); + + if (!decode) { + gif->frame_count_partial = frame_idx + 1; + } + + /* Ensure sufficient data remains. A gif trailer or a minimum lzw code + * followed by a gif trailer is treated as OK, although without any + * image data. */ + switch (len) { + default: if (data[0] == NSGIF_TRAILER) return NSGIF_OK; + break; + case 2: if (data[1] == NSGIF_TRAILER) return NSGIF_OK; + /* Fall through. */ + case 1: if (data[0] == NSGIF_TRAILER) return NSGIF_OK; + /* Fall through. */ + case 0: return NSGIF_ERR_END_OF_DATA; + } + + minimum_code_size = data[0]; + if (minimum_code_size >= LZW_CODE_MAX) { + return NSGIF_ERR_DATA_FRAME; + } + + if (decode) { + ret = nsgif__update_bitmap(gif, frame, data, frame_idx); + } else { + uint32_t block_size = 0; + + /* Skip the minimum code size. */ + data++; + len--; + + while (block_size != 1) { + if (len < 1) { + return NSGIF_ERR_END_OF_DATA; + } + block_size = data[0] + 1; + /* Check if the frame data runs off the end of the file */ + if (block_size > len) { + frame->lzw_data_length += len; + return NSGIF_ERR_END_OF_DATA; + } + + len -= block_size; + data += block_size; + frame->lzw_data_length += block_size; + } + + *pos = data; + + gif->info.frame_count = frame_idx + 1; + gif->frames[frame_idx].info.display = true; + + return NSGIF_OK; + } + + return ret; +} + +static struct nsgif_frame *nsgif__get_frame( + struct nsgif *gif, + uint32_t frame_idx) +{ + struct nsgif_frame *frame; + + if (gif->frame_holders > frame_idx) { + frame = &gif->frames[frame_idx]; + } else { + /* Allocate more memory */ + size_t count = frame_idx + 1; + struct nsgif_frame *temp; + + temp = realloc(gif->frames, count * sizeof(*frame)); + if (temp == NULL) { + return NULL; + } + gif->frames = temp; + gif->frame_holders = count; + + frame = &gif->frames[frame_idx]; + + frame->info.local_palette = false; + frame->info.transparency = false; + frame->info.display = false; + frame->info.disposal = 0; + frame->info.delay = 10; + + frame->transparency_index = NSGIF_NO_TRANSPARENCY; + frame->frame_offset = gif->buf_pos; + frame->redraw_required = false; + frame->lzw_data_length = 0; + frame->decoded = false; + } + + return frame; +} + +/** + * Attempts to initialise the next frame + * + * \param[in] gif The animation context + * \param[in] frame_idx The frame number to decode. + * \param[in] decode Whether to decode the graphical image data. + * \return NSGIF_OK on success, appropriate error otherwise. +*/ +static nsgif_error nsgif__process_frame( + struct nsgif *gif, + uint32_t frame_idx, + bool decode) +{ + nsgif_error ret; + const uint8_t *pos; + const uint8_t *end; + struct nsgif_frame *frame; + + frame = nsgif__get_frame(gif, frame_idx); + if (frame == NULL) { + return NSGIF_ERR_OOM; + } + + end = gif->buf + gif->buf_len; + + if (decode) { + pos = gif->buf + frame->frame_offset; + + /* Ensure this frame is supposed to be decoded */ + if (frame->info.display == false) { + return NSGIF_OK; + } + + /* Ensure the frame is in range to decode */ + if (frame_idx > gif->frame_count_partial) { + return NSGIF_ERR_END_OF_DATA; + } + + /* Done if frame is already decoded */ + if (frame_idx == gif->decoded_frame) { + return NSGIF_OK; + } + } else { + pos = gif->buf + gif->buf_pos; + + /* Check if we've finished */ + if (pos < end && pos[0] == NSGIF_TRAILER) { + return NSGIF_OK; + } + } + + ret = nsgif__parse_frame_extensions(gif, frame, &pos, !decode); + if (ret != NSGIF_OK) { + goto cleanup; + } + + ret = nsgif__parse_image_descriptor(gif, frame, &pos, !decode); + if (ret != NSGIF_OK) { + goto cleanup; + } + + ret = nsgif__parse_colour_table(gif, frame, &pos, decode); + if (ret != NSGIF_OK) { + goto cleanup; + } + + ret = nsgif__parse_image_data(gif, frame, &pos, decode); + if (ret != NSGIF_OK) { + goto cleanup; + } + +cleanup: + if (!decode) { + gif->buf_pos = pos - gif->buf; + } + + return ret; +} + +/* exported function documented in nsgif.h */ +void nsgif_destroy(nsgif_t *gif) +{ + if (gif == NULL) { + return; + } + + /* Release all our memory blocks */ + if (gif->frame_image) { + assert(gif->bitmap.destroy); + gif->bitmap.destroy(gif->frame_image); + gif->frame_image = NULL; + } + + free(gif->frames); + gif->frames = NULL; + + free(gif->prev_frame); + gif->prev_frame = NULL; + + lzw_context_destroy(gif->lzw_ctx); + gif->lzw_ctx = NULL; + + free(gif); +} + +/** + * Check whether the host is little endian. + * + * Checks whether least significant bit is in the first byte of a `uint16_t`. + * + * \return true if host is little endian. + */ +static inline bool nsgif__host_is_little_endian(void) +{ + const uint16_t test = 1; + + return ((const uint8_t *) &test)[0]; +} + +static struct nsgif_colour_layout nsgif__bitmap_fmt_to_colour_layout( + nsgif_bitmap_fmt_t bitmap_fmt) +{ + bool le = nsgif__host_is_little_endian(); + + /* Map endian-dependant formats to byte-wise format for the host. */ + switch (bitmap_fmt) { + case NSGIF_BITMAP_FMT_RGBA8888: + bitmap_fmt = (le) ? NSGIF_BITMAP_FMT_A8B8G8R8 + : NSGIF_BITMAP_FMT_R8G8B8A8; + break; + case NSGIF_BITMAP_FMT_BGRA8888: + bitmap_fmt = (le) ? NSGIF_BITMAP_FMT_A8R8G8B8 + : NSGIF_BITMAP_FMT_B8G8R8A8; + break; + case NSGIF_BITMAP_FMT_ARGB8888: + bitmap_fmt = (le) ? NSGIF_BITMAP_FMT_B8G8R8A8 + : NSGIF_BITMAP_FMT_A8R8G8B8; + break; + case NSGIF_BITMAP_FMT_ABGR8888: + bitmap_fmt = (le) ? NSGIF_BITMAP_FMT_R8G8B8A8 + : NSGIF_BITMAP_FMT_A8B8G8R8; + break; + default: + break; + } + + /* Set up colour component order for bitmap format. */ + switch (bitmap_fmt) { + default: + /* Fall through. */ + case NSGIF_BITMAP_FMT_R8G8B8A8: + return (struct nsgif_colour_layout) { + .r = 0, + .g = 1, + .b = 2, + .a = 3, + }; + + case NSGIF_BITMAP_FMT_B8G8R8A8: + return (struct nsgif_colour_layout) { + .b = 0, + .g = 1, + .r = 2, + .a = 3, + }; + + case NSGIF_BITMAP_FMT_A8R8G8B8: + return (struct nsgif_colour_layout) { + .a = 0, + .r = 1, + .g = 2, + .b = 3, + }; + + case NSGIF_BITMAP_FMT_A8B8G8R8: + return (struct nsgif_colour_layout) { + .a = 0, + .b = 1, + .g = 2, + .r = 3, + }; + } +} + +/* exported function documented in nsgif.h */ +nsgif_error nsgif_create( + const nsgif_bitmap_cb_vt *bitmap_vt, + nsgif_bitmap_fmt_t bitmap_fmt, + nsgif_t **gif_out) +{ + nsgif_t *gif; + + gif = calloc(1, sizeof(*gif)); + if (gif == NULL) { + return NSGIF_ERR_OOM; + } + + gif->bitmap = *bitmap_vt; + gif->decoded_frame = NSGIF_FRAME_INVALID; + gif->prev_index = NSGIF_FRAME_INVALID; + + gif->delay_min = NSGIF_FRAME_DELAY_MIN; + gif->delay_default = NSGIF_FRAME_DELAY_DEFAULT; + + gif->colour_layout = nsgif__bitmap_fmt_to_colour_layout(bitmap_fmt); + + *gif_out = gif; + return NSGIF_OK; +} + +/* exported function documented in nsgif.h */ +void nsgif_set_frame_delay_behaviour( + nsgif_t *gif, + uint16_t delay_min, + uint16_t delay_default) +{ + gif->delay_min = delay_min; + gif->delay_default = delay_default; +} + +/** + * Read GIF header. + * + * 6-byte GIF file header is: + * + * +0 3CHARS Signature ('GIF') + * +3 3CHARS Version ('87a' or '89a') + * + * \param[in] gif The GIF object we're decoding. + * \param[in,out] pos The current buffer position, updated on success. + * \param[in] strict Whether to require a known GIF version. + * \return NSGIF_OK on success, appropriate error otherwise. + */ +static nsgif_error nsgif__parse_header( + struct nsgif *gif, + const uint8_t **pos, + bool strict) +{ + const uint8_t *data = *pos; + size_t len = gif->buf + gif->buf_len - data; + + if (len < 6) { + return NSGIF_ERR_END_OF_DATA; + } + + if (strncmp((const char *) data, "GIF", 3) != 0) { + return NSGIF_ERR_DATA; + } + data += 3; + + if (strict == true) { + if ((strncmp((const char *) data, "87a", 3) != 0) && + (strncmp((const char *) data, "89a", 3) != 0)) { + return NSGIF_ERR_DATA; + } + } + data += 3; + + *pos = data; + return NSGIF_OK; +} + +/** + * Read Logical Screen Descriptor. + * + * 7-byte Logical Screen Descriptor is: + * + * +0 SHORT Logical Screen Width + * +2 SHORT Logical Screen Height + * +4 CHAR __Packed Fields__ + * 1BIT Global Colour Table Flag + * 3BITS Colour Resolution + * 1BIT Sort Flag + * 3BITS Size of Global Colour Table + * +5 CHAR Background Colour Index + * +6 CHAR Pixel Aspect Ratio + * + * \param[in] gif The GIF object we're decoding. + * \param[in,out] pos The current buffer position, updated on success. + * \return NSGIF_OK on success, appropriate error otherwise. + */ +static nsgif_error nsgif__parse_logical_screen_descriptor( + struct nsgif *gif, + const uint8_t **pos) +{ + const uint8_t *data = *pos; + size_t len = gif->buf + gif->buf_len - data; + + if (len < 7) { + return NSGIF_ERR_END_OF_DATA; + } + + gif->info.width = data[0] | (data[1] << 8); + gif->info.height = data[2] | (data[3] << 8); + gif->info.global_palette = data[4] & NSGIF_COLOUR_TABLE_MASK; + gif->colour_table_size = 2 << (data[4] & NSGIF_COLOUR_TABLE_SIZE_MASK); + gif->bg_index = data[5]; + gif->aspect_ratio = data[6]; + gif->info.loop_max = 1; + + *pos += 7; + return NSGIF_OK; +} + +/* exported function documented in nsgif.h */ +nsgif_error nsgif_data_scan( + nsgif_t *gif, + size_t size, + const uint8_t *data) +{ + const uint8_t *nsgif_data; + nsgif_error ret; + uint32_t frames; + + if (gif->data_complete) { + return NSGIF_ERR_DATA_COMPLETE; + } + + /* Initialize values */ + gif->buf_len = size; + gif->buf = data; + + /* Get our current processing position */ + nsgif_data = gif->buf + gif->buf_pos; + + /* See if we should initialise the GIF */ + if (gif->buf_pos == 0) { + /* We want everything to be NULL before we start so we've no + * chance of freeing bad pointers (paranoia) + */ + gif->frame_image = NULL; + gif->frames = NULL; + gif->frame_holders = 0; + + /* The caller may have been lazy and not reset any values */ + gif->info.frame_count = 0; + gif->frame_count_partial = 0; + gif->decoded_frame = NSGIF_FRAME_INVALID; + gif->frame = NSGIF_FRAME_INVALID; + + ret = nsgif__parse_header(gif, &nsgif_data, false); + if (ret != NSGIF_OK) { + return ret; + } + + ret = nsgif__parse_logical_screen_descriptor(gif, &nsgif_data); + if (ret != NSGIF_OK) { + return ret; + } + + /* Remember we've done this now */ + gif->buf_pos = nsgif_data - gif->buf; + + /* Some broken GIFs report the size as the screen size they + * were created in. As such, we detect for the common cases and + * set the sizes as 0 if they are found which results in the + * GIF being the maximum size of the frames. + */ + if (((gif->info.width == 640) && (gif->info.height == 480)) || + ((gif->info.width == 640) && (gif->info.height == 512)) || + ((gif->info.width == 800) && (gif->info.height == 600)) || + ((gif->info.width == 1024) && (gif->info.height == 768)) || + ((gif->info.width == 1280) && (gif->info.height == 1024)) || + ((gif->info.width == 1600) && (gif->info.height == 1200)) || + ((gif->info.width == 0) || (gif->info.height == 0)) || + ((gif->info.width > 2048) || (gif->info.height > 2048))) { + gif->info.width = 1; + gif->info.height = 1; + } + + /* Set the first colour to a value that will never occur in + * reality so we know if we've processed it + */ + gif->global_colour_table[0] = NSGIF_PROCESS_COLOURS; + + /* Check if the GIF has no frame data (13-byte header + 1-byte + * termination block) Although generally useless, the GIF + * specification does not expressly prohibit this + */ + if (gif->buf_len == gif->buf_pos + 1) { + if (nsgif_data[0] == NSGIF_TRAILER) { + return NSGIF_OK; + } + } + } + + /* Do the colour map if we haven't already. As the top byte is always + * 0xff or 0x00 depending on the transparency we know if it's been + * filled in. + */ + if (gif->global_colour_table[0] == NSGIF_PROCESS_COLOURS) { + /* Check for a global colour map signified by bit 7 */ + if (gif->info.global_palette) { + size_t remaining = gif->buf + gif->buf_len - nsgif_data; + size_t used; + + ret = nsgif__colour_table_extract( + gif->global_colour_table, + &gif->colour_layout, + gif->colour_table_size, + nsgif_data, remaining, &used, true); + if (ret != NSGIF_OK) { + return ret; + } + + nsgif_data += used; + gif->buf_pos = (nsgif_data - gif->buf); + } else { + /* Create a default colour table with the first two + * colours as black and white. */ + uint8_t *entry = (uint8_t *)gif->global_colour_table; + + /* Black */ + entry[gif->colour_layout.r] = 0x00; + entry[gif->colour_layout.g] = 0x00; + entry[gif->colour_layout.b] = 0x00; + entry[gif->colour_layout.a] = 0xFF; + + entry += sizeof(uint32_t); + + /* White */ + entry[gif->colour_layout.r] = 0xFF; + entry[gif->colour_layout.g] = 0xFF; + entry[gif->colour_layout.b] = 0xFF; + entry[gif->colour_layout.a] = 0xFF; + + gif->colour_table_size = 2; + } + + if (gif->info.global_palette && + gif->bg_index < gif->colour_table_size) { + size_t bg_idx = gif->bg_index; + gif->info.background = gif->global_colour_table[bg_idx]; + } else { + gif->info.background = gif->global_colour_table[0]; + } + } + + if (gif->lzw_ctx == NULL) { + lzw_result res = lzw_context_create( + (struct lzw_ctx **)&gif->lzw_ctx); + if (res != LZW_OK) { + return nsgif__error_from_lzw(res); + } + } + + /* Try to initialise all frames. */ + do { + frames = gif->info.frame_count; + ret = nsgif__process_frame(gif, frames, false); + } while (gif->info.frame_count > frames); + + if (ret == NSGIF_ERR_END_OF_DATA && gif->info.frame_count > 0) { + ret = NSGIF_OK; + } + + return ret; +} + +/* exported function documented in nsgif.h */ +void nsgif_data_complete( + nsgif_t *gif) +{ + if (gif->data_complete == false) { + uint32_t start = gif->info.frame_count; + uint32_t end = gif->frame_count_partial; + + for (uint32_t f = start; f < end; f++) { + nsgif_frame *frame = &gif->frames[f]; + + if (frame->lzw_data_length > 0) { + frame->info.display = true; + gif->info.frame_count = f + 1; + + if (f == 0) { + frame->info.transparency = true; + } + break; + } + } + } + + gif->data_complete = true; +} + +static void nsgif__redraw_rect_extend( + const nsgif_rect_t *frame, + nsgif_rect_t *redraw) +{ + if (redraw->x1 == 0 || redraw->y1 == 0) { + *redraw = *frame; + } else { + if (redraw->x0 > frame->x0) { + redraw->x0 = frame->x0; + } + if (redraw->x1 < frame->x1) { + redraw->x1 = frame->x1; + } + if (redraw->y0 > frame->y0) { + redraw->y0 = frame->y0; + } + if (redraw->y1 < frame->y1) { + redraw->y1 = frame->y1; + } + } +} + +static uint32_t nsgif__frame_next( + const nsgif_t *gif, + bool partial, + uint32_t frame) +{ + uint32_t frames = partial ? + gif->frame_count_partial : + gif->info.frame_count; + + if (frames == 0) { + return NSGIF_FRAME_INVALID; + } + + frame++; + return (frame >= frames) ? 0 : frame; +} + +static nsgif_error nsgif__next_displayable_frame( + const nsgif_t *gif, + uint32_t *frame, + uint32_t *delay) +{ + uint32_t next = *frame; + + do { + next = nsgif__frame_next(gif, false, next); + if (next <= *frame && *frame != NSGIF_FRAME_INVALID && + gif->data_complete == false) { + return NSGIF_ERR_END_OF_DATA; + + } else if (next == *frame || next == NSGIF_FRAME_INVALID) { + return NSGIF_ERR_FRAME_DISPLAY; + } + + if (delay != NULL) { + *delay += gif->frames[next].info.delay; + } + + } while (gif->frames[next].info.display == false); + + *frame = next; + return NSGIF_OK; +} + +static inline bool nsgif__animation_complete(int count, int max) +{ + if (max == 0) { + return false; + } + + return (count >= max); +} + +nsgif_error nsgif_reset( + nsgif_t *gif) +{ + gif->loop_count = 0; + gif->frame = NSGIF_FRAME_INVALID; + + return NSGIF_OK; +} + +/* exported function documented in nsgif.h */ +nsgif_error nsgif_frame_prepare( + nsgif_t *gif, + nsgif_rect_t *area, + uint32_t *delay_cs, + uint32_t *frame_new) +{ + nsgif_error ret; + nsgif_rect_t rect = { + .x1 = 0, + .y1 = 0, + }; + uint32_t delay = 0; + uint32_t frame = gif->frame; + + if (gif->frame != NSGIF_FRAME_INVALID && + gif->frame < gif->info.frame_count && + gif->frames[gif->frame].info.display) { + rect = gif->frames[gif->frame].info.rect; + } + + if (nsgif__animation_complete( + gif->loop_count, + gif->info.loop_max)) { + return NSGIF_ERR_ANIMATION_END; + } + + ret = nsgif__next_displayable_frame(gif, &frame, &delay); + if (ret != NSGIF_OK) { + return ret; + } + + if (gif->frame != NSGIF_FRAME_INVALID && frame < gif->frame) { + gif->loop_count++; + } + + if (gif->data_complete) { + /* Check for last frame, which has infinite delay. */ + + if (gif->info.frame_count == 1) { + delay = NSGIF_INFINITE; + } else if (gif->info.loop_max != 0) { + uint32_t frame_next = frame; + + ret = nsgif__next_displayable_frame(gif, + &frame_next, NULL); + if (ret != NSGIF_OK) { + return ret; + } + + if (gif->data_complete && frame_next < frame) { + if (nsgif__animation_complete( + gif->loop_count + 1, + gif->info.loop_max)) { + delay = NSGIF_INFINITE; + } + } + } + } + + gif->frame = frame; + nsgif__redraw_rect_extend(&gif->frames[frame].info.rect, &rect); + + if (delay < gif->delay_min) { + delay = gif->delay_default; + } + + *frame_new = gif->frame; + *delay_cs = delay; + *area = rect; + + return NSGIF_OK; +} + +/* exported function documented in nsgif.h */ +nsgif_error nsgif_frame_decode( + nsgif_t *gif, + uint32_t frame, + nsgif_bitmap_t **bitmap) +{ + uint32_t start_frame; + nsgif_error ret = NSGIF_OK; + + if (frame >= gif->info.frame_count) { + return NSGIF_ERR_BAD_FRAME; + } + + if (gif->decoded_frame == frame) { + *bitmap = gif->frame_image; + return NSGIF_OK; + + } else if (gif->decoded_frame >= frame || + gif->decoded_frame == NSGIF_FRAME_INVALID) { + /* Can skip to first frame or restart. */ + start_frame = 0; + } else { + start_frame = nsgif__frame_next( + gif, false, gif->decoded_frame); + } + + for (uint32_t f = start_frame; f <= frame; f++) { + ret = nsgif__process_frame(gif, f, true); + if (ret != NSGIF_OK) { + return ret; + } + } + + *bitmap = gif->frame_image; + return ret; +} + +/* exported function documented in nsgif.h */ +const nsgif_info_t *nsgif_get_info(const nsgif_t *gif) +{ + return &gif->info; +} + +/* exported function documented in nsgif.h */ +const nsgif_frame_info_t *nsgif_get_frame_info( + const nsgif_t *gif, + uint32_t frame) +{ + if (frame >= gif->info.frame_count) { + return NULL; + } + + return &gif->frames[frame].info; +} + +/* exported function documented in nsgif.h */ +void nsgif_global_palette( + const nsgif_t *gif, + uint32_t table[NSGIF_MAX_COLOURS], + size_t *entries) +{ + size_t len = sizeof(*table) * NSGIF_MAX_COLOURS; + + memcpy(table, gif->global_colour_table, len); + *entries = gif->colour_table_size; +} + +/* exported function documented in nsgif.h */ +bool nsgif_local_palette( + const nsgif_t *gif, + uint32_t frame, + uint32_t table[NSGIF_MAX_COLOURS], + size_t *entries) +{ + const nsgif_frame *f; + + if (frame >= gif->frame_count_partial) { + return false; + } + + f = &gif->frames[frame]; + if (f->info.local_palette == false) { + return false; + } + + *entries = 2 << (f->flags & NSGIF_COLOUR_TABLE_SIZE_MASK); + nsgif__colour_table_decode(table, &gif->colour_layout, + *entries, gif->buf + f->colour_table_offset); + + return true; +} + +/* exported function documented in nsgif.h */ +const char *nsgif_strerror(nsgif_error err) +{ + static const char *const str[] = { + [NSGIF_OK] = "Success", + [NSGIF_ERR_OOM] = "Out of memory", + [NSGIF_ERR_DATA] = "Invalid source data", + [NSGIF_ERR_BAD_FRAME] = "Requested frame does not exist", + [NSGIF_ERR_DATA_FRAME] = "Invalid frame data", + [NSGIF_ERR_END_OF_DATA] = "Unexpected end of GIF source data", + [NSGIF_ERR_DATA_COMPLETE] = "Can't add data to completed GIF", + [NSGIF_ERR_FRAME_DISPLAY] = "Frame can't be displayed", + [NSGIF_ERR_ANIMATION_END] = "Animation complete", + }; + + if (err >= NSGIF_ARRAY_LEN(str) || str[err] == NULL) { + return "Unknown error"; + } + + return str[err]; +} + +/* exported function documented in nsgif.h */ +const char *nsgif_str_disposal(enum nsgif_disposal disposal) +{ + static const char *const str[] = { + [NSGIF_DISPOSAL_UNSPECIFIED] = "Unspecified", + [NSGIF_DISPOSAL_NONE] = "None", + [NSGIF_DISPOSAL_RESTORE_BG] = "Restore background", + [NSGIF_DISPOSAL_RESTORE_PREV] = "Restore previous", + [NSGIF_DISPOSAL_RESTORE_QUIRK] = "Restore quirk", + }; + + if (disposal >= NSGIF_ARRAY_LEN(str) || str[disposal] == NULL) { + return "Unspecified"; + } + + return str[disposal]; +} diff --git a/libs/libnsgif/libnsgif.c b/libs/libnsgif/libnsgif.c deleted file mode 100644 index 6bf9956b..00000000 --- a/libs/libnsgif/libnsgif.c +++ /dev/null @@ -1,1169 +0,0 @@ -/* - * Copyright 2004 Richard Wilson - * Copyright 2008 Sean Fox - * - * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/ - * Licenced under the MIT License, - * http://www.opensource.org/licenses/mit-license.php - */ - -#include -#include -#include -#include -#include -#include -#include "libnsgif.h" -#include "utils/log.h" - -#include "lzw.h" - -/** - * - * \file - * \brief GIF image decoder - * - * The GIF format is thoroughly documented; a full description can be found at - * http://www.w3.org/Graphics/GIF/spec-gif89a.txt - * - * \todo Plain text and comment extensions should be implemented. - */ - - -/** Maximum colour table size */ -#define GIF_MAX_COLOURS 256 - -/** Internal flag that the colour table needs to be processed */ -#define GIF_PROCESS_COLOURS 0xaa000000 - -/** Internal flag that a frame is invalid/unprocessed */ -#define GIF_INVALID_FRAME -1 - -/** Transparent colour */ -#define GIF_TRANSPARENT_COLOUR 0x00 - -/* GIF Flags */ -#define GIF_FRAME_COMBINE 1 -#define GIF_FRAME_CLEAR 2 -#define GIF_FRAME_RESTORE 3 -#define GIF_FRAME_QUIRKS_RESTORE 4 - -#define GIF_IMAGE_SEPARATOR 0x2c -#define GIF_INTERLACE_MASK 0x40 -#define GIF_COLOUR_TABLE_MASK 0x80 -#define GIF_COLOUR_TABLE_SIZE_MASK 0x07 -#define GIF_EXTENSION_INTRODUCER 0x21 -#define GIF_EXTENSION_GRAPHIC_CONTROL 0xf9 -#define GIF_DISPOSAL_MASK 0x1c -#define GIF_TRANSPARENCY_MASK 0x01 -#define GIF_EXTENSION_COMMENT 0xfe -#define GIF_EXTENSION_PLAIN_TEXT 0x01 -#define GIF_EXTENSION_APPLICATION 0xff -#define GIF_BLOCK_TERMINATOR 0x00 -#define GIF_TRAILER 0x3b - -/** standard GIF header size */ -#define GIF_STANDARD_HEADER_SIZE 13 - - -/** - * Updates the sprite memory size - * - * \param gif The animation context - * \param width The width of the sprite - * \param height The height of the sprite - * \return GIF_INSUFFICIENT_MEMORY for a memory error GIF_OK for success - */ -static gif_result -gif_initialise_sprite(gif_animation *gif, - unsigned int width, - unsigned int height) -{ - unsigned int max_width; - unsigned int max_height; - struct bitmap *buffer; - - /* Check if we've changed */ - if ((width <= gif->width) && (height <= gif->height)) { - return GIF_OK; - } - - /* Get our maximum values */ - max_width = (width > gif->width) ? width : gif->width; - max_height = (height > gif->height) ? height : gif->height; - - /* Allocate some more memory */ - assert(gif->bitmap_callbacks.bitmap_create); - buffer = gif->bitmap_callbacks.bitmap_create(max_width, max_height); - if (buffer == NULL) { - return GIF_INSUFFICIENT_MEMORY; - } - - assert(gif->bitmap_callbacks.bitmap_destroy); - gif->bitmap_callbacks.bitmap_destroy(gif->frame_image); - gif->frame_image = buffer; - gif->width = max_width; - gif->height = max_height; - - /* Invalidate our currently decoded image */ - gif->decoded_frame = GIF_INVALID_FRAME; - return GIF_OK; -} - - -/** - * Attempts to initialise the frame's extensions - * - * \param gif The animation context - * \param frame The frame number - * @return GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the - * frame GIF_OK for successful initialisation. - */ -static gif_result -gif_initialise_frame_extensions(gif_animation *gif, const int frame) -{ - unsigned char *gif_data, *gif_end; - int gif_bytes; - unsigned int block_size; - - /* Get our buffer position etc. */ - gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position); - gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size); - - /* Initialise the extensions */ - while (gif_data < gif_end && gif_data[0] == GIF_EXTENSION_INTRODUCER) { - ++gif_data; - if ((gif_bytes = (gif_end - gif_data)) < 1) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - - /* Switch on extension label */ - switch (gif_data[0]) { - case GIF_EXTENSION_GRAPHIC_CONTROL: - /* 6-byte Graphic Control Extension is: - * - * +0 CHAR Graphic Control Label - * +1 CHAR Block Size - * +2 CHAR __Packed Fields__ - * 3BITS Reserved - * 3BITS Disposal Method - * 1BIT User Input Flag - * 1BIT Transparent Color Flag - * +3 SHORT Delay Time - * +5 CHAR Transparent Color Index - */ - if (gif_bytes < 6) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - - gif->frames[frame].frame_delay = gif_data[3] | (gif_data[4] << 8); - if (gif_data[2] & GIF_TRANSPARENCY_MASK) { - gif->frames[frame].transparency = true; - gif->frames[frame].transparency_index = gif_data[5]; - } - gif->frames[frame].disposal_method = ((gif_data[2] & GIF_DISPOSAL_MASK) >> 2); - /* I have encountered documentation and GIFs in the - * wild that use 0x04 to restore the previous frame, - * rather than the officially documented 0x03. I - * believe some (older?) software may even actually - * export this way. We handle this as a type of - * "quirks" mode. - */ - if (gif->frames[frame].disposal_method == GIF_FRAME_QUIRKS_RESTORE) { - gif->frames[frame].disposal_method = GIF_FRAME_RESTORE; - } - gif_data += (2 + gif_data[1]); - break; - - case GIF_EXTENSION_APPLICATION: - /* 14-byte+ Application Extension is: - * - * +0 CHAR Application Extension Label - * +1 CHAR Block Size - * +2 8CHARS Application Identifier - * +10 3CHARS Appl. Authentication Code - * +13 1-256 Application Data (Data sub-blocks) - */ - if (gif_bytes < 17) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - if ((gif_data[1] == 0x0b) && - (strncmp((const char *) gif_data + 2, - "NETSCAPE2.0", 11) == 0) && - (gif_data[13] == 0x03) && - (gif_data[14] == 0x01)) { - gif->loop_count = gif_data[15] | (gif_data[16] << 8); - } - gif_data += (2 + gif_data[1]); - break; - - case GIF_EXTENSION_COMMENT: - /* Move the pointer to the first data sub-block Skip 1 - * byte for the extension label - */ - ++gif_data; - break; - - default: - /* Move the pointer to the first data sub-block Skip 2 - * bytes for the extension label and size fields Skip - * the extension size itself - */ - if (gif_bytes < 2) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - gif_data += (2 + gif_data[1]); - } - - /* Repeatedly skip blocks until we get a zero block or run out - * of data This data is ignored by this gif decoder - */ - gif_bytes = (gif_end - gif_data); - block_size = 0; - while (gif_data < gif_end && gif_data[0] != GIF_BLOCK_TERMINATOR) { - block_size = gif_data[0] + 1; - if ((gif_bytes -= block_size) < 0) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - gif_data += block_size; - } - ++gif_data; - } - - /* Set buffer position and return */ - gif->buffer_position = (gif_data - gif->gif_data); - return GIF_OK; -} - - -/** - * Attempts to initialise the next frame - * - * \param gif The animation context - * \return error code - * - GIF_INSUFFICIENT_DATA for insufficient data to do anything - * - GIF_FRAME_DATA_ERROR for GIF frame data error - * - GIF_INSUFFICIENT_MEMORY for insufficient memory to process - * - GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame - * - GIF_DATA_ERROR for GIF error (invalid frame header) - * - GIF_OK for successful decoding - * - GIF_WORKING for successful decoding if more frames are expected -*/ -static gif_result gif_initialise_frame(gif_animation *gif) -{ - int frame; - gif_frame *temp_buf; - - unsigned char *gif_data, *gif_end; - int gif_bytes; - unsigned int flags = 0; - unsigned int width, height, offset_x, offset_y; - unsigned int block_size, colour_table_size; - bool first_image = true; - gif_result return_value; - - /* Get the frame to decode and our data position */ - frame = gif->frame_count; - - /* Get our buffer position etc. */ - gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position); - gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size); - gif_bytes = (gif_end - gif_data); - - /* Check if we've finished */ - if ((gif_bytes > 0) && (gif_data[0] == GIF_TRAILER)) { - return GIF_OK; - } - - /* Check if there is enough data remaining. The shortest block of data - * is a 4-byte comment extension + 1-byte block terminator + 1-byte gif - * trailer - */ - if (gif_bytes < 6) { - return GIF_INSUFFICIENT_DATA; - } - - /* We could theoretically get some junk data that gives us millions of - * frames, so we ensure that we don't have a silly number - */ - if (frame > 4096) { - return GIF_FRAME_DATA_ERROR; - } - - /* Get some memory to store our pointers in etc. */ - if ((int)gif->frame_holders <= frame) { - /* Allocate more memory */ - temp_buf = (gif_frame *)realloc(gif->frames, (frame + 1) * sizeof(gif_frame)); - if (temp_buf == NULL) { - return GIF_INSUFFICIENT_MEMORY; - } - gif->frames = temp_buf; - gif->frame_holders = frame + 1; - } - - /* Store our frame pointer. We would do it when allocating except we - * start off with one frame allocated so we can always use realloc. - */ - gif->frames[frame].frame_pointer = gif->buffer_position; - gif->frames[frame].display = false; - gif->frames[frame].virgin = true; - gif->frames[frame].disposal_method = 0; - gif->frames[frame].transparency = false; - gif->frames[frame].frame_delay = 100; - gif->frames[frame].redraw_required = false; - - /* Invalidate any previous decoding we have of this frame */ - if (gif->decoded_frame == frame) { - gif->decoded_frame = GIF_INVALID_FRAME; - } - - /* We pretend to initialise the frames, but really we just skip over - * all the data contained within. This is all basically a cut down - * version of gif_decode_frame that doesn't have any of the LZW bits in - * it. - */ - - /* Initialise any extensions */ - gif->buffer_position = gif_data - gif->gif_data; - return_value = gif_initialise_frame_extensions(gif, frame); - if (return_value != GIF_OK) { - return return_value; - } - gif_data = (gif->gif_data + gif->buffer_position); - gif_bytes = (gif_end - gif_data); - - /* Check if we've finished */ - if ((gif_bytes = (gif_end - gif_data)) < 1) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - - if (gif_data[0] == GIF_TRAILER) { - gif->buffer_position = (gif_data - gif->gif_data); - gif->frame_count = frame + 1; - return GIF_OK; - } - - /* If we're not done, there should be an image descriptor */ - if (gif_data[0] != GIF_IMAGE_SEPARATOR) { - return GIF_FRAME_DATA_ERROR; - } - - /* Do some simple boundary checking */ - if (gif_bytes < 10) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - offset_x = gif_data[1] | (gif_data[2] << 8); - offset_y = gif_data[3] | (gif_data[4] << 8); - width = gif_data[5] | (gif_data[6] << 8); - height = gif_data[7] | (gif_data[8] << 8); - - /* Set up the redraw characteristics. We have to check for extending - * the area due to multi-image frames. - */ - if (!first_image) { - if (gif->frames[frame].redraw_x > offset_x) { - gif->frames[frame].redraw_width += (gif->frames[frame].redraw_x - offset_x); - gif->frames[frame].redraw_x = offset_x; - } - - if (gif->frames[frame].redraw_y > offset_y) { - gif->frames[frame].redraw_height += (gif->frames[frame].redraw_y - offset_y); - gif->frames[frame].redraw_y = offset_y; - } - - if ((offset_x + width) > (gif->frames[frame].redraw_x + gif->frames[frame].redraw_width)) { - gif->frames[frame].redraw_width = (offset_x + width) - gif->frames[frame].redraw_x; - } - - if ((offset_y + height) > (gif->frames[frame].redraw_y + gif->frames[frame].redraw_height)) { - gif->frames[frame].redraw_height = (offset_y + height) - gif->frames[frame].redraw_y; - } - } else { - first_image = false; - gif->frames[frame].redraw_x = offset_x; - gif->frames[frame].redraw_y = offset_y; - gif->frames[frame].redraw_width = width; - gif->frames[frame].redraw_height = height; - } - - /* if we are clearing the background then we need to redraw enough to - * cover the previous frame too - */ - gif->frames[frame].redraw_required = ((gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) || - (gif->frames[frame].disposal_method == GIF_FRAME_RESTORE)); - - /* Boundary checking - shouldn't ever happen except with junk data */ - if (gif_initialise_sprite(gif, (offset_x + width), (offset_y + height))) { - return GIF_INSUFFICIENT_MEMORY; - } - - /* Decode the flags */ - flags = gif_data[9]; - colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK); - - /* Move our data onwards and remember we've got a bit of this frame */ - gif_data += 10; - gif_bytes = (gif_end - gif_data); - gif->frame_count_partial = frame + 1; - - /* Skip the local colour table */ - if (flags & GIF_COLOUR_TABLE_MASK) { - gif_data += 3 * colour_table_size; - if ((gif_bytes = (gif_end - gif_data)) < 0) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - } - - /* Ensure we have a correct code size */ - if (gif_bytes < 1) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - if (gif_data[0] > LZW_CODE_MAX) { - return GIF_DATA_ERROR; - } - - /* Move our pointer to the actual image data */ - gif_data++; - --gif_bytes; - - /* Repeatedly skip blocks until we get a zero block or run out of data - * These blocks of image data are processed later by gif_decode_frame() - */ - block_size = 0; - while (block_size != 1) { - if (gif_bytes < 1) return GIF_INSUFFICIENT_FRAME_DATA; - block_size = gif_data[0] + 1; - /* Check if the frame data runs off the end of the file */ - if ((int)(gif_bytes - block_size) < 0) { - /* Try to recover by signaling the end of the gif. - * Once we get garbage data, there is no logical way to - * determine where the next frame is. It's probably - * better to partially load the gif than not at all. - */ - if (gif_bytes >= 2) { - gif_data[0] = 0; - gif_data[1] = GIF_TRAILER; - gif_bytes = 1; - ++gif_data; - break; - } else { - return GIF_INSUFFICIENT_FRAME_DATA; - } - } else { - gif_bytes -= block_size; - gif_data += block_size; - } - } - - /* Add the frame and set the display flag */ - gif->buffer_position = gif_data - gif->gif_data; - gif->frame_count = frame + 1; - gif->frames[frame].display = true; - - /* Check if we've finished */ - if (gif_bytes < 1) { - return GIF_INSUFFICIENT_FRAME_DATA; - } else { - if (gif_data[0] == GIF_TRAILER) { - return GIF_OK; - } - } - return GIF_WORKING; -} - - - - -/** - * Skips the frame's extensions (which have been previously initialised) - * - * \param gif The animation context - * \return GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the - * frame GIF_OK for successful decoding - */ -static gif_result gif_skip_frame_extensions(gif_animation *gif) -{ - unsigned char *gif_data, *gif_end; - int gif_bytes; - unsigned int block_size; - - /* Get our buffer position etc. */ - gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position); - gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size); - gif_bytes = (gif_end - gif_data); - - /* Skip the extensions */ - while (gif_data < gif_end && gif_data[0] == GIF_EXTENSION_INTRODUCER) { - ++gif_data; - if (gif_data >= gif_end) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - - /* Switch on extension label */ - switch(gif_data[0]) { - case GIF_EXTENSION_COMMENT: - /* Move the pointer to the first data sub-block - * 1 byte for the extension label - */ - ++gif_data; - break; - - default: - /* Move the pointer to the first data sub-block 2 bytes - * for the extension label and size fields Skip the - * extension size itself - */ - if (gif_data + 1 >= gif_end) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - gif_data += (2 + gif_data[1]); - } - - /* Repeatedly skip blocks until we get a zero block or run out - * of data This data is ignored by this gif decoder - */ - gif_bytes = (gif_end - gif_data); - block_size = 0; - while (gif_data < gif_end && gif_data[0] != GIF_BLOCK_TERMINATOR) { - block_size = gif_data[0] + 1; - if ((gif_bytes -= block_size) < 0) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - gif_data += block_size; - } - ++gif_data; - } - - /* Set buffer position and return */ - gif->buffer_position = (gif_data - gif->gif_data); - return GIF_OK; -} - -static unsigned int gif_interlaced_line(int height, int y) { - if ((y << 3) < height) { - return (y << 3); - } - y -= ((height + 7) >> 3); - if ((y << 3) < (height - 4)) { - return (y << 3) + 4; - } - y -= ((height + 3) >> 3); - if ((y << 2) < (height - 2)) { - return (y << 2) + 2; - } - y -= ((height + 1) >> 2); - return (y << 1) + 1; -} - - -static gif_result gif_error_from_lzw(lzw_result l_res) -{ - static const gif_result g_res[] = { - [LZW_OK] = GIF_OK, - [LZW_OK_EOD] = GIF_END_OF_FRAME, - [LZW_NO_MEM] = GIF_INSUFFICIENT_MEMORY, - [LZW_NO_DATA] = GIF_INSUFFICIENT_FRAME_DATA, - [LZW_EOI_CODE] = GIF_FRAME_DATA_ERROR, - [LZW_BAD_ICODE] = GIF_FRAME_DATA_ERROR, - [LZW_BAD_CODE] = GIF_FRAME_DATA_ERROR, - }; - return g_res[l_res]; -} - - -/** - * decode a gif frame - * - * \param gif gif animation context. - * \param frame The frame number to decode. - * \param clear_image flag for image data being cleared instead of plotted. - */ -static gif_result -gif_internal_decode_frame(gif_animation *gif, - unsigned int frame, - bool clear_image) -{ - unsigned int index = 0; - unsigned char *gif_data, *gif_end; - int gif_bytes; - unsigned int width, height, offset_x, offset_y; - unsigned int flags, colour_table_size, interlace; - unsigned int *colour_table; - unsigned int *frame_data = 0; // Set to 0 for no warnings - unsigned int *frame_scanline; - unsigned int save_buffer_position; - unsigned int return_value = 0; - unsigned int x, y, decode_y, burst_bytes; - register unsigned char colour; - - /* Ensure this frame is supposed to be decoded */ - if (gif->frames[frame].display == false) { - return GIF_OK; - } - - /* Ensure the frame is in range to decode */ - if (frame > gif->frame_count_partial) { - return GIF_INSUFFICIENT_DATA; - } - - /* done if frame is already decoded */ - if ((!clear_image) && - ((int)frame == gif->decoded_frame)) { - return GIF_OK; - } - - /* Get the start of our frame data and the end of the GIF data */ - gif_data = gif->gif_data + gif->frames[frame].frame_pointer; - gif_end = gif->gif_data + gif->buffer_size; - gif_bytes = (gif_end - gif_data); - - /* - * Ensure there is a minimal amount of data to proceed. The shortest - * block of data is a 10-byte image descriptor + 1-byte gif trailer - */ - if (gif_bytes < 12) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - - /* Save the buffer position */ - save_buffer_position = gif->buffer_position; - gif->buffer_position = gif_data - gif->gif_data; - - /* Skip any extensions because they have allready been processed */ - if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) { - goto gif_decode_frame_exit; - } - gif_data = (gif->gif_data + gif->buffer_position); - gif_bytes = (gif_end - gif_data); - - /* Ensure we have enough data for the 10-byte image descriptor + 1-byte - * gif trailer - */ - if (gif_bytes < 12) { - return_value = GIF_INSUFFICIENT_FRAME_DATA; - goto gif_decode_frame_exit; - } - - /* 10-byte Image Descriptor is: - * - * +0 CHAR Image Separator (0x2c) - * +1 SHORT Image Left Position - * +3 SHORT Image Top Position - * +5 SHORT Width - * +7 SHORT Height - * +9 CHAR __Packed Fields__ - * 1BIT Local Colour Table Flag - * 1BIT Interlace Flag - * 1BIT Sort Flag - * 2BITS Reserved - * 3BITS Size of Local Colour Table - */ - if (gif_data[0] != GIF_IMAGE_SEPARATOR) { - return_value = GIF_DATA_ERROR; - goto gif_decode_frame_exit; - } - offset_x = gif_data[1] | (gif_data[2] << 8); - offset_y = gif_data[3] | (gif_data[4] << 8); - width = gif_data[5] | (gif_data[6] << 8); - height = gif_data[7] | (gif_data[8] << 8); - - /* Boundary checking - shouldn't ever happen except unless the data has - * been modified since initialisation. - */ - if ((offset_x + width > gif->width) || - (offset_y + height > gif->height)) { - return_value = GIF_DATA_ERROR; - goto gif_decode_frame_exit; - } - - /* Decode the flags */ - flags = gif_data[9]; - colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK); - interlace = flags & GIF_INTERLACE_MASK; - - /* Advance data pointer to next block either colour table or image - * data. - */ - gif_data += 10; - gif_bytes = (gif_end - gif_data); - - /* Set up the colour table */ - if (flags & GIF_COLOUR_TABLE_MASK) { - if (gif_bytes < (int)(3 * colour_table_size)) { - return_value = GIF_INSUFFICIENT_FRAME_DATA; - goto gif_decode_frame_exit; - } - colour_table = gif->local_colour_table; - if (!clear_image) { - for (index = 0; index < colour_table_size; index++) { - /* Gif colour map contents are r,g,b. - * - * We want to pack them bytewise into the - * colour table, such that the red component - * is in byte 0 and the alpha component is in - * byte 3. - */ - unsigned char *entry = - (unsigned char *) &colour_table[index]; - - entry[0] = gif_data[0]; /* r */ - entry[1] = gif_data[1]; /* g */ - entry[2] = gif_data[2]; /* b */ - entry[3] = 0xff; /* a */ - - gif_data += 3; - } - } else { - gif_data += 3 * colour_table_size; - } - gif_bytes = (gif_end - gif_data); - } else { - colour_table = gif->global_colour_table; - } - - /* Ensure sufficient data remains */ - if (gif_bytes < 1) { - return_value = GIF_INSUFFICIENT_FRAME_DATA; - goto gif_decode_frame_exit; - } - - /* check for an end marker */ - if (gif_data[0] == GIF_TRAILER) { - return_value = GIF_OK; - goto gif_decode_frame_exit; - } - - /* Get the frame data */ - assert(gif->bitmap_callbacks.bitmap_get_buffer); - frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image); - if (!frame_data) { - return GIF_INSUFFICIENT_MEMORY; - } - - /* If we are clearing the image we just clear, if not decode */ - if (!clear_image) { - lzw_result res; - const uint8_t *stack_base; - const uint8_t *stack_pos; - - /* Ensure we have enough data for a 1-byte LZW code size + - * 1-byte gif trailer - */ - if (gif_bytes < 2) { - return_value = GIF_INSUFFICIENT_FRAME_DATA; - goto gif_decode_frame_exit; - } - - /* If we only have a 1-byte LZW code size + 1-byte gif trailer, - * we're finished - */ - if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) { - return_value = GIF_OK; - goto gif_decode_frame_exit; - } - - /* If the previous frame's disposal method requires we restore - * the background colour or this is the first frame, clear - * the frame data - */ - if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) { - memset((char*)frame_data, - GIF_TRANSPARENT_COLOUR, - gif->width * gif->height * sizeof(int)); - gif->decoded_frame = frame; - /* The line below would fill the image with its - * background color, but because GIFs support - * transparency we likely wouldn't want to do that. */ - /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */ - } else if ((frame != 0) && - (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) { - return_value = gif_internal_decode_frame(gif, - (frame - 1), - true); - if (return_value != GIF_OK) { - goto gif_decode_frame_exit; - } - - } else if ((frame != 0) && - (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) { - /* - * If the previous frame's disposal method requires we - * restore the previous image, find the last image set - * to "do not dispose" and get that frame data - */ - int last_undisposed_frame = frame - 2; - while ((last_undisposed_frame >= 0) && - (gif->frames[last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE)) { - last_undisposed_frame--; - } - - /* If we don't find one, clear the frame data */ - if (last_undisposed_frame == -1) { - /* see notes above on transparency - * vs. background color - */ - memset((char*)frame_data, - GIF_TRANSPARENT_COLOUR, - gif->width * gif->height * sizeof(int)); - } else { - return_value = gif_internal_decode_frame(gif, last_undisposed_frame, false); - if (return_value != GIF_OK) { - goto gif_decode_frame_exit; - } - /* Get this frame's data */ - assert(gif->bitmap_callbacks.bitmap_get_buffer); - frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image); - if (!frame_data) { - return GIF_INSUFFICIENT_MEMORY; - } - } - } - gif->decoded_frame = frame; - gif->buffer_position = (gif_data - gif->gif_data) + 1; - - /* Initialise the LZW decoding */ - res = lzw_decode_init(gif->lzw_ctx, gif->gif_data, - gif->buffer_size, gif->buffer_position, - gif_data[0], &stack_base, &stack_pos); - if (res != LZW_OK) { - return gif_error_from_lzw(res); - } - - /* Decompress the data */ - for (y = 0; y < height; y++) { - if (interlace) { - decode_y = gif_interlaced_line(height, y) + offset_y; - } else { - decode_y = y + offset_y; - } - frame_scanline = frame_data + offset_x + (decode_y * gif->width); - - /* Rather than decoding pixel by pixel, we try to burst - * out streams of data to remove the need for end-of - * data checks every pixel. - */ - x = width; - while (x > 0) { - burst_bytes = (stack_pos - stack_base); - if (burst_bytes > 0) { - if (burst_bytes > x) { - burst_bytes = x; - } - x -= burst_bytes; - while (burst_bytes-- > 0) { - colour = *--stack_pos; - if (((gif->frames[frame].transparency) && - (colour != gif->frames[frame].transparency_index)) || - (!gif->frames[frame].transparency)) { - *frame_scanline = colour_table[colour]; - } - frame_scanline++; - } - } else { - res = lzw_decode(gif->lzw_ctx, &stack_pos); - if (res != LZW_OK) { - /* Unexpected end of frame, try to recover */ - if (res == LZW_OK_EOD) { - return_value = GIF_OK; - } else { - return_value = gif_error_from_lzw(res); - } - goto gif_decode_frame_exit; - } - } - } - } - } else { - /* Clear our frame */ - if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) { - for (y = 0; y < height; y++) { - frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width); - if (gif->frames[frame].transparency) { - memset(frame_scanline, - GIF_TRANSPARENT_COLOUR, - width * 4); - } else { - memset(frame_scanline, - colour_table[gif->background_index], - width * 4); - } - } - } - } -gif_decode_frame_exit: - - /* Check if we should test for optimisation */ - if (gif->frames[frame].virgin) { - if (gif->bitmap_callbacks.bitmap_test_opaque) { - gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image); - } else { - gif->frames[frame].opaque = false; - } - gif->frames[frame].virgin = false; - } - - if (gif->bitmap_callbacks.bitmap_set_opaque) { - gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque); - } - - if (gif->bitmap_callbacks.bitmap_modified) { - gif->bitmap_callbacks.bitmap_modified(gif->frame_image); - } - - /* Restore the buffer position */ - gif->buffer_position = save_buffer_position; - - return return_value; -} - - -/* exported function documented in libnsgif.h */ -void gif_create(gif_animation *gif, gif_bitmap_callback_vt *bitmap_callbacks) -{ - memset(gif, 0, sizeof(gif_animation)); - gif->bitmap_callbacks = *bitmap_callbacks; - gif->decoded_frame = GIF_INVALID_FRAME; -} - - -/* exported function documented in libnsgif.h */ -gif_result gif_initialise(gif_animation *gif, size_t size, unsigned char *data) -{ - unsigned char *gif_data; - unsigned int index; - gif_result return_value; - - /* Initialize values */ - gif->buffer_size = size; - gif->gif_data = data; - - if (gif->lzw_ctx == NULL) { - lzw_result res = lzw_context_create( - (struct lzw_ctx **)&gif->lzw_ctx); - if (res != LZW_OK) { - return gif_error_from_lzw(res); - } - } - - /* Check for sufficient data to be a GIF (6-byte header + 7-byte - * logical screen descriptor) - */ - if (gif->buffer_size < GIF_STANDARD_HEADER_SIZE) { - return GIF_INSUFFICIENT_DATA; - } - - /* Get our current processing position */ - gif_data = gif->gif_data + gif->buffer_position; - - /* See if we should initialise the GIF */ - if (gif->buffer_position == 0) { - /* We want everything to be NULL before we start so we've no - * chance of freeing bad pointers (paranoia) - */ - gif->frame_image = NULL; - gif->frames = NULL; - gif->local_colour_table = NULL; - gif->global_colour_table = NULL; - - /* The caller may have been lazy and not reset any values */ - gif->frame_count = 0; - gif->frame_count_partial = 0; - gif->decoded_frame = GIF_INVALID_FRAME; - - /* 6-byte GIF file header is: - * - * +0 3CHARS Signature ('GIF') - * +3 3CHARS Version ('87a' or '89a') - */ - if (strncmp((const char *) gif_data, "GIF", 3) != 0) { - return GIF_DATA_ERROR; - } - gif_data += 3; - - /* Ensure GIF reports version 87a or 89a */ - /* - if ((strncmp(gif_data, "87a", 3) != 0) && - (strncmp(gif_data, "89a", 3) != 0)) - LOG(("Unknown GIF format - proceeding anyway")); - */ - gif_data += 3; - - /* 7-byte Logical Screen Descriptor is: - * - * +0 SHORT Logical Screen Width - * +2 SHORT Logical Screen Height - * +4 CHAR __Packed Fields__ - * 1BIT Global Colour Table Flag - * 3BITS Colour Resolution - * 1BIT Sort Flag - * 3BITS Size of Global Colour Table - * +5 CHAR Background Colour Index - * +6 CHAR Pixel Aspect Ratio - */ - gif->width = gif_data[0] | (gif_data[1] << 8); - gif->height = gif_data[2] | (gif_data[3] << 8); - gif->global_colours = (gif_data[4] & GIF_COLOUR_TABLE_MASK); - gif->colour_table_size = (2 << (gif_data[4] & GIF_COLOUR_TABLE_SIZE_MASK)); - gif->background_index = gif_data[5]; - gif->aspect_ratio = gif_data[6]; - gif->loop_count = 1; - gif_data += 7; - - /* Some broken GIFs report the size as the screen size they - * were created in. As such, we detect for the common cases and - * set the sizes as 0 if they are found which results in the - * GIF being the maximum size of the frames. - */ - if (((gif->width == 640) && (gif->height == 480)) || - ((gif->width == 640) && (gif->height == 512)) || - ((gif->width == 800) && (gif->height == 600)) || - ((gif->width == 1024) && (gif->height == 768)) || - ((gif->width == 1280) && (gif->height == 1024)) || - ((gif->width == 1600) && (gif->height == 1200)) || - ((gif->width == 0) || (gif->height == 0)) || - ((gif->width > 2048) || (gif->height > 2048))) { - gif->width = 1; - gif->height = 1; - } - - /* Allocate some data irrespective of whether we've got any - * colour tables. We always get the maximum size in case a GIF - * is lying to us. It's far better to give the wrong colours - * than to trample over some memory somewhere. - */ - gif->global_colour_table = calloc(GIF_MAX_COLOURS, sizeof(unsigned int)); - gif->local_colour_table = calloc(GIF_MAX_COLOURS, sizeof(unsigned int)); - if ((gif->global_colour_table == NULL) || - (gif->local_colour_table == NULL)) { - gif_finalise(gif); - return GIF_INSUFFICIENT_MEMORY; - } - - /* Set the first colour to a value that will never occur in - * reality so we know if we've processed it - */ - gif->global_colour_table[0] = GIF_PROCESS_COLOURS; - - /* Check if the GIF has no frame data (13-byte header + 1-byte - * termination block) Although generally useless, the GIF - * specification does not expressly prohibit this - */ - if (gif->buffer_size == (GIF_STANDARD_HEADER_SIZE + 1)) { - if (gif_data[0] == GIF_TRAILER) { - return GIF_OK; - } else { - return GIF_INSUFFICIENT_DATA; - } - } - - /* Initialise enough workspace for a frame */ - if ((gif->frames = (gif_frame *)malloc(sizeof(gif_frame))) == NULL) { - gif_finalise(gif); - return GIF_INSUFFICIENT_MEMORY; - } - gif->frame_holders = 1; - - /* Initialise the bitmap header */ - assert(gif->bitmap_callbacks.bitmap_create); - gif->frame_image = gif->bitmap_callbacks.bitmap_create(gif->width, gif->height); - if (gif->frame_image == NULL) { - gif_finalise(gif); - return GIF_INSUFFICIENT_MEMORY; - } - - /* Remember we've done this now */ - gif->buffer_position = gif_data - gif->gif_data; - } - - /* Do the colour map if we haven't already. As the top byte is always - * 0xff or 0x00 depending on the transparency we know if it's been - * filled in. - */ - if (gif->global_colour_table[0] == GIF_PROCESS_COLOURS) { - /* Check for a global colour map signified by bit 7 */ - if (gif->global_colours) { - if (gif->buffer_size < (gif->colour_table_size * 3 + GIF_STANDARD_HEADER_SIZE)) { - return GIF_INSUFFICIENT_DATA; - } - for (index = 0; index < gif->colour_table_size; index++) { - /* Gif colour map contents are r,g,b. - * - * We want to pack them bytewise into the - * colour table, such that the red component - * is in byte 0 and the alpha component is in - * byte 3. - */ - unsigned char *entry = (unsigned char *) &gif-> - global_colour_table[index]; - - entry[0] = gif_data[0]; /* r */ - entry[1] = gif_data[1]; /* g */ - entry[2] = gif_data[2]; /* b */ - entry[3] = 0xff; /* a */ - - gif_data += 3; - } - gif->buffer_position = (gif_data - gif->gif_data); - } else { - /* Create a default colour table with the first two - * colours as black and white - */ - unsigned int *entry = gif->global_colour_table; - - entry[0] = 0x00000000; - /* Force Alpha channel to opaque */ - ((unsigned char *) entry)[3] = 0xff; - - entry[1] = 0xffffffff; - } - } - - /* Repeatedly try to initialise frames */ - while ((return_value = gif_initialise_frame(gif)) == GIF_WORKING); - - /* If there was a memory error tell the caller */ - if ((return_value == GIF_INSUFFICIENT_MEMORY) || - (return_value == GIF_DATA_ERROR)) { - return return_value; - } - - /* If we didn't have some frames then a GIF_INSUFFICIENT_DATA becomes a - * GIF_INSUFFICIENT_FRAME_DATA - */ - if ((return_value == GIF_INSUFFICIENT_DATA) && - (gif->frame_count_partial > 0)) { - return GIF_INSUFFICIENT_FRAME_DATA; - } - - /* Return how many we got */ - return return_value; -} - - -/* exported function documented in libnsgif.h */ -gif_result gif_decode_frame(gif_animation *gif, unsigned int frame) -{ - return gif_internal_decode_frame(gif, frame, false); -} - - -/* exported function documented in libnsgif.h */ -void gif_finalise(gif_animation *gif) -{ - /* Release all our memory blocks */ - if (gif->frame_image) { - assert(gif->bitmap_callbacks.bitmap_destroy); - gif->bitmap_callbacks.bitmap_destroy(gif->frame_image); - } - - gif->frame_image = NULL; - free(gif->frames); - gif->frames = NULL; - free(gif->local_colour_table); - gif->local_colour_table = NULL; - free(gif->global_colour_table); - gif->global_colour_table = NULL; - - lzw_context_destroy(gif->lzw_ctx); - gif->lzw_ctx = NULL; -} diff --git a/libs/libnsgif/libnsgif.h b/libs/libnsgif/libnsgif.h deleted file mode 100644 index 94221bd1..00000000 --- a/libs/libnsgif/libnsgif.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright 2004 Richard Wilson - * Copyright 2008 Sean Fox - * - * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/ - * Licenced under the MIT License, - * http://www.opensource.org/licenses/mit-license.php - */ - -/** - * \file - * Interface to progressive animated GIF file decoding. - */ - -#ifndef _LIBNSGIF_H_ -#define _LIBNSGIF_H_ - -#if defined (__cplusplus) -extern "C" { -#endif - -#include -#include - -/* Error return values */ -typedef enum { - GIF_WORKING = 1, - GIF_OK = 0, - GIF_INSUFFICIENT_FRAME_DATA = -1, - GIF_FRAME_DATA_ERROR = -2, - GIF_INSUFFICIENT_DATA = -3, - GIF_DATA_ERROR = -4, - GIF_INSUFFICIENT_MEMORY = -5, - GIF_FRAME_NO_DISPLAY = -6, - GIF_END_OF_FRAME = -7 -} gif_result; - -/** GIF frame data */ -typedef struct gif_frame { - /** whether the frame should be displayed/animated */ - bool display; - /** delay (in cs) before animating the frame */ - unsigned int frame_delay; - - /* Internal members are listed below */ - - /** offset (in bytes) to the GIF frame data */ - unsigned int frame_pointer; - /** whether the frame has previously been used */ - bool virgin; - /** whether the frame is totally opaque */ - bool opaque; - /** whether a forcable screen redraw is required */ - bool redraw_required; - /** how the previous frame should be disposed; affects plotting */ - unsigned char disposal_method; - /** whether we acknoledge transparency */ - bool transparency; - /** the index designating a transparent pixel */ - unsigned char transparency_index; - /** x co-ordinate of redraw rectangle */ - unsigned int redraw_x; - /** y co-ordinate of redraw rectangle */ - unsigned int redraw_y; - /** width of redraw rectangle */ - unsigned int redraw_width; - /** height of redraw rectangle */ - unsigned int redraw_height; -} gif_frame; - -/* API for Bitmap callbacks */ -typedef void* (*gif_bitmap_cb_create)(int width, int height); -typedef void (*gif_bitmap_cb_destroy)(void *bitmap); -typedef unsigned char* (*gif_bitmap_cb_get_buffer)(void *bitmap); -typedef void (*gif_bitmap_cb_set_opaque)(void *bitmap, bool opaque); -typedef bool (*gif_bitmap_cb_test_opaque)(void *bitmap); -typedef void (*gif_bitmap_cb_modified)(void *bitmap); - -/** Bitmap callbacks function table */ -typedef struct gif_bitmap_callback_vt { - /** Create a bitmap. */ - gif_bitmap_cb_create bitmap_create; - /** Free a bitmap. */ - gif_bitmap_cb_destroy bitmap_destroy; - /** Return a pointer to the pixel data in a bitmap. */ - gif_bitmap_cb_get_buffer bitmap_get_buffer; - - /* Members below are optional */ - - /** Sets whether a bitmap should be plotted opaque. */ - gif_bitmap_cb_set_opaque bitmap_set_opaque; - /** Tests whether a bitmap has an opaque alpha channel. */ - gif_bitmap_cb_test_opaque bitmap_test_opaque; - /** The bitmap image has changed, so flush any persistant cache. */ - gif_bitmap_cb_modified bitmap_modified; -} gif_bitmap_callback_vt; - -/** GIF animation data */ -typedef struct gif_animation { - /** LZW decode context */ - void *lzw_ctx; - /** callbacks for bitmap functions */ - gif_bitmap_callback_vt bitmap_callbacks; - /** pointer to GIF data */ - unsigned char *gif_data; - /** width of GIF (may increase during decoding) */ - unsigned int width; - /** heigth of GIF (may increase during decoding) */ - unsigned int height; - /** number of frames decoded */ - unsigned int frame_count; - /** number of frames partially decoded */ - unsigned int frame_count_partial; - /** decoded frames */ - gif_frame *frames; - /** current frame decoded to bitmap */ - int decoded_frame; - /** currently decoded image; stored as bitmap from bitmap_create callback */ - void *frame_image; - /** number of times to loop animation */ - int loop_count; - - /* Internal members are listed below */ - - /** current index into GIF data */ - unsigned int buffer_position; - /** total number of bytes of GIF data available */ - unsigned int buffer_size; - /** current number of frame holders */ - unsigned int frame_holders; - /** index in the colour table for the background colour */ - unsigned int background_index; - /** image aspect ratio (ignored) */ - unsigned int aspect_ratio; - /** size of colour table (in entries) */ - unsigned int colour_table_size; - /** whether the GIF has a global colour table */ - bool global_colours; - /** global colour table */ - unsigned int *global_colour_table; - /** local colour table */ - unsigned int *local_colour_table; -} gif_animation; - -/** - * Initialises necessary gif_animation members. - */ -void gif_create(gif_animation *gif, gif_bitmap_callback_vt *bitmap_callbacks); - -/** - * Initialises any workspace held by the animation and attempts to decode - * any information that hasn't already been decoded. - * If an error occurs, all previously decoded frames are retained. - * - * @return Error return value. - * - GIF_FRAME_DATA_ERROR for GIF frame data error - * - GIF_INSUFFICIENT_FRAME_DATA for insufficient data to process - * any more frames - * - GIF_INSUFFICIENT_MEMORY for memory error - * - GIF_DATA_ERROR for GIF error - * - GIF_INSUFFICIENT_DATA for insufficient data to do anything - * - GIF_OK for successful decoding - * - GIF_WORKING for successful decoding if more frames are expected - */ -gif_result gif_initialise(gif_animation *gif, size_t size, unsigned char *data); - -/** - * Decodes a GIF frame. - * - * @return Error return value. If a frame does not contain any image data, - * GIF_OK is returned and gif->current_error is set to - * GIF_FRAME_NO_DISPLAY - * - GIF_FRAME_DATA_ERROR for GIF frame data error - * - GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame - * - GIF_DATA_ERROR for GIF error (invalid frame header) - * - GIF_INSUFFICIENT_DATA for insufficient data to do anything - * - GIF_INSUFFICIENT_MEMORY for insufficient memory to process - * - GIF_OK for successful decoding - */ -gif_result gif_decode_frame(gif_animation *gif, unsigned int frame); - -/** - * Releases any workspace held by a gif - */ -void gif_finalise(gif_animation *gif); - -#if defined (__cplusplus) -} -#endif - -#endif diff --git a/libs/libnsgif/lzw.c b/libs/libnsgif/lzw.c old mode 100644 new mode 100755 index 31cf7d4e..3098ef50 --- a/libs/libnsgif/lzw.c +++ b/libs/libnsgif/lzw.c @@ -4,6 +4,7 @@ * http://www.opensource.org/licenses/mit-license.php * * Copyright 2017 Michael Drake + * Copyright 2021 Michael Drake */ #include @@ -20,6 +21,8 @@ * Decoder for GIF LZW data. */ +/** Maximum number of lzw table entries. */ +#define LZW_TABLE_ENTRY_MAX (1u << LZW_CODE_MAX) /** * Context for reading LZW data. @@ -33,57 +36,65 @@ * Note that an individual LZW code can be split over up to three sub-blocks. */ struct lzw_read_ctx { - const uint8_t *data; /**< Pointer to start of input data */ - uint32_t data_len; /**< Input data length */ - uint32_t data_sb_next; /**< Offset to sub-block size */ + const uint8_t *restrict data; /**< Pointer to start of input data */ + size_t data_len; /**< Input data length */ + size_t data_sb_next; /**< Offset to sub-block size */ const uint8_t *sb_data; /**< Pointer to current sub-block in data */ - uint32_t sb_bit; /**< Current bit offset in sub-block */ + size_t sb_bit; /**< Current bit offset in sub-block */ uint32_t sb_bit_count; /**< Bit count in sub-block */ }; /** - * LZW dictionary entry. + * LZW table entry. * - * Records in the dictionary are composed of 1 or more entries. - * Entries point to previous entries which can be followed to compose + * Records in the table are composed of 1 or more entries. + * Entries refer to the entry they extend which can be followed to compose * the complete record. To compose the record in reverse order, take - * the `last_value` from each entry, and move to the previous entry. - * If the previous_entry's index is < the current clear_code, then it + * the `value` from each entry, and move to the entry it extends. + * If the extended entries index is < the current clear_code, then it * is the last entry in the record. */ -struct lzw_dictionary_entry { - uint8_t last_value; /**< Last value for record ending at entry. */ - uint8_t first_value; /**< First value for entry's record. */ - uint16_t previous_entry; /**< Offset in dictionary to previous entry. */ +struct lzw_table_entry { + uint8_t value; /**< Last value for record ending at entry. */ + uint8_t first; /**< First value in entry's entire record. */ + uint16_t count; /**< Count of values in this entry's record. */ + uint16_t extends; /**< Offset in table to previous entry. */ }; /** * LZW decompression context. */ struct lzw_ctx { - /** Input reading context */ - struct lzw_read_ctx input; + struct lzw_read_ctx input; /**< Input reading context */ - uint32_t previous_code; /**< Code read from input previously. */ - uint32_t previous_code_first; /**< First value of previous code. */ + uint16_t prev_code; /**< Code read from input previously. */ + uint16_t prev_code_first; /**< First value of previous code. */ + uint16_t prev_code_count; /**< Total values for previous code. */ - uint32_t initial_code_size; /**< Starting LZW code size. */ - uint32_t current_code_size; /**< Current LZW code size. */ - uint32_t current_code_size_max; /**< Max code value for current size. */ + uint8_t initial_code_size; /**< Starting LZW code size. */ - uint32_t clear_code; /**< Special Clear code value */ - uint32_t eoi_code; /**< Special End of Information code value */ + uint8_t code_size; /**< Current LZW code size. */ + uint16_t code_max; /**< Max code value for current code size. */ - uint32_t current_entry; /**< Next position in table to fill. */ + uint16_t clear_code; /**< Special Clear code value */ + uint16_t eoi_code; /**< Special End of Information code value */ - /** Output value stack. */ - uint8_t stack_base[1 << LZW_CODE_MAX]; + uint16_t table_size; /**< Next position in table to fill. */ - /** LZW decode dictionary. Generated during decode. */ - struct lzw_dictionary_entry table[1 << LZW_CODE_MAX]; -}; + uint16_t output_code; /**< Code that has been partially output. */ + uint16_t output_left; /**< Number of values left for output_code. */ + + bool has_transparency; /**< Whether the image is opaque. */ + uint8_t transparency_idx; /**< Index representing transparency. */ + const uint32_t *restrict colour_map; /**< Index to colour mapping. */ + /** LZW code table. Generated during decode. */ + struct lzw_table_entry table[LZW_TABLE_ENTRY_MAX]; + + /** Output value stack. */ + uint8_t stack_base[LZW_TABLE_ENTRY_MAX]; +}; /* Exported function, documented in lzw.h */ lzw_result lzw_context_create(struct lzw_ctx **ctx) @@ -97,24 +108,22 @@ lzw_result lzw_context_create(struct lzw_ctx **ctx) return LZW_OK; } - /* Exported function, documented in lzw.h */ void lzw_context_destroy(struct lzw_ctx *ctx) { free(ctx); } - /** * Advance the context to the next sub-block in the input data. * * \param[in] ctx LZW reading context, updated on success. * \return LZW_OK or LZW_OK_EOD on success, appropriate error otherwise. */ -static lzw_result lzw__block_advance(struct lzw_read_ctx *ctx) +static lzw_result lzw__block_advance(struct lzw_read_ctx *restrict ctx) { - uint32_t block_size; - uint32_t next_block_pos = ctx->data_sb_next; + size_t block_size; + size_t next_block_pos = ctx->data_sb_next; const uint8_t *data_next = ctx->data + next_block_pos; if (next_block_pos >= ctx->data_len) { @@ -141,7 +150,6 @@ static lzw_result lzw__block_advance(struct lzw_read_ctx *ctx) return LZW_OK; } - /** * Get the next LZW code of given size from the raw input data. * @@ -152,31 +160,27 @@ static lzw_result lzw__block_advance(struct lzw_read_ctx *ctx) * \param[out] code_out Returns an LZW code on success. * \return LZW_OK or LZW_OK_EOD on success, appropriate error otherwise. */ -static inline lzw_result lzw__next_code( - struct lzw_read_ctx *ctx, - uint8_t code_size, - uint32_t *code_out) +static inline lzw_result lzw__read_code( + struct lzw_read_ctx *restrict ctx, + uint16_t code_size, + uint16_t *restrict code_out) { uint32_t code = 0; - uint8_t current_bit = ctx->sb_bit & 0x7; - uint8_t byte_advance = (current_bit + code_size) >> 3; + uint32_t current_bit = ctx->sb_bit & 0x7; - assert(byte_advance <= 2); - - if (ctx->sb_bit + code_size <= ctx->sb_bit_count) { - /* Fast path: code fully inside this sub-block */ + if (ctx->sb_bit + 24 <= ctx->sb_bit_count) { + /* Fast path: read three bytes from this sub-block */ const uint8_t *data = ctx->sb_data + (ctx->sb_bit >> 3); - switch (byte_advance) { - case 2: code |= data[2] << 16; /* Fall through */ - case 1: code |= data[1] << 8; /* Fall through */ - case 0: code |= data[0] << 0; - } + code |= *data++ << 0; + code |= *data++ << 8; + code |= *data << 16; ctx->sb_bit += code_size; } else { /* Slow path: code spans sub-blocks */ + uint8_t byte_advance = (current_bit + code_size) >> 3; uint8_t byte = 0; - uint8_t bits_remaining_0 = (code_size < (8 - current_bit)) ? - code_size : (8 - current_bit); + uint8_t bits_remaining_0 = (code_size < (8u - current_bit)) ? + code_size : (8u - current_bit); uint8_t bits_remaining_1 = code_size - bits_remaining_0; uint8_t bits_used[3] = { [0] = bits_remaining_0, @@ -184,6 +188,8 @@ static inline lzw_result lzw__next_code( [2] = bits_remaining_1 - 8, }; + assert(byte_advance <= 2); + while (true) { const uint8_t *data = ctx->sb_data; lzw_result res; @@ -213,165 +219,395 @@ static inline lzw_result lzw__next_code( return LZW_OK; } - /** - * Clear LZW code dictionary. + * Handle clear code. * - * \param[in] ctx LZW reading context, updated. - * \param[out] stack_pos_out Returns current stack position. + * \param[in] ctx LZW reading context, updated. + * \param[out] code_out Returns next code after a clear code. * \return LZW_OK or error code. */ -static lzw_result lzw__clear_codes( +static inline lzw_result lzw__handle_clear( struct lzw_ctx *ctx, - const uint8_t ** const stack_pos_out) + uint16_t *code_out) { - uint32_t code; - uint8_t *stack_pos; + uint16_t code; - /* Reset dictionary building context */ - ctx->current_code_size = ctx->initial_code_size + 1; - ctx->current_code_size_max = (1 << ctx->current_code_size) - 1;; - ctx->current_entry = (1 << ctx->initial_code_size) + 2; + /* Reset table building context */ + ctx->code_size = ctx->initial_code_size; + ctx->code_max = (1 << ctx->initial_code_size) - 1; + ctx->table_size = ctx->eoi_code + 1; /* There might be a sequence of clear codes, so process them all */ do { - lzw_result res = lzw__next_code(&ctx->input, - ctx->current_code_size, &code); + lzw_result res = lzw__read_code(&ctx->input, + ctx->code_size, &code); if (res != LZW_OK) { return res; } } while (code == ctx->clear_code); - /* The initial code must be from the initial dictionary. */ + /* The initial code must be from the initial table. */ if (code > ctx->clear_code) { return LZW_BAD_ICODE; } - /* Record this initial code as "previous" code, needed during decode. */ - ctx->previous_code = code; - ctx->previous_code_first = code; - - /* Reset the stack, and add first non-clear code added as first item. */ - stack_pos = ctx->stack_base; - *stack_pos++ = code; - - *stack_pos_out = stack_pos; + *code_out = code; return LZW_OK; } - /* Exported function, documented in lzw.h */ lzw_result lzw_decode_init( struct lzw_ctx *ctx, - const uint8_t *compressed_data, - uint32_t compressed_data_len, - uint32_t compressed_data_pos, - uint8_t code_size, - const uint8_t ** const stack_base_out, - const uint8_t ** const stack_pos_out) + uint8_t minimum_code_size, + const uint8_t *input_data, + size_t input_length, + size_t input_pos) { - struct lzw_dictionary_entry *table = ctx->table; + struct lzw_table_entry *table = ctx->table; + lzw_result res; + uint16_t code; + + if (minimum_code_size >= LZW_CODE_MAX) { + return LZW_BAD_ICODE; + } /* Initialise the input reading context */ - ctx->input.data = compressed_data; - ctx->input.data_len = compressed_data_len; - ctx->input.data_sb_next = compressed_data_pos; + ctx->input.data = input_data; + ctx->input.data_len = input_length; + ctx->input.data_sb_next = input_pos; ctx->input.sb_bit = 0; ctx->input.sb_bit_count = 0; - /* Initialise the dictionary building context */ - ctx->initial_code_size = code_size; + /* Initialise the table building context */ + ctx->initial_code_size = minimum_code_size + 1; - ctx->clear_code = (1 << code_size) + 0; - ctx->eoi_code = (1 << code_size) + 1; + ctx->clear_code = (1 << minimum_code_size) + 0; + ctx->eoi_code = (1 << minimum_code_size) + 1; - /* Initialise the standard dictionary entries */ - for (uint32_t i = 0; i < ctx->clear_code; ++i) { - table[i].first_value = i; - table[i].last_value = i; + ctx->output_left = 0; + + /* Initialise the standard table entries */ + for (uint16_t i = 0; i < ctx->clear_code; i++) { + table[i].first = i; + table[i].value = i; + table[i].count = 1; } - *stack_base_out = ctx->stack_base; - return lzw__clear_codes(ctx, stack_pos_out); -} + res = lzw__handle_clear(ctx, &code); + if (res != LZW_OK) { + return res; + } + + /* Store details of this code as "previous code" to the context. */ + ctx->prev_code_first = ctx->table[code].first; + ctx->prev_code_count = ctx->table[code].count; + ctx->prev_code = code; + + /* Add code to context for immediate output. */ + ctx->output_code = code; + ctx->output_left = 1; + ctx->has_transparency = false; + ctx->transparency_idx = 0; + ctx->colour_map = NULL; + + return LZW_OK; +} /* Exported function, documented in lzw.h */ -lzw_result lzw_decode(struct lzw_ctx *ctx, - const uint8_t ** const stack_pos_out) +lzw_result lzw_decode_init_map( + struct lzw_ctx *ctx, + uint8_t minimum_code_size, + uint32_t transparency_idx, + const uint32_t *colour_table, + const uint8_t *input_data, + size_t input_length, + size_t input_pos) +{ + lzw_result res; + + if (colour_table == NULL) { + return LZW_BAD_PARAM; + } + + res = lzw_decode_init(ctx, minimum_code_size, + input_data, input_length, input_pos); + if (res != LZW_OK) { + return res; + } + + ctx->has_transparency = (transparency_idx <= 0xFF); + ctx->transparency_idx = transparency_idx; + ctx->colour_map = colour_table; + + return LZW_OK; +} + +/** + * Create new table entry. + * + * \param[in] ctx LZW reading context, updated. + * \param[in] code Last value code for new table entry. + */ +static inline void lzw__table_add_entry( + struct lzw_ctx *ctx, + uint16_t code) +{ + struct lzw_table_entry *entry = &ctx->table[ctx->table_size]; + + entry->value = code; + entry->first = ctx->prev_code_first; + entry->count = ctx->prev_code_count + 1; + entry->extends = ctx->prev_code; + + ctx->table_size++; +} + +typedef uint32_t (*lzw_writer_fn)( + struct lzw_ctx *ctx, + void *restrict output_data, + uint32_t output_length, + uint32_t output_pos, + uint16_t code, + uint16_t left); + +/** + * Get the next LZW code and write its value(s) to output buffer. + * + * \param[in] ctx LZW reading context, updated. + * \param[in] write_fn Function for writing pixels to output. + * \param[in] output_data Array to write output values into. + * \param[in] output_length Size of output array. + * \param[in,out] output_written Number of values written. Updated on exit. + * \return LZW_OK on success, or appropriate error code otherwise. + */ +static inline lzw_result lzw__decode( + struct lzw_ctx *ctx, + lzw_writer_fn write_fn, + void *restrict output_data, + uint32_t output_length, + uint32_t *restrict output_written) { lzw_result res; - uint32_t code_new; - uint32_t code_out; - uint8_t last_value; - uint8_t *stack_pos = ctx->stack_base; - uint32_t clear_code = ctx->clear_code; - uint32_t current_entry = ctx->current_entry; - struct lzw_dictionary_entry * const table = ctx->table; + uint16_t code; /* Get a new code from the input */ - res = lzw__next_code(&ctx->input, ctx->current_code_size, &code_new); + res = lzw__read_code(&ctx->input, ctx->code_size, &code); if (res != LZW_OK) { return res; } /* Handle the new code */ - if (code_new == clear_code) { - /* Got Clear code */ - return lzw__clear_codes(ctx, stack_pos_out); - - } else if (code_new == ctx->eoi_code) { + if (code == ctx->eoi_code) { /* Got End of Information code */ return LZW_EOI_CODE; - } else if (code_new > current_entry) { + } else if (code > ctx->table_size) { /* Code is invalid */ return LZW_BAD_CODE; - } else if (code_new < current_entry) { - /* Code is in table */ - code_out = code_new; - last_value = table[code_new].first_value; + } else if (code == ctx->clear_code) { + res = lzw__handle_clear(ctx, &code); + if (res != LZW_OK) { + return res; + } + + } else if (ctx->table_size < LZW_TABLE_ENTRY_MAX) { + uint16_t size = ctx->table_size; + lzw__table_add_entry(ctx, (code < size) ? + ctx->table[code].first : + ctx->prev_code_first); + + /* Ensure code size is increased, if needed. */ + if (size == ctx->code_max && ctx->code_size < LZW_CODE_MAX) { + ctx->code_size++; + ctx->code_max = (1 << ctx->code_size) - 1; + } + } + + *output_written += write_fn(ctx, + output_data, output_length, *output_written, + code, ctx->table[code].count); + + /* Store details of this code as "previous code" to the context. */ + ctx->prev_code_first = ctx->table[code].first; + ctx->prev_code_count = ctx->table[code].count; + ctx->prev_code = code; + + return LZW_OK; +} + +/** + * Write values for this code to the output stack. + * + * If there isn't enough space in the output stack, this function will write + * the as many as it can into the output. If `ctx->output_left > 0` after + * this call, then there is more data for this code left to output. The code + * is stored to the context as `ctx->output_code`. + * + * \param[in] ctx LZW reading context, updated. + * \param[in] output_data Array to write output values into. + * \param[in] output_length length Size of output array. + * \param[in] output_used Current position in output array. + * \param[in] code LZW code to output values for. + * \param[in] left Number of values remaining to output for this code. + * \return Number of pixel values written. + */ +static inline uint32_t lzw__write_fn(struct lzw_ctx *ctx, + void *restrict output_data, + uint32_t output_length, + uint32_t output_used, + uint16_t code, + uint16_t left) +{ + uint8_t *restrict output_pos = (uint8_t *)output_data + output_used; + const struct lzw_table_entry * const table = ctx->table; + uint32_t space = output_length - output_used; + uint16_t count = left; + + if (count > space) { + left = count - space; + count = space; } else { - /* Code not in table */ - *stack_pos++ = ctx->previous_code_first; - code_out = ctx->previous_code; - last_value = ctx->previous_code_first; + left = 0; } - /* Add to the dictionary, only if there's space */ - if (current_entry < (1 << LZW_CODE_MAX)) { - struct lzw_dictionary_entry *entry = table + current_entry; - entry->last_value = last_value; - entry->first_value = ctx->previous_code_first; - entry->previous_entry = ctx->previous_code; - ctx->current_entry++; + ctx->output_code = code; + ctx->output_left = left; + + /* Skip over any values we don't have space for. */ + for (unsigned i = left; i != 0; i--) { + const struct lzw_table_entry *entry = table + code; + code = entry->extends; + } + + output_pos += count; + for (unsigned i = count; i != 0; i--) { + const struct lzw_table_entry *entry = table + code; + *--output_pos = entry->value; + code = entry->extends; + } + + return count; +} + +/* Exported function, documented in lzw.h */ +lzw_result lzw_decode(struct lzw_ctx *ctx, + const uint8_t *restrict *const restrict output_data, + uint32_t *restrict output_written) +{ + const uint32_t output_length = sizeof(ctx->stack_base); + + *output_written = 0; + *output_data = ctx->stack_base; + + if (ctx->output_left != 0) { + *output_written += lzw__write_fn(ctx, + ctx->stack_base, output_length, *output_written, + ctx->output_code, ctx->output_left); } - /* Ensure code size is increased, if needed. */ - if (current_entry == ctx->current_code_size_max) { - if (ctx->current_code_size < LZW_CODE_MAX) { - ctx->current_code_size++; - ctx->current_code_size_max = - (1 << ctx->current_code_size) - 1; + while (*output_written != output_length) { + lzw_result res = lzw__decode(ctx, lzw__write_fn, + ctx->stack_base, output_length, output_written); + if (res != LZW_OK) { + return res; } } - /* Store details of this code as "previous code" to the context. */ - ctx->previous_code_first = table[code_new].first_value; - ctx->previous_code = code_new; - - /* Put rest of data for this code on output stack. - * Note, in the case of "code not in table", the last entry of the - * current code has already been placed on the stack above. */ - while (code_out > clear_code) { - struct lzw_dictionary_entry *entry = table + code_out; - *stack_pos++ = entry->last_value; - code_out = entry->previous_entry; + return LZW_OK; +} + +/** + * Write colour mapped values for this code to the output. + * + * If there isn't enough space in the output stack, this function will write + * the as many as it can into the output. If `ctx->output_left > 0` after + * this call, then there is more data for this code left to output. The code + * is stored to the context as `ctx->output_code`. + * + * \param[in] ctx LZW reading context, updated. + * \param[in] output_data Array to write output values into. + * \param[in] output_length Size of output array. + * \param[in] output_used Current position in output array. + * \param[in] code LZW code to output values for. + * \param[in] left Number of values remaining to output for code. + * \return Number of pixel values written. + */ +static inline uint32_t lzw__map_write_fn(struct lzw_ctx *ctx, + void *restrict output_data, + uint32_t output_length, + uint32_t output_used, + uint16_t code, + uint16_t left) +{ + uint32_t *restrict output_pos = (uint32_t *)output_data + output_used; + const struct lzw_table_entry * const table = ctx->table; + uint32_t space = output_length - output_used; + uint16_t count = left; + + if (count > space) { + left = count - space; + count = space; + } else { + left = 0; + } + + ctx->output_code = code; + ctx->output_left = left; + + for (unsigned i = left; i != 0; i--) { + const struct lzw_table_entry *entry = table + code; + code = entry->extends; + } + + output_pos += count; + if (ctx->has_transparency) { + for (unsigned i = count; i != 0; i--) { + const struct lzw_table_entry *entry = table + code; + --output_pos; + if (entry->value != ctx->transparency_idx) { + *output_pos = ctx->colour_map[entry->value]; + } + code = entry->extends; + } + } else { + for (unsigned i = count; i != 0; i--) { + const struct lzw_table_entry *entry = table + code; + *--output_pos = ctx->colour_map[entry->value]; + code = entry->extends; + } + } + + return count; +} + +/* Exported function, documented in lzw.h */ +lzw_result lzw_decode_map(struct lzw_ctx *ctx, + uint32_t *restrict output_data, + uint32_t output_length, + uint32_t *restrict output_written) +{ + *output_written = 0; + + if (ctx->colour_map == NULL) { + return LZW_NO_COLOUR; + } + + if (ctx->output_left != 0) { + *output_written += lzw__map_write_fn(ctx, + output_data, output_length, *output_written, + ctx->output_code, ctx->output_left); + } + + while (*output_written != output_length) { + lzw_result res = lzw__decode(ctx, lzw__map_write_fn, + output_data, output_length, output_written); + if (res != LZW_OK) { + return res; + } } - *stack_pos++ = table[code_out].last_value; - *stack_pos_out = stack_pos; return LZW_OK; } diff --git a/libs/libnsgif/lzw.h b/libs/libnsgif/lzw.h old mode 100644 new mode 100755 index 385b4255..f19432f1 --- a/libs/libnsgif/lzw.h +++ b/libs/libnsgif/lzw.h @@ -4,6 +4,7 @@ * http://www.opensource.org/licenses/mit-license.php * * Copyright 2017 Michael Drake + * Copyright 2021 Michael Drake */ #ifndef LZW_H_ @@ -16,15 +17,12 @@ * Decoder for GIF LZW data. */ - /** Maximum LZW code size in bits */ #define LZW_CODE_MAX 12 - /* Declare lzw internal context structure */ struct lzw_ctx; - /** LZW decoding response codes */ typedef enum lzw_result { LZW_OK, /**< Success */ @@ -32,11 +30,12 @@ typedef enum lzw_result { LZW_NO_MEM, /**< Error: Out of memory */ LZW_NO_DATA, /**< Error: Out of data */ LZW_EOI_CODE, /**< Error: End of Information code */ + LZW_NO_COLOUR, /**< Error: No colour map provided. */ LZW_BAD_ICODE, /**< Error: Bad initial LZW code */ + LZW_BAD_PARAM, /**< Error: Bad function parameter. */ LZW_BAD_CODE, /**< Error: Bad LZW code */ } lzw_result; - /** * Create an LZW decompression context. * @@ -58,48 +57,81 @@ void lzw_context_destroy( /** * Initialise an LZW decompression context for decoding. * - * Caller owns neither `stack_base_out` or `stack_pos_out`. - * - * \param[in] ctx The LZW decompression context to initialise. - * \param[in] compressed_data The compressed data. - * \param[in] compressed_data_len Byte length of compressed data. - * \param[in] compressed_data_pos Start position in data. Must be position - * of a size byte at sub-block start. - * \param[in] code_size The initial LZW code size to use. - * \param[out] stack_base_out Returns base of decompressed data stack. - * \param[out] stack_pos_out Returns current stack position. - * There are `stack_pos_out - stack_base_out` - * current stack entries. + * \param[in] ctx The LZW decompression context to initialise. + * \param[in] minimum_code_size The LZW Minimum Code Size. + * \param[in] input_data The compressed data. + * \param[in] input_length Byte length of compressed data. + * \param[in] input_pos Start position in data. Must be position + * of a size byte at sub-block start. * \return LZW_OK on success, or appropriate error code otherwise. */ lzw_result lzw_decode_init( struct lzw_ctx *ctx, - const uint8_t *compressed_data, - uint32_t compressed_data_len, - uint32_t compressed_data_pos, - uint8_t code_size, - const uint8_t ** const stack_base_out, - const uint8_t ** const stack_pos_out); + uint8_t minimum_code_size, + const uint8_t *input_data, + size_t input_length, + size_t input_pos); /** - * Fill the LZW stack with decompressed data + * Read input codes until end of LZW context owned output buffer. + * + * Ensure anything in output is used before calling this, as anything + * there before this call will be trampled. * - * Ensure anything on the stack is used before calling this, as anything - * on the stack before this call will be trampled. + * \param[in] ctx LZW reading context, updated. + * \param[out] output_data Returns pointer to array of output values. + * \param[out] output_written Returns the number of values written to data. + * \return LZW_OK on success, or appropriate error code otherwise. + */ +lzw_result lzw_decode(struct lzw_ctx *ctx, + const uint8_t *restrict *const restrict output_data, + uint32_t *restrict output_written); + +/** + * Initialise an LZW decompression context for decoding to colour map values. * - * Caller does not own `stack_pos_out`. + * For transparency to work correctly, the given client buffer must have + * the values from the previous frame. The transparency_idx should be a value + * of 256 or above, if the frame does not have transparency. * - * \param[in] ctx LZW reading context, updated. - * \param[out] stack_pos_out Returns current stack position. - * Use with `stack_base_out` value from previous - * lzw_decode_init() call. - * There are `stack_pos_out - stack_base_out` - * current stack entries. + * \param[in] ctx The LZW decompression context to initialise. + * \param[in] minimum_code_size The LZW Minimum Code Size. + * \param[in] transparency_idx Index representing transparency. + * \param[in] colour_table Index to pixel colour mapping. + * \param[in] input_data The compressed data. + * \param[in] input_length Byte length of compressed data. + * \param[in] input_pos Start position in data. Must be position + * of a size byte at sub-block start. * \return LZW_OK on success, or appropriate error code otherwise. */ -lzw_result lzw_decode( +lzw_result lzw_decode_init_map( struct lzw_ctx *ctx, - const uint8_t ** const stack_pos_out); + uint8_t minimum_code_size, + uint32_t transparency_idx, + const uint32_t *colour_table, + const uint8_t *input_data, + size_t input_length, + size_t input_pos); +/** + * Read LZW codes into client buffer, mapping output to colours. + * + * The context must have been initialised using \ref lzw_decode_init_map + * before calling this function, in order to provide the colour mapping table + * and any transparency index. + * + * Ensure anything in output is used before calling this, as anything + * there before this call will be trampled. + * + * \param[in] ctx LZW reading context, updated. + * \param[in] output_data Client buffer to fill with colour mapped values. + * \param[in] output_length Size of output array. + * \param[out] output_written Returns the number of values written to data. + * \return LZW_OK on success, or appropriate error code otherwise. + */ +lzw_result lzw_decode_map(struct lzw_ctx *ctx, + uint32_t *restrict output_data, + uint32_t output_length, + uint32_t *restrict output_written); #endif diff --git a/libs/libnsgif/nsgif.h b/libs/libnsgif/nsgif.h new file mode 100755 index 00000000..57c09d30 --- /dev/null +++ b/libs/libnsgif/nsgif.h @@ -0,0 +1,535 @@ +/* + * Copyright 2004 Richard Wilson + * Copyright 2008 Sean Fox + * Copyright 2013-2022 Michael Drake + * + * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/ + * Licenced under the MIT License, + * http://www.opensource.org/licenses/mit-license.php + */ + +/** + * \file + * Interface to progressive animated GIF file decoding. + */ + +#ifndef NSNSGIF_H +#define NSNSGIF_H + +#if defined (__cplusplus) +extern "C" { +#endif + +#include +#include +#include + +/** Representation of infinity. */ +#define NSGIF_INFINITE (UINT32_MAX) + +/** Maximum colour table size */ +#define NSGIF_MAX_COLOURS 256 + +/** + * Opaque type used by LibNSGIF to represent a GIF object in memory. + */ +typedef struct nsgif nsgif_t; + +/** + * LibNSGIF rectangle structure. + * + * * Top left coordinate is `(x0, y0)`. + * * Width is `x1 - x0`. + * * Height is `y1 - y0`. + * * Units are pixels. + */ +typedef struct nsgif_rect { + /** x co-ordinate of redraw rectangle, left */ + uint32_t x0; + /** y co-ordinate of redraw rectangle, top */ + uint32_t y0; + /** x co-ordinate of redraw rectangle, right */ + uint32_t x1; + /** y co-ordinate of redraw rectangle, bottom */ + uint32_t y1; +} nsgif_rect_t; + +/** + * LibNSGIF return codes. + */ +typedef enum { + /** + * Success. + */ + NSGIF_OK, + + /** + * Out of memory error. + */ + NSGIF_ERR_OOM, + + /** + * GIF source data is invalid, and no frames are recoverable. + */ + NSGIF_ERR_DATA, + + /** + * Frame number is not valid. + */ + NSGIF_ERR_BAD_FRAME, + + /** + * GIF source data contained an error in a frame. + */ + NSGIF_ERR_DATA_FRAME, + + /** + * Unexpected end of GIF source data. + */ + NSGIF_ERR_END_OF_DATA, + + /** + * Can't supply more data after calling \ref nsgif_data_complete. + */ + NSGIF_ERR_DATA_COMPLETE, + + /** + * The current frame cannot be displayed. + */ + NSGIF_ERR_FRAME_DISPLAY, + + /** + * Indicates an animation is complete, and \ref nsgif_reset must be + * called to restart the animation from the beginning. + */ + NSGIF_ERR_ANIMATION_END, +} nsgif_error; + +/** + * NSGIF \ref nsgif_bitmap_t pixel format. + * + * All pixel formats are 32 bits per pixel (bpp). The different formats + * allow control over the ordering of the colour channels. All colour + * channels are 8 bits wide. + * + * Note that the GIF file format only supports an on/off mask, so the + * alpha (A) component (opacity) will always have a value of `0` (fully + * transparent) or `255` (fully opaque). + */ +typedef enum nsgif_bitmap_fmt { + /** Bite-wise RGBA: Byte order: 0xRR, 0xGG, 0xBB, 0xAA. */ + NSGIF_BITMAP_FMT_R8G8B8A8, + + /** Bite-wise BGRA: Byte order: 0xBB, 0xGG, 0xRR, 0xAA. */ + NSGIF_BITMAP_FMT_B8G8R8A8, + + /** Bite-wise ARGB: Byte order: 0xAA, 0xRR, 0xGG, 0xBB. */ + NSGIF_BITMAP_FMT_A8R8G8B8, + + /** Bite-wise ABGR: Byte order: 0xAA, 0xBB, 0xGG, 0xRR. */ + NSGIF_BITMAP_FMT_A8B8G8R8, + + /** + * 32-bit RGBA (0xRRGGBBAA). + * + * * On little endian host, same as \ref NSGIF_BITMAP_FMT_A8B8G8R8. + * * On big endian host, same as \ref NSGIF_BITMAP_FMT_R8G8B8A8. + */ + NSGIF_BITMAP_FMT_RGBA8888, + + /** + * 32-bit BGRA (0xBBGGRRAA). + * + * * On little endian host, same as \ref NSGIF_BITMAP_FMT_A8R8G8B8. + * * On big endian host, same as \ref NSGIF_BITMAP_FMT_B8G8R8A8. + */ + NSGIF_BITMAP_FMT_BGRA8888, + + /** + * 32-bit ARGB (0xAARRGGBB). + * + * * On little endian host, same as \ref NSGIF_BITMAP_FMT_B8G8R8A8. + * * On big endian host, same as \ref NSGIF_BITMAP_FMT_A8R8G8B8. + */ + NSGIF_BITMAP_FMT_ARGB8888, + + /** + * 32-bit BGRA (0xAABBGGRR). + * + * * On little endian host, same as \ref NSGIF_BITMAP_FMT_R8G8B8A8. + * * On big endian host, same as \ref NSGIF_BITMAP_FMT_A8B8G8R8. + */ + NSGIF_BITMAP_FMT_ABGR8888, +} nsgif_bitmap_fmt_t; + +/** + * Client bitmap type. + * + * These are client-created and destroyed, via the \ref nsgif_bitmap_cb_vt + * callbacks, but they are owned by a \ref nsgif_t. + * + * See \ref nsgif_bitmap_fmt for pixel format information. + * + * The bitmap may have a row_span greater than the bitmap width, but the + * difference between row span and width must be a whole number of pixels + * (a multiple of four bytes). + */ +typedef void nsgif_bitmap_t; + +/** Bitmap callbacks function table */ +typedef struct nsgif_bitmap_cb_vt { + /** + * Callback to create a bitmap with the given dimensions. + * + * \param[in] width Required bitmap width in pixels. + * \param[in] height Required bitmap height in pixels. + * \return pointer to client's bitmap structure or NULL on error. + */ + nsgif_bitmap_t* (*create)(int width, int height); + + /** + * Callback to free a bitmap. + * + * \param[in] bitmap The bitmap to destroy. + */ + void (*destroy)(nsgif_bitmap_t *bitmap); + + /** + * Get pointer to pixel buffer in a bitmap. + * + * The pixel buffer must be `(width + N) * height * sizeof(uint32_t)`. + * Where `N` is any number greater than or equal to 0. + * Note that the returned pointer to uint8_t must be 4-byte aligned. + * + * \param[in] bitmap The bitmap. + * \return pointer to bitmap's pixel buffer. + */ + uint8_t* (*get_buffer)(nsgif_bitmap_t *bitmap); + + /* The following functions are optional. */ + + /** + * Set whether a bitmap can be plotted opaque. + * + * \param[in] bitmap The bitmap. + * \param[in] opaque Whether the current frame is opaque. + */ + void (*set_opaque)(nsgif_bitmap_t *bitmap, bool opaque); + + /** + * Tests whether a bitmap has an opaque alpha channel. + * + * \param[in] bitmap The bitmap. + * \return true if the bitmap is opaque, false otherwise. + */ + bool (*test_opaque)(nsgif_bitmap_t *bitmap); + + /** + * Bitmap modified notification. + * + * \param[in] bitmap The bitmap. + */ + void (*modified)(nsgif_bitmap_t *bitmap); + + /** + * Get row span in pixels. + * + * If this callback is not provided, LibNSGIF will use the width. + * + * If row span is greater than width, this callback must be provided. + * + * \param[in] bitmap The bitmap. + */ + uint32_t (*get_rowspan)(nsgif_bitmap_t *bitmap); +} nsgif_bitmap_cb_vt; + +/** + * Convert an error code to a string. + * + * \param[in] err The error code to convert. + * \return String representation of given error code. + */ +const char *nsgif_strerror(nsgif_error err); + +/** + * Create the NSGIF object. + * + * \param[in] bitmap_vt Bitmap operation functions v-table. + * \param[in] bitmap_fmt Bitmap pixel format specification. + * \param[out] gif_out Return \ref nsgif_t object on success. + * + * \return NSGIF_OK on success, or appropriate error otherwise. + */ +nsgif_error nsgif_create( + const nsgif_bitmap_cb_vt *bitmap_vt, + nsgif_bitmap_fmt_t bitmap_fmt, + nsgif_t **gif_out); + +/** + * Free a NSGIF object. + * + * \param[in] gif The NSGIF to free. + */ +void nsgif_destroy(nsgif_t *gif); + +/** + * Scan the source image data. + * + * This is used to feed the source data into LibNSGIF. This must be called + * before calling \ref nsgif_frame_decode. + * + * It can be called multiple times with, with increasing sizes. If it is called + * several times, as more data is available (e.g. slow network fetch) the data + * already given to \ref nsgif_data_scan must be provided each time. + * + * Once all the data has been provided, call \ref nsgif_data_complete. + * + * For example, if you call \ref nsgif_data_scan with 25 bytes of data, and then + * fetch another 10 bytes, you would need to call \ref nsgif_data_scan with a + * size of 35 bytes, and the whole 35 bytes must be contiguous memory. It is + * safe to `realloc` the source buffer between calls to \ref nsgif_data_scan. + * (The actual data pointer is allowed to be different.) + * + * If an error occurs, all previously scanned frames are retained. + * + * Note that an error returned from this function is purely informational. + * So long as at least one frame is available, you can display frames. + * + * \param[in] gif The \ref nsgif_t object. + * \param[in] size Number of bytes in data. + * \param[in] data Raw source GIF data. + * + * \return NSGIF_OK on success, or appropriate error otherwise. + */ +nsgif_error nsgif_data_scan( + nsgif_t *gif, + size_t size, + const uint8_t *data); + +/** + * Tell libnsgif that all the gif data has been provided. + * + * Call this after calling \ref nsgif_data_scan with the the entire GIF + * source data. You can call \ref nsgif_data_scan multiple times up until + * this is called, and after this is called, \ref nsgif_data_scan will + * return an error. + * + * You can decode a GIF before this is called, however, it will fail to + * decode any truncated final frame data and will not perform loops when + * driven via \ref nsgif_frame_prepare (because it doesn't know if there + * will be more frames supplied in future data). + * + * \param[in] gif The \ref nsgif_t object. + */ +void nsgif_data_complete( + nsgif_t *gif); + +/** + * Prepare to show a frame. + * + * If this is the last frame of an animation with a finite loop count, the + * returned `delay_cs` will be \ref NSGIF_INFINITE, indicating that the frame + * should be shown forever. + * + * Note that if \ref nsgif_data_complete has not been called on this gif, + * animated GIFs will not loop back to the start. Instead it will return + * \ref NSGIF_ERR_END_OF_DATA. + * + * \param[in] gif The \ref nsgif_t object. + * \param[out] area The area in pixels that must be redrawn. + * \param[out] delay_cs Time to wait after frame_new before next frame in cs. + * \param[out] frame_new The frame to decode. + * + * \return NSGIF_OK on success, or appropriate error otherwise. + */ +nsgif_error nsgif_frame_prepare( + nsgif_t *gif, + nsgif_rect_t *area, + uint32_t *delay_cs, + uint32_t *frame_new); + +/** + * Decodes a GIF frame. + * + * \param[in] gif The \ref nsgif_t object. + * \param[in] frame The frame number to decode. + * \param[out] bitmap On success, returns pointer to the client-allocated, + * nsgif-owned client bitmap structure. + * + * \return NSGIF_OK on success, or appropriate error otherwise. + */ +nsgif_error nsgif_frame_decode( + nsgif_t *gif, + uint32_t frame, + nsgif_bitmap_t **bitmap); + +/** + * Reset a GIF animation. + * + * Some animations are only meant to loop N times, and then show the + * final frame forever. This function resets the loop and frame counters, + * so that the animation can be replayed without the overhead of recreating + * the \ref nsgif_t object and rescanning the raw data. + * + * \param[in] gif A \ref nsgif_t object. + * + * \return NSGIF_OK on success, or appropriate error otherwise. + */ +nsgif_error nsgif_reset( + nsgif_t *gif); + +/** + * Information about a GIF. + */ +typedef struct nsgif_info { + /** width of GIF (may increase during decoding) */ + uint32_t width; + /** height of GIF (may increase during decoding) */ + uint32_t height; + /** number of frames decoded */ + uint32_t frame_count; + /** number of times to play animation (zero means loop forever) */ + int loop_max; + /** background colour in same pixel format as \ref nsgif_bitmap_t. */ + uint32_t background; + /** whether the GIF has a global colour table */ + bool global_palette; +} nsgif_info_t; + +/** + * Frame disposal method. + * + * Clients do not need to know about this, it is provided purely for dumping + * raw information about GIF frames. + */ +enum nsgif_disposal { + NSGIF_DISPOSAL_UNSPECIFIED, /**< No disposal method specified. */ + NSGIF_DISPOSAL_NONE, /**< Frame remains. */ + NSGIF_DISPOSAL_RESTORE_BG, /**< Clear frame to background colour. */ + NSGIF_DISPOSAL_RESTORE_PREV, /**< Restore previous frame. */ + NSGIF_DISPOSAL_RESTORE_QUIRK, /**< Alias for NSGIF_DISPOSAL_RESTORE_PREV. */ +}; + +/** + * Convert a disposal method to a string. + * + * \param[in] disposal The disposal method to convert. + * \return String representation of given disposal method. + */ +const char *nsgif_str_disposal(enum nsgif_disposal disposal); + +/** + * Information about a GIF frame. + */ +typedef struct nsgif_frame_info { + /** whether the frame should be displayed/animated */ + bool display; + /** whether the frame may have transparency */ + bool transparency; + /** whether the frame has a local colour table */ + bool local_palette; + /** whether the frame is interlaced */ + bool interlaced; + /** Disposal method for previous frame; affects plotting */ + uint8_t disposal; + /** delay (in cs) before animating the frame */ + uint32_t delay; + + /** Frame's redraw rectangle. */ + nsgif_rect_t rect; +} nsgif_frame_info_t; + +/** + * Get information about a GIF from an \ref nsgif_t object. + * + * \param[in] gif The \ref nsgif_t object to get info for. + * + * \return The gif info, or NULL on error. + */ +const nsgif_info_t *nsgif_get_info(const nsgif_t *gif); + +/** + * Get information about a GIF from an \ref nsgif_t object. + * + * \param[in] gif The \ref nsgif_t object to get frame info for. + * \param[in] frame The frame number to get info for. + * + * \return The gif frame info, or NULL on error. + */ +const nsgif_frame_info_t *nsgif_get_frame_info( + const nsgif_t *gif, + uint32_t frame); + +/** + * Get the global colour palette. + * + * If the GIF has no global colour table, this will return the default + * colour palette. + * + * Colours in same pixel format as \ref nsgif_bitmap_t. + * + * \param[in] gif The \ref nsgif_t object. + * \param[out] table Client buffer to hold the colour table. + * \param[out] entries The number of used entries in the colour table. + */ +void nsgif_global_palette( + const nsgif_t *gif, + uint32_t table[NSGIF_MAX_COLOURS], + size_t *entries); + +/** + * Get the local colour palette for a frame. + * + * Frames may have no local palette. In this case they use the global palette. + * This function returns false if the frame has no local palette. + * + * Colours in same pixel format as \ref nsgif_bitmap_t. + * + * \param[in] gif The \ref nsgif_t object. + * \param[in] frame The frame to get the palette for. + * \param[out] table Client buffer to hold the colour table. + * \param[out] entries The number of used entries in the colour table. + * \return true if a palette is returned, false otherwise. + */ +bool nsgif_local_palette( + const nsgif_t *gif, + uint32_t frame, + uint32_t table[NSGIF_MAX_COLOURS], + size_t *entries); + +/** + * Configure handling of small frame delays. + * + * Historically people created GIFs with a tiny frame delay, however the slow + * hardware of the time meant they actually played much slower. As computers + * sped up, to prevent animations playing faster than intended, decoders came + * to ignore overly small frame delays. + * + * By default a \ref nsgif_frame_prepare() managed animation will override + * frame delays of less than 2 centiseconds with a default frame delay of + * 10 centiseconds. This matches the behaviour of web browsers and other + * renderers. + * + * Both the minimum and the default values can be overridden for a given GIF + * by the client. To get frame delays exactly as specified by the GIF file, set + * `delay_min` to zero. + * + * Note that this does not affect the frame delay in the frame info + * (\ref nsgif_frame_info_t) structure, which will always contain values + * specified by the GIF. + * + * \param[in] gif The \ref nsgif_t object to configure. + * \param[in] delay_min The minimum frame delay in centiseconds. + * \param[in] delay_default The delay to use if a frame delay is less than + * `delay_min`. + */ +void nsgif_set_frame_delay_behaviour( + nsgif_t *gif, + uint16_t delay_min, + uint16_t delay_default); + +#if defined (__cplusplus) +} +#endif + +#endif diff --git a/module_driver/ModuleMgrForKernel.S b/module_driver/ModuleMgrForKernel.S deleted file mode 100644 index 78c3800c..00000000 --- a/module_driver/ModuleMgrForKernel.S +++ /dev/null @@ -1,18 +0,0 @@ - .set noreorder - -#include "pspimport.s" - - IMPORT_START "ModuleMgrForKernel",0x00010000 - IMPORT_FUNC "ModuleMgrForKernel",0xFFB9B760,sceKernelLoadModule - IMPORT_FUNC "ModuleMgrForKernel",0xE6BF3960,sceKernelStartModule - IMPORT_FUNC "ModuleMgrForKernel",0x0D053026,sceKernelUnloadModule - IMPORT_FUNC "ModuleMgrForKernel",0x32292450,_sceKernelLoadModuleWithApitype2 - IMPORT_FUNC "ModuleMgrForKernel",0xE3CCC6EA,sceKernelLoadModule_620 - IMPORT_FUNC "ModuleMgrForKernel",0xDF8FFFAB,sceKernelStartModule_620 - IMPORT_FUNC "ModuleMgrForKernel",0x9CEB18C4,sceKernelUnloadModule_620 - IMPORT_FUNC "ModuleMgrForKernel",0xB691CB9F,sceKernelLoadModuleWithApitype2_620 - IMPORT_FUNC "ModuleMgrForKernel",0x939E4270,sceKernelLoadModule_660 - IMPORT_FUNC "ModuleMgrForKernel",0x3FF74DF1,sceKernelStartModule_660 - IMPORT_FUNC "ModuleMgrForKernel",0x387E3CA9,sceKernelUnloadModule_660 - IMPORT_FUNC "ModuleMgrForKernel",0x2B7FC10D,sceKernelLoadModuleWithApitype2_660 - IMPORT_FUNC "ModuleMgrForKernel",0x4E62C48A,sceKernelLoadModuleBufferForKernel diff --git a/module_driver/module_driver.c b/module_driver/module_driver.c deleted file mode 100644 index 7bda7c63..00000000 --- a/module_driver/module_driver.c +++ /dev/null @@ -1,21 +0,0 @@ -#include - -PSP_MODULE_INFO("module_driver", PSP_MODULE_KERNEL, 1, 0); -PSP_NO_CREATE_MAIN_THREAD(); - -SceUID sceKernelLoadModuleBufferForKernel(SceSize size, void *buf, s32 flag, const SceKernelLMOption *option); - -int pspKernelLoadModuleBuffer(SceSize size, void *buf, s32 flag, const SceKernelLMOption *option) { - int k1 = pspSdkSetK1(0); - int ret = sceKernelLoadModuleBufferForKernel(size, buf, flag, option); - pspSdkSetK1(k1); - return ret; -} - -int module_start(SceSize args, void *argp) { - return 0; -} - -int module_stop(void) { - return 0; -}