diff --git a/.gitignore b/.gitignore index 9208658..59e812b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /build/* /ctruLua.* -/doc/html/* \ No newline at end of file +/doc/html/* +/doc/sublimetext/* diff --git a/Makefile b/Makefile index d7bd5ff..b4d10bb 100644 --- a/Makefile +++ b/Makefile @@ -29,15 +29,17 @@ include $(DEVKITARM)/3ds_rules #--------------------------------------------------------------------------------- TARGET := ctruLua BUILD := build -SOURCES := source libs/lua-5.3.1/src +SOURCES := source libs/lua-5.3.2/src libs/tremor DATA := data -INCLUDES := include libs/lua-5.3.1/src libs/lzlib +INCLUDES := include libs/lua-5.3.2/src libs/lzlib libs/tremor #ROMFS := romfs APP_TITLE := ctruLua APP_DESCRIPTION := Lua for the 3DS. Yes, it works. APP_AUTHOR := Reuh, Firew0lf and NegiAD ICON := icon.png +APP_VERSION := $(shell git describe --abbrev=0 --tags) +LASTCOMMIT := $(shell git rev-parse HEAD) #--------------------------------------------------------------------------------- # options for code generation @@ -48,14 +50,17 @@ CFLAGS := -g -Wall -O2 -mword-relocations -std=gnu11 \ -fomit-frame-pointer -ffast-math \ $(ARCH) -CFLAGS += $(INCLUDE) -DARM11 -D_3DS +CFLAGS += $(INCLUDE) -DARM11 -D_3DS -DCTR_VERSION=\"$(APP_VERSION)\" -DCTR_BUILD=\"$(LASTCOMMIT)\" +ifneq ($(ROMFS),) + CFLAGS += -DROMFS +endif CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++11 ASFLAGS := -g $(ARCH) LDFLAGS = -specs=3dsx.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) -LIBS := -lsfil -ljpeg -lsftd -lfreetype -lpng -lz -lsf2d -lctru -lm +LIBS := -lsfil -ljpeg -lsftd -lfreetype -lpng -lz -lsf2d -lctru -logg -lm #--------------------------------------------------------------------------------- # list of directories containing libraries, this must be the top level containing @@ -65,7 +70,8 @@ LIBDIRS := $(CTRULIB) $(PORTLIBS) \ $(CURDIR)/libs/3ds_portlibs/build \ $(CURDIR)/libs/sf2dlib/libsf2d \ $(CURDIR)/libs/sftdlib/libsftd \ - $(CURDIR)/libs/sfillib/libsfil + $(CURDIR)/libs/sfillib/libsfil \ + $(CURDIR)/libs/stb #--------------------------------------------------------------------------------- # no real need to edit anything past this point unless you need to add additional @@ -129,7 +135,6 @@ endif ifneq ($(ROMFS),) export _3DSXFLAGS += --romfs=$(CURDIR)/$(ROMFS) - CFLAGS += -DROMFS endif .PHONY: $(BUILD) clean all @@ -142,7 +147,7 @@ $(BUILD): @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile build-portlibs: - @make -C libs/3ds_portlibs zlib freetype libjpeg-turbo libpng + @make -C libs/3ds_portlibs zlib freetype libjpeg-turbo libpng libogg build-sf2dlib: @make -C libs/sf2dlib/libsf2d build @@ -166,8 +171,17 @@ build-all: @make build build-doc: + @echo Building HTML documentation... + @make build-doc-html + @echo Building SublimeText documentation... + @make build-doc-st + +build-doc-html: @cd doc/ && ldoc . && cd .. +build-doc-st: + @cd doc/ && ldoc . --template ./ --ext sublime-completions --dir ./sublimetext/ && cd .. + #--------------------------------------------------------------------------------- clean: @rm -fr $(BUILD) $(TARGET).3dsx $(OUTPUT).smdh $(TARGET).elf @@ -197,8 +211,17 @@ clean-all: @make clean clean-doc: + @echo Cleaning HTML documentation... + @make clean-doc-html + @echo Cleaning SublimeText documentation... + @make clean-doc-st + +clean-doc-html: @rm -rf doc/html +clean-doc-st: + @rm -rf doc/sublimetext + #--------------------------------------------------------------------------------- else diff --git a/README.md b/README.md index 6232241..75dbf84 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,86 @@ # ctrµLua - -Everything is in the Wiki. +![banner](https://www.dropbox.com/s/cqmtoohyx6t7q7c/banner.png?raw=1) Warning: the 'u' in the repo's name is a 'µ', not a 'u'. -#### Builds ![build status](http://thomas99.no-ip.org:3000/ctrulua.png) +### Users part -* Most recent working build: [here](http://thomas99.no-ip.org:3000/ctrulua/builds/latest/artifacts/ctruLua.3dsx) (warning: only tested with Citra, sometimes on real hardware). -* See http://thomas99.no-ip.org:3000/ctrulua for all the builds. +#### How to install + +* Download ctruLua.zip from the [releases](https://github.com/ctruLua/ctruLua/releases) (for something stable) or the [CI server](https://reuh.eu/ctrulua/ci/ctrulua) (for more features) +* Unzip it on your SD card, in a folder inside your homebrews folder; if you use HBL, extract it in `/3ds/ctrulua/` +* Put some scripts wherever you want, just remember where +* Launch CtrµLua from your homebrew launcher +* Use the shell to run your scripts + +### Homebrewers part + +#### Builds ![build status](https://reuh.eu/ctrulua/ci/ctrulua.png) + +* Most recent working build: [ctruLua.3dsx](https://reuh.eu/ctrulua/ci/ctrulua/builds/latest/artifacts/ctruLua.3dsx) +* See [https://reuh.eu/ctrulua/ci/ctrulua](https://reuh.eu/ctrulua/ci/ctrulua) for all the builds. + +#### Hello world + +```Lua +local ctr = require("ctr") +local gfx = require("ctr.gfx") +local hid = require("ctr.hid") + +while ctr.run() do + hid.read() + local keys = hid.keys() + if keys.held.start then break end + + gfx.start(gfx.TOP) + gfx.text(2, 2, "Hello, world !") + gfx.stop() + + gfx.render() +end +``` +This script will print "Hello, world !" on the top screen, and will exit if the user presses Start. +This is the "graphical" version; there's also a text-only version, based on the console: +```Lua +local ctr = require("ctr") +local gfx = require("ctr.gfx") +local hid = require("ctr.hid") + +gfx.console() +print("Hello, world !") + +while ctr.run() do + hid.read() + local keys = hid.keys() + if keys.held.start then break end + + gfx.render() +end + +gfx.disableConsole() +``` + +#### Lua API Documentation + +* An online version of the documentation can be found [here](https://reuh.eu/ctrulua/latest/html/) +* To build the documentation, run `make build-doc-html` (requires [LDoc](https://github.com/stevedonovan/LDoc)). + +### Developers part #### Build instructions * Setup your environment as shown here : http://3dbrew.org/wiki/Setting_up_Development_Environment * Clone this repository and run the command `make build-all` to build all the dependencies. -* If you only made changes to ctrµLua, run `make` to rebuild ctµLua without rebuilding all the dependencies. +* If you only made changes to ctrµLua, run `make` to rebuild ctrµLua without rebuilding all the dependencies. May not work under Windows. -#### Lua API Documentation +### Credits -* An online version of the documentation can be found here : http://thomas99.no-ip.org/ctrulua -* To build the documentation, run `make build-doc` (requires [LDoc](https://github.com/stevedonovan/LDoc)). - -#### Based on ctrulib by smealum: [https://github.com/smealum/ctrulib](https://github.com/smealum/ctrulib) +* __Smealum__ and everyone who worked on the ctrulib: [https://github.com/smealum/ctrulib](https://github.com/smealum/ctrulib) +* __Xerpi__ for the [sf2dlib](https://github.com/xerpi/sf2dlib), [sftdlib](https://github.com/xerpi/sftdlib) and [sfillib](https://github.com/xerpi/sfillib) +* __All the [Citra](https://citra-emu.org/) developers__ +* __Everyone who worked on [DevKitARM](http://devkitpro.org/)__ +* __Nothings__ for the [stb](https://github.com/nothings/stb) libs +* Everyone who worked on the other libs we use + diff --git a/doc/config.ld b/doc/config.ld index 13c1958..cfecb59 100644 --- a/doc/config.ld +++ b/doc/config.ld @@ -11,7 +11,7 @@ format = "markdown" plain = true -- Input files -topics = "../README.md" +topics = {"../README.md", "filepicker.md"} file = "../source/" examples = "../sdcard/3ds/ctruLua/examples/" manual_url = "file://../libs/lua-5.3.1/doc/manual.html" diff --git a/doc/filepicker.md b/doc/filepicker.md new file mode 100644 index 0000000..7f89590 --- /dev/null +++ b/doc/filepicker.md @@ -0,0 +1,93 @@ +# filepicker +## filePicker([workingDirectory[, bindings[, callbacks[, ...]]]]) +### Argument: workingDirectory +The directory that shows up first in the file browser. +If this is nil, ctr.fs.getDirectory() is used. +The recommended form is sdmc:/path/ or romfs:/path/, but it can be a simple /path/ instead. +#### Possible values +- string +- nil + +### Argument: bindings +A table, list of filetypes and key bindings related to these filetypes. +#### Format +``` +{ + __default, __directory, [Lua regexp] = { + [keys from ctr.hid.keys()] = { + function + string + }... + __name = string + }... +} +``` + +The Lua regexp is matched against the filename to determine if it is of this type. +__directory is the "file type" for directories +__default is the "file type" for files that cannot be matched with any other. + Also, every other type inherits the values it doesn't define from __default. +A file type contains the human-readable name (__name) of the type, displayed on the bottom screen, + as well as an optional binding for each key. +The optional binding is formed of an anonymous function, followed by the key's label to be displayed on the bottom screen, + if the label is nil, the key isn't displayed but still bound. + +The function is defined as-is: +##### function(externalConfig, selected, bindingPattern, bindingKey) +externalConfig.workingDirectory is the active directory for filePicker, doesn't necessarily match ctrµLua's. +externalConfig.bindings, externalConfig.callbacks and externalConfig.additionalArguments all are the arguments passed to filePicker, + starting from position 2. +externalConfig.fileList is the list of files currently displayed by filePicker, in the same format as is returned by ctr.fs.listDirectory(). +selected.inList is the absolute position of the cursor in externalConfig.fileList +selected.offset is the number of items skipped for display from fileList +bindingPattern is the [Lua regexp] defined earlier, and bindingKey the [key] that triggered this event. +This function may return the same thing as filePicker itself (Defined later here), or nothing. If it returns nothing, +filePicker will keep running, if it returns the same returns as filePicker, filePicker will exit, returning these values. + +#### Notes +Sane defaults are set if you did not set them otherwise: +__default.x quits filePicker, returning the current directory, "__directory", nil and "x". See the returns to understand what this means. +__directory.a changes directories to that directory. + +### Argument: callbacks +A table defining the callbacks ran at the end of each of the equivalent phases. +#### Format +``` +{ + drawTop, drawBottom, eventHandler = function +} +``` +All of these take the following parameters: (externalConfig, selected) +They have the meaning defined earlier. + +#### Notes +Although drawTop and drawBottom are ran at the end of their respective functions, +eventHandler is not, as it cannot be without being run repeatedly, so it's run at the beginning of +the ACTUAL eventHandler instead of its end. + +### Argument: ... +Additional parameters. All of these are aggregated orderly in externalConfig.additionalArguments and passed around as explained earlier. +They have no specific meaning unless defined so by event handling functions. + +### Return 1: selectedPath +The path selected by the either, may or may not have the sdmc:/romfs: prefix, depending on your input. +A string. + +### Return 2: bindingPattern +The pattern the file matched to. You can use this to know exactly which kind of file you're dealing with +A string. + +### Return 3: mode +Included handlers may have it be "open", in case you're opening an existing file, "new" in case the user wants to create a new file, +Or nil. A "nil" is assumed to mean that the user didn't pick anything. +A string or nil. + +### Return 4: key +The key that triggered the event that made filePicker exit. +A string. + +## Included event handlers you have available are: +- filepicker.changeDirectory - The name is on the tin, change workingDirectory to the active element and refresh the file list for that path. +- filepicker.openFile - Quits and returns as described by this document based on the active element. +- filepicker.newFile - Prompts the user to input a file name manually, relative to the current working directory, and with FAT-incompatible characters excluded. Quits and returns that. +- filepicker.nothing - Do nothing and keep on running. Literally. This is used as a plug to enable an action for all (or a certain type) but files of a certain type (or more precise than the initial type). \ No newline at end of file diff --git a/doc/ldoc.ltp b/doc/ldoc.ltp new file mode 100644 index 0000000..ca2ab5d --- /dev/null +++ b/doc/ldoc.ltp @@ -0,0 +1,118 @@ +# -- LDoc template by Reuh. +# -- Generates sublime-completions files which can be used in Sublime Text 3 for autocompletion. +# -- Based on the HTML template, so generated files will contain lots of comments with additionnal data not handled by ST. +# -- I tried to make the generated files human-readable, so they may be used instead of the HTML documentation. +# -- Typical usage: ldoc . --template ./ --ext sublime-completions --dir ./sublimetext/ +# +# local scope = "source.lua" +# local function e(str) return (str or ""):gsub("\"", "\\\"") end -- escape json string ("str") +# local function indent(indentation, str) -- indent str (except first line) with indentation +# return (str or ""):gsub("(.-)\n", indentation.."%1\n"):gsub("\n([^\n]*)$", "\n"..indentation.."%1"):gsub("^"..indentation, "") +# end +# local function displayName(item) return item.type == "function" and item.name..item.args or item.name end -- nice name +# local function autocompleteName(item) -- ST-autocomplete name +# if item.type == "function" then +# local i = 1 +# local args = "(" +# for arg in (item.args:match("^%((.*)%)$")..","):gmatch("%s*([^,]+)%,") do +# args = args.."${"..i..":"..arg.."}, " +# i = i +1 +# end +# return item.name..args:gsub("%, $", "")..")" +# else return item.name end +# end +/* +Title: $(ldoc.title) +Project: $(ldoc.project) +Description: $(ldoc.description) +# if ldoc.single then +(Single module-project) +# end +# if not module then + +Project contents: +# for kind, mods in ldoc.kinds() do + $(kind) +# for m in mods() do + $(m.name): $(m.summary) +# end +# end +*/ +# else -- if not module +*/ + +/* +Module: $(module.name) +Summary: $(module.summary) +Description: $(module.description) + +Module contents: +# for kind, items in module.kinds() do + $(kind) +# for item in items() do + $(item.type) $(displayName(item)) +# end +# end +*/ + +/* Completions */ +{ + "scope": "$(e(scope))", + + "completions": [ +# for kind, items in module.kinds() do + /* $(kind) */ +# for item in items() do + /* + $(item.type) $(displayName(item)) + Summary: $(item.summary) + Description: $(indent("\t\t\t", item.description)) +# if item.type == "function" then + Parameters: +# for p in item.params:iter() do +# local default = item:default_of_param(p) +# if default == true then default = "(optional)" +# elseif default then default = "(defaults to "..default..")" end + ($(item:type_of_param(p))) $(item:display_name_of(p)):$(item.params.map[p]) $(default) +# end +# local retgroups = item.retgroups or {} + Returns: +# for i, group in ldoc.ipairs(retgroups) do +# for ret in group:iter() do + ($(ret.type)) $(indent("\t\t\t", ret.text)) +# end +# if i < #retgroups then + ---or--- +# end +# end +# end +# if item.usage then + Usage: +# for i, usage in ldoc.ipairs(item.usage) do + $(sep)$(indent("\t\t\t", usage:gsub("^\n", ""))) +# if i < #item.usage then + -------- +# end +# end +# end +# if item.see then + See also: +# for see in item.see:iter() do + $(see.mod.name): $(see.name) +# end +# end + */ +# for pos in (module.name.."."):gmatch("()[^.]+%.") do +# local prefix = e(module.name:sub(pos) .. (item.name:match("^[%.%:]") and "" or ".")) + { + "trigger": "$(prefix)$(e(item.name))\t$(e(item.summary))", + "contents": "$(prefix)$(e(autocompleteName(item)))" + }, +# end +# end +# end + ] +} +# end -- if not module + +/* Generated by LDoc; sublime-completions template by Reuh. Last updated $(ldoc.updatetime).*/ diff --git a/icon.png b/icon.png index f035c56..5c7a62b 100644 Binary files a/icon.png and b/icon.png differ diff --git a/libs/3ds_portlibs/.gitignore b/libs/3ds_portlibs/.gitignore index 115f9d0..8e0d03f 100644 --- a/libs/3ds_portlibs/.gitignore +++ b/libs/3ds_portlibs/.gitignore @@ -4,4 +4,6 @@ libjpeg-* libpng-* sqlite-* zlib-* +libogg-* +libvorbis-* build/ \ No newline at end of file diff --git a/libs/3ds_portlibs/Makefile b/libs/3ds_portlibs/Makefile index 355b8ad..c47b8c1 100644 --- a/libs/3ds_portlibs/Makefile +++ b/libs/3ds_portlibs/Makefile @@ -28,6 +28,16 @@ ZLIB_VERSION := $(ZLIB)-1.2.8 ZLIB_SRC := $(ZLIB_VERSION).tar.gz ZLIB_DOWNLOAD := "http://prdownloads.sourceforge.net/libpng/zlib-1.2.8.tar.gz" +LIBOGG := libogg +LIBOGG_VERSION := $(LIBOGG)-1.3.2 +LIBOGG_SRC := $(LIBOGG_VERSION).tar.gz +LIBOGG_DOWNLOAD := "http://downloads.xiph.org/releases/ogg/libogg-1.3.2.tar.gz" + +LIBVORBIS := libvorbis +LIBVORBIS_VERSION := $(LIBVORBIS)-1.3.5 +LIBVORBIS_SRC := $(LIBVORBIS_VERSION).tar.gz +LIBVORBIS_DOWNLOAD := "http://downloads.xiph.org/releases/vorbis/libvorbis-1.3.5.tar.gz" + export PORTLIBS := $(CURDIR)/build export PATH := $(DEVKITARM)/bin:$(PATH) export PKG_CONFIG_PATH := $(PORTLIBS)/lib/pkgconfig @@ -66,8 +76,8 @@ $(FREETYPE): $(FREETYPE_SRC) ./configure --prefix=$(PORTLIBS) --host=arm-none-eabi --disable-shared --enable-static --without-harfbuzz @$(MAKE) -C $(FREETYPE_VERSION) @make create_build_dir - @cp -srf $(CURDIR)/freetype-2.6/include/. $(CURDIR)/build/include - @cp -sf $(CURDIR)/freetype-2.6/objs/.libs/libfreetype.a $(CURDIR)/build/lib/libfreetype.a + @cp -srf $(CURDIR)/$(FREETYPE_VERSION)/include/. $(CURDIR)/build/include + @cp -sf $(CURDIR)/$(FREETYPE_VERSION)/objs/.libs/libfreetype.a $(CURDIR)/build/lib/libfreetype.a $(LIBEXIF): $(LIBEXIF_SRC) @[ -d $(LIBEXIF_VERSION) ] || tar -xf $< @@ -81,8 +91,8 @@ $(LIBJPEGTURBO): $(LIBJPEGTURBO_SRC) ./configure --prefix=$(PORTLIBS) --host=arm-none-eabi --disable-shared --enable-static @$(MAKE) CFLAGS+="\"-Drandom()=rand()\"" -C $(LIBJPEGTURBO_VERSION) @make create_build_dir - @cp -sf $(CURDIR)/libjpeg-turbo-*/*.h $(CURDIR)/build/include - @cp -sf $(CURDIR)/libjpeg-turbo-*/.libs/libjpeg.a $(CURDIR)/build/lib/libjpeg.a + @cp -sf $(CURDIR)/$(LIBJPEGTURBO_VERSION)/*.h $(CURDIR)/build/include + @cp -sf $(CURDIR)/$(LIBJPEGTURBO_VERSION)/.libs/libjpeg.a $(CURDIR)/build/lib/libjpeg.a $(LIBPNG): $(LIBPNG_SRC) @[ -d $(LIBPNG_VERSION) ] || tar -xf $< @@ -90,8 +100,8 @@ $(LIBPNG): $(LIBPNG_SRC) ./configure --prefix=$(PORTLIBS) --host=arm-none-eabi --disable-shared --enable-static @$(MAKE) -C $(LIBPNG_VERSION) @make create_build_dir - @cp -sf $(CURDIR)/libpng-*/*.h $(CURDIR)/build/include - @cp -sf $(CURDIR)/libpng-*/.libs/*.a $(CURDIR)/build/lib/libpng.a + @cp -sf $(CURDIR)/$(LIBPNG_VERSION)/*.h $(CURDIR)/build/include + @cp -sf $(CURDIR)/$(LIBPNG_VERSION)/.libs/*.a $(CURDIR)/build/lib/libpng.a # sqlite won't work with -ffast-math $(SQLITE): $(SQLITE_SRC) @@ -107,8 +117,26 @@ $(ZLIB): $(ZLIB_SRC) CHOST=arm-none-eabi ./configure --static --prefix=$(PORTLIBS) @$(MAKE) -C $(ZLIB_VERSION) @make create_build_dir - @cp -sf $(CURDIR)/zlib-*/*.h $(CURDIR)/build/include - @cp -sf $(CURDIR)/zlib-*/libz.a $(CURDIR)/build/lib/libz.a + @cp -sf $(CURDIR)/$(ZLIB_VERSION)/*.h $(CURDIR)/build/include + @cp -sf $(CURDIR)/$(ZLIB_VERSION)/libz.a $(CURDIR)/build/lib/libz.a + +$(LIBOGG): $(LIBOGG_SRC) + @[ -d $(LIBOGG_VERSION) ] || tar -xf $< + @cd $(LIBOGG_VERSION) && \ + ./configure --prefix=$(PORTLIBS) --host=arm-none-eabi --disable-shared --enable-static + @$(MAKE) -C $(LIBOGG_VERSION) + @make create_build_dir + @cp -srf $(CURDIR)/$(LIBOGG_VERSION)/include/. $(CURDIR)/build/include + @cp -sf $(CURDIR)/$(LIBOGG_VERSION)/src/.libs/*.a $(CURDIR)/build/lib + +$(LIBVORBIS): $(LIBVORBIS_SRC) + @[ -d $(LIBVORBIS_VERSION) ] || tar -xf $< + @cd $(LIBVORBIS_VERSION) && \ + ./configure --prefix=$(PORTLIBS) --host=arm-none-eabi --disable-shared --enable-static + @$(MAKE) -C $(LIBVORBIS_VERSION) + @make create_build_dir + @cp -srf $(CURDIR)/$(LIBVORBIS_VERSION)/include/. $(CURDIR)/build/include + @cp -sf $(CURDIR)/$(LIBVORBIS_VERSION)/lib/.libs/*.a $(CURDIR)/build/lib # Downloads $(ZLIB_SRC): @@ -129,6 +157,12 @@ $(LIBPNG_SRC): $(SQLITE_SRC): wget -O $@ $(SQLITE_DOWNLOAD) +$(LIBOGG_SRC): + wget -O $@ $(LIBOGG_DOWNLOAD) + +$(LIBVORBIS_SRC): + wget -O $@ $(LIBVORBIS_DOWNLOAD) + install-zlib: @$(MAKE) -C $(ZLIB_VERSION) install @@ -138,6 +172,8 @@ install: @[ ! -d $(LIBJPEGTURBO_VERSION) ] || $(MAKE) -C $(LIBJPEGTURBO_VERSION) install @[ ! -d $(LIBPNG_VERSION) ] || $(MAKE) -C $(LIBPNG_VERSION) install @[ ! -d $(SQLITE_VERSION) ] || $(MAKE) -C $(SQLITE_VERSION) install-libLTLIBRARIES install-data + @[ ! -d $(LIBOGG_VERSION) ] || $(MAKE) -C $(LIBOGG_VERSION) install + @[ ! -d $(LIBVORBIS_VERSION) ] || $(MAKE) -C $(LIBVORBIS_VERSION) install clean: @$(RM) -r $(FREETYPE_VERSION) @@ -146,5 +182,7 @@ clean: @$(RM) -r $(LIBPNG_VERSION) @$(RM) -r $(SQLITE_VERSION) @$(RM) -r $(ZLIB_VERSION) + @$(RM) -r $(LIBOGG_VERSION) + @$(RM) -r $(LIBVORBIS_VERSION) @rm -rf $(CURDIR)/build @rm -f $(CURDIR)/*.tar.* diff --git a/libs/lua-5.3.1/src/ltablib.c b/libs/lua-5.3.1/src/ltablib.c deleted file mode 100644 index a05c885..0000000 --- a/libs/lua-5.3.1/src/ltablib.c +++ /dev/null @@ -1,359 +0,0 @@ -/* -** $Id: ltablib.c,v 1.80 2015/01/13 16:27:29 roberto Exp $ -** Library for Table Manipulation -** See Copyright Notice in lua.h -*/ - -#define ltablib_c -#define LUA_LIB - -#include "lprefix.h" - - -#include -#include - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - - -/* -** Structure with table-access functions -*/ -typedef struct { - int (*geti) (lua_State *L, int idx, lua_Integer n); - void (*seti) (lua_State *L, int idx, lua_Integer n); -} TabA; - - -/* -** Check that 'arg' has a table and set access functions in 'ta' to raw -** or non-raw according to the presence of corresponding metamethods. -*/ -static void checktab (lua_State *L, int arg, TabA *ta) { - ta->geti = NULL; ta->seti = NULL; - if (lua_getmetatable(L, arg)) { - lua_pushliteral(L, "__index"); /* 'index' metamethod */ - if (lua_rawget(L, -2) != LUA_TNIL) - ta->geti = lua_geti; - lua_pushliteral(L, "__newindex"); /* 'newindex' metamethod */ - if (lua_rawget(L, -3) != LUA_TNIL) - ta->seti = lua_seti; - lua_pop(L, 3); /* pop metatable plus both metamethods */ - } - if (ta->geti == NULL || ta->seti == NULL) { - luaL_checktype(L, arg, LUA_TTABLE); /* must be table for raw methods */ - if (ta->geti == NULL) ta->geti = lua_rawgeti; - if (ta->seti == NULL) ta->seti = lua_rawseti; - } -} - - -#define aux_getn(L,n,ta) (checktab(L, n, ta), luaL_len(L, n)) - - -#if defined(LUA_COMPAT_MAXN) -static int maxn (lua_State *L) { - lua_Number max = 0; - luaL_checktype(L, 1, LUA_TTABLE); - lua_pushnil(L); /* first key */ - while (lua_next(L, 1)) { - lua_pop(L, 1); /* remove value */ - if (lua_type(L, -1) == LUA_TNUMBER) { - lua_Number v = lua_tonumber(L, -1); - if (v > max) max = v; - } - } - lua_pushnumber(L, max); - return 1; -} -#endif - - -static int tinsert (lua_State *L) { - TabA ta; - lua_Integer e = aux_getn(L, 1, &ta) + 1; /* first empty element */ - lua_Integer pos; /* where to insert new element */ - switch (lua_gettop(L)) { - case 2: { /* called with only 2 arguments */ - pos = e; /* insert new element at the end */ - break; - } - case 3: { - lua_Integer i; - pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */ - luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds"); - for (i = e; i > pos; i--) { /* move up elements */ - (*ta.geti)(L, 1, i - 1); - (*ta.seti)(L, 1, i); /* t[i] = t[i - 1] */ - } - break; - } - default: { - return luaL_error(L, "wrong number of arguments to 'insert'"); - } - } - (*ta.seti)(L, 1, pos); /* t[pos] = v */ - return 0; -} - - -static int tremove (lua_State *L) { - TabA ta; - lua_Integer size = aux_getn(L, 1, &ta); - lua_Integer pos = luaL_optinteger(L, 2, size); - if (pos != size) /* validate 'pos' if given */ - luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds"); - (*ta.geti)(L, 1, pos); /* result = t[pos] */ - for ( ; pos < size; pos++) { - (*ta.geti)(L, 1, pos + 1); - (*ta.seti)(L, 1, pos); /* t[pos] = t[pos + 1] */ - } - lua_pushnil(L); - (*ta.seti)(L, 1, pos); /* t[pos] = nil */ - return 1; -} - - -static int tmove (lua_State *L) { - TabA ta; - lua_Integer f = luaL_checkinteger(L, 2); - lua_Integer e = luaL_checkinteger(L, 3); - lua_Integer t = luaL_checkinteger(L, 4); - int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */ - if (e >= f) { /* otherwise, nothing to move */ - lua_Integer n, i; - ta.geti = (luaL_getmetafield(L, 1, "__index") == LUA_TNIL) - ? (luaL_checktype(L, 1, LUA_TTABLE), lua_rawgeti) - : lua_geti; - ta.seti = (luaL_getmetafield(L, tt, "__newindex") == LUA_TNIL) - ? (luaL_checktype(L, tt, LUA_TTABLE), lua_rawseti) - : lua_seti; - luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3, - "too many elements to move"); - n = e - f + 1; /* number of elements to move */ - luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4, - "destination wrap around"); - if (t > f) { - for (i = n - 1; i >= 0; i--) { - (*ta.geti)(L, 1, f + i); - (*ta.seti)(L, tt, t + i); - } - } - else { - for (i = 0; i < n; i++) { - (*ta.geti)(L, 1, f + i); - (*ta.seti)(L, tt, t + i); - } - } - } - lua_pushvalue(L, tt); /* return "to table" */ - return 1; -} - - -static void addfield (lua_State *L, luaL_Buffer *b, TabA *ta, lua_Integer i) { - (*ta->geti)(L, 1, i); - if (!lua_isstring(L, -1)) - luaL_error(L, "invalid value (%s) at index %d in table for 'concat'", - luaL_typename(L, -1), i); - luaL_addvalue(b); -} - - -static int tconcat (lua_State *L) { - TabA ta; - luaL_Buffer b; - size_t lsep; - lua_Integer i, last; - const char *sep = luaL_optlstring(L, 2, "", &lsep); - checktab(L, 1, &ta); - i = luaL_optinteger(L, 3, 1); - last = luaL_opt(L, luaL_checkinteger, 4, luaL_len(L, 1)); - luaL_buffinit(L, &b); - for (; i < last; i++) { - addfield(L, &b, &ta, i); - luaL_addlstring(&b, sep, lsep); - } - if (i == last) /* add last value (if interval was not empty) */ - addfield(L, &b, &ta, i); - luaL_pushresult(&b); - return 1; -} - - -/* -** {====================================================== -** Pack/unpack -** ======================================================= -*/ - -static int pack (lua_State *L) { - int i; - int n = lua_gettop(L); /* number of elements to pack */ - lua_createtable(L, n, 1); /* create result table */ - lua_insert(L, 1); /* put it at index 1 */ - for (i = n; i >= 1; i--) /* assign elements */ - lua_rawseti(L, 1, i); - lua_pushinteger(L, n); - lua_setfield(L, 1, "n"); /* t.n = number of elements */ - return 1; /* return table */ -} - - -static int unpack (lua_State *L) { - TabA ta; - lua_Integer i, e; - lua_Unsigned n; - checktab(L, 1, &ta); - i = luaL_optinteger(L, 2, 1); - e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1)); - if (i > e) return 0; /* empty range */ - n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */ - if (n >= (unsigned int)INT_MAX || !lua_checkstack(L, (int)(++n))) - return luaL_error(L, "too many results to unpack"); - do { /* must have at least one element */ - (*ta.geti)(L, 1, i); /* push arg[i..e] */ - } while (i++ < e); - - return (int)n; -} - -/* }====================================================== */ - - - -/* -** {====================================================== -** Quicksort -** (based on 'Algorithms in MODULA-3', Robert Sedgewick; -** Addison-Wesley, 1993.) -** ======================================================= -*/ - - -static void set2 (lua_State *L, TabA *ta, int i, int j) { - (*ta->seti)(L, 1, i); - (*ta->seti)(L, 1, j); -} - -static int sort_comp (lua_State *L, int a, int b) { - if (!lua_isnil(L, 2)) { /* function? */ - int res; - lua_pushvalue(L, 2); - lua_pushvalue(L, a-1); /* -1 to compensate function */ - lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */ - lua_call(L, 2, 1); - res = lua_toboolean(L, -1); - lua_pop(L, 1); - return res; - } - else /* a < b? */ - return lua_compare(L, a, b, LUA_OPLT); -} - -static void auxsort (lua_State *L, TabA *ta, int l, int u) { - while (l < u) { /* for tail recursion */ - int i, j; - /* sort elements a[l], a[(l+u)/2] and a[u] */ - (*ta->geti)(L, 1, l); - (*ta->geti)(L, 1, u); - if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */ - set2(L, ta, l, u); /* swap a[l] - a[u] */ - else - lua_pop(L, 2); - if (u-l == 1) break; /* only 2 elements */ - i = (l+u)/2; - (*ta->geti)(L, 1, i); - (*ta->geti)(L, 1, l); - if (sort_comp(L, -2, -1)) /* a[i]geti)(L, 1, u); - if (sort_comp(L, -1, -2)) /* a[u]geti)(L, 1, i); /* Pivot */ - lua_pushvalue(L, -1); - (*ta->geti)(L, 1, u-1); - set2(L, ta, i, u-1); - /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */ - i = l; j = u-1; - for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */ - /* repeat ++i until a[i] >= P */ - while ((*ta->geti)(L, 1, ++i), sort_comp(L, -1, -2)) { - if (i>=u) luaL_error(L, "invalid order function for sorting"); - lua_pop(L, 1); /* remove a[i] */ - } - /* repeat --j until a[j] <= P */ - while ((*ta->geti)(L, 1, --j), sort_comp(L, -3, -1)) { - if (j<=l) luaL_error(L, "invalid order function for sorting"); - lua_pop(L, 1); /* remove a[j] */ - } - if (jgeti)(L, 1, u-1); - (*ta->geti)(L, 1, i); - set2(L, ta, u-1, i); /* swap pivot (a[u-1]) with a[i] */ - /* a[l..i-1] <= a[i] == P <= a[i+1..u] */ - /* adjust so that smaller half is in [j..i] and larger one in [l..u] */ - if (i-l < u-i) { - j=l; i=i-1; l=i+2; - } - else { - j=i+1; i=u; u=j-2; - } - auxsort(L, ta, j, i); /* call recursively the smaller one */ - } /* repeat the routine for the larger one */ -} - -static int sort (lua_State *L) { - TabA ta; - int n = (int)aux_getn(L, 1, &ta); - luaL_checkstack(L, 50, ""); /* assume array is smaller than 2^50 */ - if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */ - luaL_checktype(L, 2, LUA_TFUNCTION); - lua_settop(L, 2); /* make sure there are two arguments */ - auxsort(L, &ta, 1, n); - return 0; -} - -/* }====================================================== */ - - -static const luaL_Reg tab_funcs[] = { - {"concat", tconcat}, -#if defined(LUA_COMPAT_MAXN) - {"maxn", maxn}, -#endif - {"insert", tinsert}, - {"pack", pack}, - {"unpack", unpack}, - {"remove", tremove}, - {"move", tmove}, - {"sort", sort}, - {NULL, NULL} -}; - - -LUAMOD_API int luaopen_table (lua_State *L) { - luaL_newlib(L, tab_funcs); -#if defined(LUA_COMPAT_UNPACK) - /* _G.unpack = table.unpack */ - lua_getfield(L, -1, "unpack"); - lua_setglobal(L, "unpack"); -#endif - return 1; -} - diff --git a/libs/lua-5.3.1/src/lvm.h b/libs/lua-5.3.1/src/lvm.h deleted file mode 100644 index 0613826..0000000 --- a/libs/lua-5.3.1/src/lvm.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -** $Id: lvm.h,v 2.35 2015/02/20 14:27:53 roberto Exp $ -** Lua virtual machine -** See Copyright Notice in lua.h -*/ - -#ifndef lvm_h -#define lvm_h - - -#include "ldo.h" -#include "lobject.h" -#include "ltm.h" - - -#if !defined(LUA_NOCVTN2S) -#define cvt2str(o) ttisnumber(o) -#else -#define cvt2str(o) 0 /* no conversion from numbers to strings */ -#endif - - -#if !defined(LUA_NOCVTS2N) -#define cvt2num(o) ttisstring(o) -#else -#define cvt2num(o) 0 /* no conversion from strings to numbers */ -#endif - - -/* -** You can define LUA_FLOORN2I if you want to convert floats to integers -** by flooring them (instead of raising an error if they are not -** integral values) -*/ -#if !defined(LUA_FLOORN2I) -#define LUA_FLOORN2I 0 -#endif - - -#define tonumber(o,n) \ - (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n)) - -#define tointeger(o,i) \ - (ttisinteger(o) ? (*(i) = ivalue(o), 1) : luaV_tointeger(o,i,LUA_FLOORN2I)) - -#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2)) - -#define luaV_rawequalobj(t1,t2) luaV_equalobj(NULL,t1,t2) - - -LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2); -LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); -LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r); -LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n); -LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, int mode); -LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key, - StkId val); -LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key, - StkId val); -LUAI_FUNC void luaV_finishOp (lua_State *L); -LUAI_FUNC void luaV_execute (lua_State *L); -LUAI_FUNC void luaV_concat (lua_State *L, int total); -LUAI_FUNC lua_Integer luaV_div (lua_State *L, lua_Integer x, lua_Integer y); -LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y); -LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y); -LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb); - -#endif diff --git a/libs/lua-5.3.1/Makefile b/libs/lua-5.3.2/Makefile similarity index 99% rename from libs/lua-5.3.1/Makefile rename to libs/lua-5.3.2/Makefile index 5ee5601..e87e958 100644 --- a/libs/lua-5.3.1/Makefile +++ b/libs/lua-5.3.2/Makefile @@ -46,7 +46,7 @@ TO_MAN= lua.1 luac.1 # Lua version and release. V= 5.3 -R= $V.1 +R= $V.2 # Targets start here. all: $(PLAT) diff --git a/libs/lua-5.3.1/README b/libs/lua-5.3.2/README similarity index 70% rename from libs/lua-5.3.1/README rename to libs/lua-5.3.2/README index d6ae660..eb6247a 100644 --- a/libs/lua-5.3.1/README +++ b/libs/lua-5.3.2/README @@ -1,5 +1,5 @@ -This is Lua 5.3.1, released on 10 Jun 2015. +This is Lua 5.3.2, released on 25 Nov 2015. For installation instructions, license details, and further information about Lua, see doc/readme.html. diff --git a/libs/lua-5.3.1/doc/contents.html b/libs/lua-5.3.2/doc/contents.html similarity index 100% rename from libs/lua-5.3.1/doc/contents.html rename to libs/lua-5.3.2/doc/contents.html diff --git a/libs/lua-5.3.1/doc/index.css b/libs/lua-5.3.2/doc/index.css similarity index 100% rename from libs/lua-5.3.1/doc/index.css rename to libs/lua-5.3.2/doc/index.css diff --git a/libs/lua-5.3.1/doc/logo.gif b/libs/lua-5.3.2/doc/logo.gif similarity index 100% rename from libs/lua-5.3.1/doc/logo.gif rename to libs/lua-5.3.2/doc/logo.gif diff --git a/libs/lua-5.3.1/doc/lua.1 b/libs/lua-5.3.2/doc/lua.1 similarity index 100% rename from libs/lua-5.3.1/doc/lua.1 rename to libs/lua-5.3.2/doc/lua.1 diff --git a/libs/lua-5.3.1/doc/lua.css b/libs/lua-5.3.2/doc/lua.css similarity index 85% rename from libs/lua-5.3.1/doc/lua.css rename to libs/lua-5.3.2/doc/lua.css index b614f3c..eb20fec 100644 --- a/libs/lua-5.3.1/doc/lua.css +++ b/libs/lua-5.3.2/doc/lua.css @@ -131,3 +131,29 @@ table.columns td { p.logos a:link:hover, p.logos a:visited:hover { background-color: inherit ; } + +table.book { + border: none ; + border-spacing: 0 ; + border-collapse: collapse ; +} + +table.book td { + padding: 0 ; + vertical-align: top ; +} + +table.book td.cover { + padding-right: 1em ; +} + +table.book img { + border: solid #000080 1px ; +} + +table.book span { + font-size: small ; + text-align: left ; + display: block ; + margin-top: 0.25em ; +} diff --git a/libs/lua-5.3.1/doc/luac.1 b/libs/lua-5.3.2/doc/luac.1 similarity index 100% rename from libs/lua-5.3.1/doc/luac.1 rename to libs/lua-5.3.2/doc/luac.1 diff --git a/libs/lua-5.3.1/doc/manual.css b/libs/lua-5.3.2/doc/manual.css similarity index 100% rename from libs/lua-5.3.1/doc/manual.css rename to libs/lua-5.3.2/doc/manual.css diff --git a/libs/lua-5.3.1/doc/manual.html b/libs/lua-5.3.2/doc/manual.html similarity index 98% rename from libs/lua-5.3.1/doc/manual.html rename to libs/lua-5.3.2/doc/manual.html index f2eb313..60c4c98 100644 --- a/libs/lua-5.3.1/doc/manual.html +++ b/libs/lua-5.3.2/doc/manual.html @@ -35,7 +35,7 @@ Freely available under the terms of the

- + @@ -398,7 +398,7 @@ You can replace the metatable of tables using the setmetatable function. You cannot change the metatable of other types from Lua code (except by using the debug library (§6.10)); -you must use the C API for that. +you should use the C API for that.

@@ -589,7 +589,7 @@ The result of the call is always converted to a boolean. the <= (less equal) operation. Unlike other operations, -The less-equal operation can use two different events. +the less-equal operation can use two different events. First, Lua looks for the "__le" metamethod in both operands, like in the "lt" operation. If it cannot find such a metamethod, @@ -1051,7 +1051,8 @@ except as delimiters between names and keywords. (also called identifiers) in Lua can be any string of letters, digits, and underscores, -not beginning with a digit. +not beginning with a digit and +not being a reserved word. Identifiers are used to name variables, table fields, and labels. @@ -2706,7 +2707,9 @@ The first upvalue associated with a function is at index lua_upvalueindex(1), and so on. Any access to lua_upvalueindex(n), where n is greater than the number of upvalues of the -current function (but not greater than 256), +current function +(but not greater than 256, +which is one plus the maximum number of upvalues in a closure), produces an acceptable but invalid index. @@ -2971,6 +2974,7 @@ by looking only at its arguments The third field, x, tells whether the function may raise errors: '-' means the function never raises any error; +'m' means the function may raise memory errors; 'e' means the function may raise errors; 'v' means the function may raise an error on purpose. @@ -3143,7 +3147,8 @@ The function results are pushed onto the stack when the function returns. The number of results is adjusted to nresults, unless nresults is LUA_MULTRET. In this case, all results from the function are pushed. -Lua takes care that the returned values fit into the stack space. +Lua takes care that the returned values fit into the stack space, +but it does not ensure any extra space in the stack. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack. @@ -3253,14 +3258,15 @@ of numeric arguments and returns their average and their sum:

int lua_checkstack (lua_State *L, int n);

-Ensures that the stack has space for at least n extra slots. +Ensures that the stack has space for at least n extra slots +(that is, that you can safely push up to n values into it). It returns false if it cannot fulfill the request, either because it would cause the stack to be larger than a fixed maximum size (typically at least several thousand elements) or because it cannot allocate memory for the extra space. This function never shrinks the stack; -if the stack is already larger than the new size, +if the stack already has space for the extra slots, it is left unchanged. @@ -3345,7 +3351,7 @@ Values at other positions are not affected.


lua_createtable

-[-0, +1, e] +[-0, +1, m]

void lua_createtable (lua_State *L, int narr, int nrec);

@@ -3355,7 +3361,7 @@ will have as a sequence; parameter nrec is a hint for how many other elements the table will have. Lua may use these hints to preallocate memory for the new table. -This pre-allocation is useful for performance when you know in advance +This preallocation is useful for performance when you know in advance how many elements the table will have. Otherwise you can use the function lua_newtable. @@ -3364,7 +3370,7 @@ Otherwise you can use the function lua_newtable

lua_dump

-[-0, +0, e] +[-0, +0, –]

int lua_dump (lua_State *L,
                         lua_Writer writer,
                         void *data,
@@ -3978,7 +3984,7 @@ passes to the allocator in every call.
 
 
 

lua_newtable

-[-0, +1, e] +[-0, +1, m]

void lua_newtable (lua_State *L);

@@ -3990,7 +3996,7 @@ It is equivalent to lua_createtable(L, 0, 0).


lua_newthread

-[-0, +1, e] +[-0, +1, m]

lua_State *lua_newthread (lua_State *L);

@@ -4011,7 +4017,7 @@ like any Lua object.


lua_newuserdata

-[-0, +1, e] +[-0, +1, m]

void *lua_newuserdata (lua_State *L, size_t size);

@@ -4221,7 +4227,7 @@ Pushes a boolean value with value b onto the stack.


lua_pushcclosure

-[-n, +1, e] +[-n, +1, m]

void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);

@@ -4278,7 +4284,7 @@ and return its results (see lua_CFunction<


lua_pushfstring

-[-0, +1, e] +[-0, +1, m]

const char *lua_pushfstring (lua_State *L, const char *fmt, ...);

@@ -4358,7 +4364,7 @@ light userdata with the same C address.


lua_pushliteral

-[-0, +1, e] +[-0, +1, m]

const char *lua_pushliteral (lua_State *L, const char *s);

@@ -4370,7 +4376,7 @@ but should be used only when s is a literal string.


lua_pushlstring

-[-0, +1, e] +[-0, +1, m]

const char *lua_pushlstring (lua_State *L, const char *s, size_t len);

@@ -4413,7 +4419,7 @@ Pushes a float with value n onto the stack.


lua_pushstring

-[-0, +1, e] +[-0, +1, m]

const char *lua_pushstring (lua_State *L, const char *s);

@@ -4460,7 +4466,7 @@ onto the stack.


lua_pushvfstring

-[-0, +1, e] +[-0, +1, m]

const char *lua_pushvfstring (lua_State *L,
                               const char *fmt,
                               va_list argp);
@@ -4555,7 +4561,7 @@ for other values, it is 0.

lua_rawset

-[-2, +0, e] +[-2, +0, m]

void lua_rawset (lua_State *L, int index);

@@ -4567,7 +4573,7 @@ Similar to lua_settable, but does a raw


lua_rawseti

-[-1, +0, e] +[-1, +0, m]

void lua_rawseti (lua_State *L, int index, lua_Integer i);

@@ -4586,7 +4592,7 @@ that is, it does not invoke metamethods.


lua_rawsetp

-[-1, +0, e] +[-1, +0, m]

void lua_rawsetp (lua_State *L, int index, const void *p);

@@ -4989,13 +4995,13 @@ indicates whether the operation succeeded.


lua_tolstring

-[-0, +0, e] +[-0, +0, m]

const char *lua_tolstring (lua_State *L, int index, size_t *len);

Converts the Lua value at the given index to a C string. If len is not NULL, -it also sets *len with the string length. +it sets *len with the string length. The Lua value must be a string or a number; otherwise, the function returns NULL. If the value is a number, @@ -5006,7 +5012,7 @@ when lua_tolstring is applied to keys during a table traversal.)

-lua_tolstring returns a fully aligned pointer +lua_tolstring returns a pointer to a string inside the Lua state. This string always has a zero ('\0') after its last character (as in C), @@ -5075,7 +5081,7 @@ Typically this function is used only for hashing and debug information.


lua_tostring

-[-0, +0, e] +[-0, +0, m]

const char *lua_tostring (lua_State *L, int index);

@@ -5884,7 +5890,7 @@ in alphabetical order.


luaL_addchar

-[-?, +?, e] +[-?, +?, m]

void luaL_addchar (luaL_Buffer *B, char c);

@@ -5896,7 +5902,7 @@ Adds the byte c to the buffer B


luaL_addlstring

-[-?, +?, e] +[-?, +?, m]

void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);

@@ -5910,7 +5916,7 @@ The string can contain embedded zeros.


luaL_addsize

-[-?, +?, e] +[-?, +?, –]

void luaL_addsize (luaL_Buffer *B, size_t n);

@@ -5923,7 +5929,7 @@ buffer area (see luaL_prepbuffer).


luaL_addstring

-[-?, +?, e] +[-?, +?, m]

void luaL_addstring (luaL_Buffer *B, const char *s);

@@ -5936,7 +5942,7 @@ to the buffer B


luaL_addvalue

-[-1, +?, e] +[-1, +?, m]

void luaL_addvalue (luaL_Buffer *B);

@@ -6074,7 +6080,7 @@ the buffer must be declared as a variable


luaL_buffinitsize

-[-?, +?, e] +[-?, +?, m]

char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);

@@ -6325,7 +6331,7 @@ as return luaL_error(args).


luaL_execresult

-[-0, +3, e] +[-0, +3, m]

int luaL_execresult (lua_State *L, int stat);

@@ -6338,7 +6344,7 @@ process-related functions in the standard library


luaL_fileresult

-[-0, +(1|3), e] +[-0, +(1|3), m]

int luaL_fileresult (lua_State *L, int stat, const char *fname);

@@ -6351,7 +6357,7 @@ file-related functions in the standard library


luaL_getmetafield

-[-0, +(0|1), e] +[-0, +(0|1), m]

int luaL_getmetafield (lua_State *L, int obj, const char *e);

@@ -6366,7 +6372,7 @@ pushes nothing and returns LUA_TNIL.


luaL_getmetatable

-[-0, +1, –] +[-0, +1, m]

int luaL_getmetatable (lua_State *L, const char *tname);

@@ -6396,7 +6402,7 @@ and false if it creates a new table.


luaL_gsub

-[-0, +1, e] +[-0, +1, m]

const char *luaL_gsub (lua_State *L,
                        const char *s,
                        const char *p,
@@ -6531,7 +6537,7 @@ it does not run it.
 
 
 

luaL_newlib

-[-0, +1, e] +[-0, +1, m]

void luaL_newlib (lua_State *L, const luaL_Reg l[]);

@@ -6553,7 +6559,7 @@ not a pointer to it.


luaL_newlibtable

-[-0, +1, e] +[-0, +1, m]

void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);

@@ -6574,7 +6580,7 @@ not a pointer to it.


luaL_newmetatable

-[-0, +1, e] +[-0, +1, m]

int luaL_newmetatable (lua_State *L, const char *tname);

@@ -6664,6 +6670,9 @@ Otherwise, raises an error.

If l is not NULL, fills the position *l with the result's length. +If the result is NULL +(only possible when returning d and d == NULL), +its length is considered zero. @@ -6702,7 +6711,7 @@ Otherwise, raises an error.


luaL_prepbuffer

-[-?, +?, e] +[-?, +?, m]

char *luaL_prepbuffer (luaL_Buffer *B);

@@ -6714,7 +6723,7 @@ with the predefined size LUAL_BUFFERSIZE

luaL_prepbuffsize

-[-?, +?, e] +[-?, +?, m]

char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);

@@ -6730,7 +6739,7 @@ it to the buffer.


luaL_pushresult

-[-?, +1, e] +[-?, +1, m]

void luaL_pushresult (luaL_Buffer *B);

@@ -6742,7 +6751,7 @@ the top of the stack.


luaL_pushresultsize

-[-?, +1, e] +[-?, +1, m]

void luaL_pushresultsize (luaL_Buffer *B, size_t sz);

@@ -6753,7 +6762,7 @@ Equivalent to the sequence luaL_addsize


luaL_ref

-[-1, +0, e] +[-1, +0, m]

int luaL_ref (lua_State *L, int t);

@@ -6824,7 +6833,7 @@ Leaves a copy of the module on the stack.


luaL_setfuncs

-[-nup, +0, e] +[-nup, +0, m]

void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);

@@ -6888,7 +6897,7 @@ this function receives the file handle as its sole argument and must return either true (in case of success) or nil plus an error message (in case of error). Once Lua calls this field, -the field value is changed to NULL +it changes the field value to NULL to signal that the handle is closed. @@ -6896,7 +6905,7 @@ to signal that the handle is closed.


luaL_testudata

-[-0, +0, e] +[-0, +0, m]

void *luaL_testudata (lua_State *L, int arg, const char *tname);

@@ -6932,7 +6941,7 @@ and uses the result of the call as its result.


luaL_traceback

-[-0, +1, e] +[-0, +1, m]

void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
                      int level);
@@ -6979,7 +6988,7 @@ If ref is LUA_NOREF or

luaL_where

-[-0, +1, e] +[-0, +1, m]

void luaL_where (lua_State *L, int lvl);

@@ -7476,7 +7485,8 @@ and select returns the total number of extra arguments it received.

Sets the metatable for the given table. -(You cannot change the metatable of other types from Lua, only from C.) +(To change the metatable of other types from Lua code, +you must use the debug library (§6.10).) If metatable is nil, removes the metatable of the given table. If the original metatable has a "__metatable" field, @@ -7557,8 +7567,11 @@ and "userdata".


_VERSION

+ + +

A global variable (not a function) that -holds a string containing the current interpreter version. +holds a string containing the running Lua version. The current value of this variable is "Lua 5.3". @@ -8194,9 +8207,11 @@ Options c, d, i, o, u, X, and x expect an integer. Option q expects a string. -Option s expects a string without embedded zeros; +Option s expects a string; if its argument is not a string, it is converted to one following the same rules of tostring. +If the option has any modifier (flags, width, length), +the string argument should not contain embedded zeros.

@@ -8392,6 +8407,11 @@ The default value for sep is the empty string Returns the empty string if n is not positive. +

+(Note that it is very easy to exhaust the memory of your machine +with a single call to this function.) + +

@@ -8963,14 +8983,23 @@ If comp is given, then it must be a function that receives two list elements and returns true when the first element must come before the second in the final order -(so that not comp(list[i+1],list[i]) will be true after the sort). +(so that, after the sort, +i < j implies not comp(list[j],list[i])). If comp is not given, then the standard Lua operator < is used instead. +

+Note that the comp function must define +a strict partial order over the elements in the list; +that is, it must be asymmetric and transitive. +Otherwise, no valid sort may be possible. + +

The sort algorithm is not stable; -that is, elements considered equal by the given order +that is, elements not comparable by the given order +(e.g., equal elements) may have their relative positions changed by the sort. @@ -9222,14 +9251,13 @@ in the range [0,1). When called with two integers m and n, math.random returns a pseudo-random integer with uniform distribution in the range [m, n]. -(The value m-n cannot be negative and must fit in a Lua integer.) +(The value n-m cannot be negative and must fit in a Lua integer.) The call math.random(n) is equivalent to math.random(1,n).

This function is an interface to the underling pseudo-random generator function provided by C. -No guarantees can be given for its statistical properties. @@ -9397,7 +9425,7 @@ instead of returning an error code.

-


io.lines ([filename ···])

+

io.lines ([filename, ···])

@@ -9771,7 +9799,7 @@ then the date is formatted in Coordinated Universal Time. After this optional character, if format is the string "*t", then date returns a table with the following fields: -year (four digits), month (1–12), day (1–31), +year, month (1–12), day (1–31), hour (0–23), min (0–59), sec (0–61), wday (weekday, Sunday is 1), yday (day of the year), @@ -9789,8 +9817,8 @@ formatted according to the same rules as the ISO C function strftime<

When called without arguments, date returns a reasonable date and time representation that depends on -the host system and on the current locale -(that is, os.date() is equivalent to os.date("%c")). +the host system and on the current locale. +(More specifically, os.date() is equivalent to os.date("%c").)

@@ -10797,10 +10825,10 @@ and LiteralString, see §3.1.)

diff --git a/libs/lua-5.3.1/doc/osi-certified-72x60.png b/libs/lua-5.3.2/doc/osi-certified-72x60.png similarity index 100% rename from libs/lua-5.3.1/doc/osi-certified-72x60.png rename to libs/lua-5.3.2/doc/osi-certified-72x60.png diff --git a/libs/lua-5.3.1/doc/readme.html b/libs/lua-5.3.2/doc/readme.html similarity index 100% rename from libs/lua-5.3.1/doc/readme.html rename to libs/lua-5.3.2/doc/readme.html diff --git a/libs/lua-5.3.1/src/Makefile b/libs/lua-5.3.2/src/Makefile similarity index 100% rename from libs/lua-5.3.1/src/Makefile rename to libs/lua-5.3.2/src/Makefile diff --git a/libs/lua-5.3.1/src/lapi.c b/libs/lua-5.3.2/src/lapi.c similarity index 91% rename from libs/lua-5.3.1/src/lapi.c rename to libs/lua-5.3.2/src/lapi.c index fea9eb2..9a6a3fb 100644 --- a/libs/lua-5.3.1/src/lapi.c +++ b/libs/lua-5.3.2/src/lapi.c @@ -1,5 +1,5 @@ /* -** $Id: lapi.c,v 2.249 2015/04/06 12:23:48 roberto Exp $ +** $Id: lapi.c,v 2.257 2015/11/02 18:48:07 roberto Exp $ ** Lua API ** See Copyright Notice in lua.h */ @@ -121,11 +121,11 @@ LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { lua_lock(to); api_checknelems(from, n); api_check(from, G(from) == G(to), "moving among independent states"); - api_check(from, to->ci->top - to->top >= n, "not enough elements to move"); + api_check(from, to->ci->top - to->top >= n, "stack overflow"); from->top -= n; for (i = 0; i < n; i++) { setobj2s(to, to->top, from->top + i); - api_incr_top(to); + to->top++; /* stack already checked by previous 'api_check' */ } lua_unlock(to); } @@ -471,11 +471,16 @@ LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { } +/* +** Pushes on the stack a string with given length. Avoid using 's' when +** 'len' == 0 (as 's' can be NULL in that case), due to later use of +** 'memcmp' and 'memcpy'. +*/ LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) { TString *ts; lua_lock(L); luaC_checkGC(L); - ts = luaS_newlstr(L, s, len); + ts = (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len); setsvalue2s(L, L->top, ts); api_incr_top(L); lua_unlock(L); @@ -579,19 +584,30 @@ LUA_API int lua_pushthread (lua_State *L) { */ -LUA_API int lua_getglobal (lua_State *L, const char *name) { - Table *reg = hvalue(&G(L)->l_registry); - const TValue *gt; /* global table */ - lua_lock(L); - gt = luaH_getint(reg, LUA_RIDX_GLOBALS); - setsvalue2s(L, L->top, luaS_new(L, name)); - api_incr_top(L); - luaV_gettable(L, gt, L->top - 1, L->top - 1); +static int auxgetstr (lua_State *L, const TValue *t, const char *k) { + const TValue *aux; + TString *str = luaS_new(L, k); + if (luaV_fastget(L, t, str, aux, luaH_getstr)) { + setobj2s(L, L->top, aux); + api_incr_top(L); + } + else { + setsvalue2s(L, L->top, str); + api_incr_top(L); + luaV_finishget(L, t, L->top - 1, L->top - 1, aux); + } lua_unlock(L); return ttnov(L->top - 1); } +LUA_API int lua_getglobal (lua_State *L, const char *name) { + Table *reg = hvalue(&G(L)->l_registry); + lua_lock(L); + return auxgetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name); +} + + LUA_API int lua_gettable (lua_State *L, int idx) { StkId t; lua_lock(L); @@ -603,24 +619,25 @@ LUA_API int lua_gettable (lua_State *L, int idx) { LUA_API int lua_getfield (lua_State *L, int idx, const char *k) { - StkId t; lua_lock(L); - t = index2addr(L, idx); - setsvalue2s(L, L->top, luaS_new(L, k)); - api_incr_top(L); - luaV_gettable(L, t, L->top - 1, L->top - 1); - lua_unlock(L); - return ttnov(L->top - 1); + return auxgetstr(L, index2addr(L, idx), k); } LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) { StkId t; + const TValue *aux; lua_lock(L); t = index2addr(L, idx); - setivalue(L->top, n); - api_incr_top(L); - luaV_gettable(L, t, L->top - 1, L->top - 1); + if (luaV_fastget(L, t, n, aux, luaH_getint)) { + setobj2s(L, L->top, aux); + api_incr_top(L); + } + else { + setivalue(L->top, n); + api_incr_top(L); + luaV_finishget(L, t, L->top - 1, L->top - 1, aux); + } lua_unlock(L); return ttnov(L->top - 1); } @@ -719,18 +736,29 @@ LUA_API int lua_getuservalue (lua_State *L, int idx) { ** set functions (stack -> Lua) */ +/* +** t[k] = value at the top of the stack (where 'k' is a string) +*/ +static void auxsetstr (lua_State *L, const TValue *t, const char *k) { + const TValue *aux; + TString *str = luaS_new(L, k); + api_checknelems(L, 1); + if (luaV_fastset(L, t, str, aux, luaH_getstr, L->top - 1)) + L->top--; /* pop value */ + else { + setsvalue2s(L, L->top, str); /* push 'str' (to make it a TValue) */ + api_incr_top(L); + luaV_finishset(L, t, L->top - 1, L->top - 2, aux); + L->top -= 2; /* pop value and key */ + } + lua_unlock(L); /* lock done by caller */ +} + LUA_API void lua_setglobal (lua_State *L, const char *name) { Table *reg = hvalue(&G(L)->l_registry); - const TValue *gt; /* global table */ - lua_lock(L); - api_checknelems(L, 1); - gt = luaH_getint(reg, LUA_RIDX_GLOBALS); - setsvalue2s(L, L->top, luaS_new(L, name)); - api_incr_top(L); - luaV_settable(L, gt, L->top - 1, L->top - 2); - L->top -= 2; /* pop value and key */ - lua_unlock(L); + lua_lock(L); /* unlock done in 'auxsetstr' */ + auxsetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name); } @@ -746,42 +774,40 @@ LUA_API void lua_settable (lua_State *L, int idx) { LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { - StkId t; - lua_lock(L); - api_checknelems(L, 1); - t = index2addr(L, idx); - setsvalue2s(L, L->top, luaS_new(L, k)); - api_incr_top(L); - luaV_settable(L, t, L->top - 1, L->top - 2); - L->top -= 2; /* pop value and key */ - lua_unlock(L); + lua_lock(L); /* unlock done in 'auxsetstr' */ + auxsetstr(L, index2addr(L, idx), k); } LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) { StkId t; + const TValue *aux; lua_lock(L); api_checknelems(L, 1); t = index2addr(L, idx); - setivalue(L->top, n); - api_incr_top(L); - luaV_settable(L, t, L->top - 1, L->top - 2); - L->top -= 2; /* pop value and key */ + if (luaV_fastset(L, t, n, aux, luaH_getint, L->top - 1)) + L->top--; /* pop value */ + else { + setivalue(L->top, n); + api_incr_top(L); + luaV_finishset(L, t, L->top - 1, L->top - 2, aux); + L->top -= 2; /* pop value and key */ + } lua_unlock(L); } LUA_API void lua_rawset (lua_State *L, int idx) { StkId o; - Table *t; + TValue *slot; lua_lock(L); api_checknelems(L, 2); o = index2addr(L, idx); api_check(L, ttistable(o), "table expected"); - t = hvalue(o); - setobj2t(L, luaH_set(L, t, L->top-2), L->top-1); - invalidateTMcache(t); - luaC_barrierback(L, t, L->top-1); + slot = luaH_set(L, hvalue(o), L->top - 2); + setobj2t(L, slot, L->top - 1); + invalidateTMcache(hvalue(o)); + luaC_barrierback(L, hvalue(o), L->top-1); L->top -= 2; lua_unlock(L); } @@ -789,14 +815,12 @@ LUA_API void lua_rawset (lua_State *L, int idx) { LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) { StkId o; - Table *t; lua_lock(L); api_checknelems(L, 1); o = index2addr(L, idx); api_check(L, ttistable(o), "table expected"); - t = hvalue(o); - luaH_setint(L, t, n, L->top - 1); - luaC_barrierback(L, t, L->top-1); + luaH_setint(L, hvalue(o), n, L->top - 1); + luaC_barrierback(L, hvalue(o), L->top-1); L->top--; lua_unlock(L); } @@ -804,16 +828,15 @@ LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) { LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) { StkId o; - Table *t; - TValue k; + TValue k, *slot; lua_lock(L); api_checknelems(L, 1); o = index2addr(L, idx); api_check(L, ttistable(o), "table expected"); - t = hvalue(o); setpvalue(&k, cast(void *, p)); - setobj2t(L, luaH_set(L, t, &k), L->top - 1); - luaC_barrierback(L, t, L->top - 1); + slot = luaH_set(L, hvalue(o), &k); + setobj2t(L, slot, L->top - 1); + luaC_barrierback(L, hvalue(o), L->top - 1); L->top--; lua_unlock(L); } @@ -895,10 +918,10 @@ LUA_API void lua_callk (lua_State *L, int nargs, int nresults, if (k != NULL && L->nny == 0) { /* need to prepare continuation? */ L->ci->u.c.k = k; /* save continuation */ L->ci->u.c.ctx = ctx; /* save context */ - luaD_call(L, func, nresults, 1); /* do the call */ + luaD_call(L, func, nresults); /* do the call */ } else /* no continuation or no yieldable */ - luaD_call(L, func, nresults, 0); /* just do the call */ + luaD_callnoyield(L, func, nresults); /* just do the call */ adjustresults(L, nresults); lua_unlock(L); } @@ -916,7 +939,7 @@ struct CallS { /* data to 'f_call' */ static void f_call (lua_State *L, void *ud) { struct CallS *c = cast(struct CallS *, ud); - luaD_call(L, c->func, c->nresults, 0); + luaD_callnoyield(L, c->func, c->nresults); } @@ -954,7 +977,7 @@ LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc, L->errfunc = func; setoah(ci->callstatus, L->allowhook); /* save value of 'allowhook' */ ci->callstatus |= CIST_YPCALL; /* function can do error recovery */ - luaD_call(L, c.func, nresults, 1); /* do the call */ + luaD_call(L, c.func, nresults); /* do the call */ ci->callstatus &= ~CIST_YPCALL; L->errfunc = ci->u.c.old_errfunc; status = LUA_OK; /* if it is here, there were no errors */ @@ -1043,7 +1066,7 @@ LUA_API int lua_gc (lua_State *L, int what, int data) { } case LUA_GCSTEP: { l_mem debt = 1; /* =1 to signal that it did an actual step */ - int oldrunning = g->gcrunning; + lu_byte oldrunning = g->gcrunning; g->gcrunning = 1; /* allow GC to run */ if (data == 0) { luaE_setdebt(g, -GCSTEPSIZE); /* to do a "small" step */ diff --git a/libs/lua-5.3.1/src/lapi.h b/libs/lua-5.3.2/src/lapi.h similarity index 100% rename from libs/lua-5.3.1/src/lapi.h rename to libs/lua-5.3.2/src/lapi.h diff --git a/libs/lua-5.3.1/src/lauxlib.c b/libs/lua-5.3.2/src/lauxlib.c similarity index 92% rename from libs/lua-5.3.1/src/lauxlib.c rename to libs/lua-5.3.2/src/lauxlib.c index b8bace7..5d362c3 100644 --- a/libs/lua-5.3.1/src/lauxlib.c +++ b/libs/lua-5.3.2/src/lauxlib.c @@ -1,5 +1,5 @@ /* -** $Id: lauxlib.c,v 1.280 2015/02/03 17:38:24 roberto Exp $ +** $Id: lauxlib.c,v 1.284 2015/11/19 19:16:22 roberto Exp $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ @@ -33,8 +33,8 @@ */ -#define LEVELS1 12 /* size of the first part of the stack */ -#define LEVELS2 10 /* size of the second part of the stack */ +#define LEVELS1 10 /* size of the first part of the stack */ +#define LEVELS2 11 /* size of the second part of the stack */ @@ -107,7 +107,7 @@ static void pushfuncname (lua_State *L, lua_Debug *ar) { } -static int countlevels (lua_State *L) { +static int lastlevel (lua_State *L) { lua_Debug ar; int li = 1, le = 1; /* find an upper bound */ @@ -126,14 +126,16 @@ LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level) { lua_Debug ar; int top = lua_gettop(L); - int numlevels = countlevels(L1); - int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0; - if (msg) lua_pushfstring(L, "%s\n", msg); + int last = lastlevel(L1); + int n1 = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1; + if (msg) + lua_pushfstring(L, "%s\n", msg); + luaL_checkstack(L, 10, NULL); lua_pushliteral(L, "stack traceback:"); while (lua_getstack(L1, level++, &ar)) { - if (level == mark) { /* too many levels? */ + if (n1-- == 0) { /* too many levels? */ lua_pushliteral(L, "\n\t..."); /* add a '...' */ - level = numlevels - LEVELS2; /* and skip to last ones */ + level = last - LEVELS2 + 1; /* and skip to last ones */ } else { lua_getinfo(L1, "Slnt", &ar); @@ -289,7 +291,7 @@ LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */ return 0; /* leave previous value on top, but return 0 */ lua_pop(L, 1); - lua_newtable(L); /* create metatable */ + lua_createtable(L, 0, 2); /* create metatable */ lua_pushstring(L, tname); lua_setfield(L, -2, "__name"); /* metatable.__name = tname */ lua_pushvalue(L, -1); @@ -435,6 +437,47 @@ LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg, ** ======================================================= */ +/* userdata to box arbitrary data */ +typedef struct UBox { + void *box; + size_t bsize; +} UBox; + + +static void *resizebox (lua_State *L, int idx, size_t newsize) { + void *ud; + lua_Alloc allocf = lua_getallocf(L, &ud); + UBox *box = (UBox *)lua_touserdata(L, idx); + void *temp = allocf(ud, box->box, box->bsize, newsize); + if (temp == NULL && newsize > 0) { /* allocation error? */ + resizebox(L, idx, 0); /* free buffer */ + luaL_error(L, "not enough memory for buffer allocation"); + } + box->box = temp; + box->bsize = newsize; + return temp; +} + + +static int boxgc (lua_State *L) { + resizebox(L, 1, 0); + return 0; +} + + +static void *newbox (lua_State *L, size_t newsize) { + UBox *box = (UBox *)lua_newuserdata(L, sizeof(UBox)); + box->box = NULL; + box->bsize = 0; + if (luaL_newmetatable(L, "LUABOX")) { /* creating metatable? */ + lua_pushcfunction(L, boxgc); + lua_setfield(L, -2, "__gc"); /* metatable.__gc = boxgc */ + } + lua_setmetatable(L, -2); + return resizebox(L, -1, newsize); +} + + /* ** check whether buffer is using a userdata on the stack as a temporary ** buffer @@ -455,11 +498,12 @@ LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { if (newsize < B->n || newsize - B->n < sz) luaL_error(L, "buffer too large"); /* create larger buffer */ - newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char)); - /* move content to new buffer */ - memcpy(newbuff, B->b, B->n * sizeof(char)); if (buffonstack(B)) - lua_remove(L, -2); /* remove old buffer */ + newbuff = (char *)resizebox(L, -1, newsize); + else { /* no buffer yet */ + newbuff = (char *)newbox(L, newsize); + memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */ + } B->b = newbuff; B->size = newsize; } @@ -468,9 +512,11 @@ LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { - char *b = luaL_prepbuffsize(B, l); - memcpy(b, s, l * sizeof(char)); - luaL_addsize(B, l); + if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */ + char *b = luaL_prepbuffsize(B, l); + memcpy(b, s, l * sizeof(char)); + luaL_addsize(B, l); + } } @@ -482,8 +528,10 @@ LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { LUALIB_API void luaL_pushresult (luaL_Buffer *B) { lua_State *L = B->L; lua_pushlstring(L, B->b, B->n); - if (buffonstack(B)) - lua_remove(L, -2); /* remove old buffer */ + if (buffonstack(B)) { + resizebox(L, -2, 0); /* delete old buffer */ + lua_remove(L, -2); /* remove its header from the stack */ + } } @@ -605,7 +653,7 @@ static int errfile (lua_State *L, const char *what, int fnameindex) { static int skipBOM (LoadF *lf) { - const char *p = "\xEF\xBB\xBF"; /* Utf8 BOM mark */ + const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */ int c; lf->n = 0; do { diff --git a/libs/lua-5.3.1/src/lauxlib.h b/libs/lua-5.3.2/src/lauxlib.h similarity index 98% rename from libs/lua-5.3.1/src/lauxlib.h rename to libs/lua-5.3.2/src/lauxlib.h index 0bac246..ddb7c22 100644 --- a/libs/lua-5.3.1/src/lauxlib.h +++ b/libs/lua-5.3.2/src/lauxlib.h @@ -1,5 +1,5 @@ /* -** $Id: lauxlib.h,v 1.128 2014/10/29 16:11:17 roberto Exp $ +** $Id: lauxlib.h,v 1.129 2015/11/23 11:29:43 roberto Exp $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ @@ -65,7 +65,7 @@ LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def, LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname); LUALIB_API int (luaL_execresult) (lua_State *L, int stat); -/* pre-defined references */ +/* predefined references */ #define LUA_NOREF (-2) #define LUA_REFNIL (-1) diff --git a/libs/lua-5.3.1/src/lbaselib.c b/libs/lua-5.3.2/src/lbaselib.c similarity index 92% rename from libs/lua-5.3.1/src/lbaselib.c rename to libs/lua-5.3.2/src/lbaselib.c index 9a15124..861823d 100644 --- a/libs/lua-5.3.1/src/lbaselib.c +++ b/libs/lua-5.3.2/src/lbaselib.c @@ -1,5 +1,5 @@ /* -** $Id: lbaselib.c,v 1.310 2015/03/28 19:14:47 roberto Exp $ +** $Id: lbaselib.c,v 1.312 2015/10/29 15:21:04 roberto Exp $ ** Basic library ** See Copyright Notice in lua.h */ @@ -86,8 +86,8 @@ static int luaB_tonumber (lua_State *L) { const char *s; lua_Integer n = 0; /* to avoid warnings */ lua_Integer base = luaL_checkinteger(L, 2); - luaL_checktype(L, 1, LUA_TSTRING); /* before 'luaL_checklstring'! */ - s = luaL_checklstring(L, 1, &l); + luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */ + s = lua_tolstring(L, 1, &l); luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); if (b_str2int(s, (int)base, &n) == s + l) { lua_pushinteger(L, n); @@ -198,12 +198,10 @@ static int luaB_collectgarbage (lua_State *L) { } -/* -** This function has all type names as upvalues, to maximize performance. -*/ static int luaB_type (lua_State *L) { - luaL_checkany(L, 1); - lua_pushvalue(L, lua_upvalueindex(lua_type(L, 1) + 1)); + int t = lua_type(L, 1); + luaL_argcheck(L, t != LUA_TNONE, 1, "value expected"); + lua_pushstring(L, lua_typename(L, t)); return 1; } @@ -243,18 +241,7 @@ static int luaB_pairs (lua_State *L) { /* -** Traversal function for 'ipairs' for raw tables -*/ -static int ipairsaux_raw (lua_State *L) { - lua_Integer i = luaL_checkinteger(L, 2) + 1; - luaL_checktype(L, 1, LUA_TTABLE); - lua_pushinteger(L, i); - return (lua_rawgeti(L, 1, i) == LUA_TNIL) ? 1 : 2; -} - - -/* -** Traversal function for 'ipairs' for tables with metamethods +** Traversal function for 'ipairs' */ static int ipairsaux (lua_State *L) { lua_Integer i = luaL_checkinteger(L, 2) + 1; @@ -269,13 +256,11 @@ static int ipairsaux (lua_State *L) { ** that can affect the traversal. */ static int luaB_ipairs (lua_State *L) { - lua_CFunction iter = (luaL_getmetafield(L, 1, "__index") != LUA_TNIL) - ? ipairsaux : ipairsaux_raw; #if defined(LUA_COMPAT_IPAIRS) - return pairsmeta(L, "__ipairs", 1, iter); + return pairsmeta(L, "__ipairs", 1, ipairsaux); #else luaL_checkany(L, 1); - lua_pushcfunction(L, iter); /* iteration function */ + lua_pushcfunction(L, ipairsaux); /* iteration function */ lua_pushvalue(L, 1); /* state */ lua_pushinteger(L, 0); /* initial value */ return 3; @@ -490,9 +475,9 @@ static const luaL_Reg base_funcs[] = { {"setmetatable", luaB_setmetatable}, {"tonumber", luaB_tonumber}, {"tostring", luaB_tostring}, + {"type", luaB_type}, {"xpcall", luaB_xpcall}, /* placeholders */ - {"type", NULL}, {"_G", NULL}, {"_VERSION", NULL}, {NULL, NULL} @@ -500,7 +485,6 @@ static const luaL_Reg base_funcs[] = { LUAMOD_API int luaopen_base (lua_State *L) { - int i; /* open lib into global table */ lua_pushglobaltable(L); luaL_setfuncs(L, base_funcs, 0); @@ -510,11 +494,6 @@ LUAMOD_API int luaopen_base (lua_State *L) { /* set global _VERSION */ lua_pushliteral(L, LUA_VERSION); lua_setfield(L, -2, "_VERSION"); - /* set function 'type' with proper upvalues */ - for (i = 0; i < LUA_NUMTAGS; i++) /* push all type names as upvalues */ - lua_pushstring(L, lua_typename(L, i)); - lua_pushcclosure(L, luaB_type, LUA_NUMTAGS); - lua_setfield(L, -2, "type"); return 1; } diff --git a/libs/lua-5.3.1/src/lbitlib.c b/libs/lua-5.3.2/src/lbitlib.c similarity index 80% rename from libs/lua-5.3.1/src/lbitlib.c rename to libs/lua-5.3.2/src/lbitlib.c index 15d5f0c..1cb1d5b 100644 --- a/libs/lua-5.3.1/src/lbitlib.c +++ b/libs/lua-5.3.2/src/lbitlib.c @@ -1,5 +1,5 @@ /* -** $Id: lbitlib.c,v 1.28 2014/11/02 19:19:04 roberto Exp $ +** $Id: lbitlib.c,v 1.30 2015/11/11 19:08:09 roberto Exp $ ** Standard library for bitwise operations ** See Copyright Notice in lua.h */ @@ -19,6 +19,10 @@ #if defined(LUA_COMPAT_BITLIB) /* { */ +#define pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) +#define checkunsigned(L,i) ((lua_Unsigned)luaL_checkinteger(L,i)) + + /* number of bits to consider in a number */ #if !defined(LUA_NBITS) #define LUA_NBITS 32 @@ -46,14 +50,14 @@ static lua_Unsigned andaux (lua_State *L) { int i, n = lua_gettop(L); lua_Unsigned r = ~(lua_Unsigned)0; for (i = 1; i <= n; i++) - r &= luaL_checkunsigned(L, i); + r &= checkunsigned(L, i); return trim(r); } static int b_and (lua_State *L) { lua_Unsigned r = andaux(L); - lua_pushunsigned(L, r); + pushunsigned(L, r); return 1; } @@ -69,8 +73,8 @@ static int b_or (lua_State *L) { int i, n = lua_gettop(L); lua_Unsigned r = 0; for (i = 1; i <= n; i++) - r |= luaL_checkunsigned(L, i); - lua_pushunsigned(L, trim(r)); + r |= checkunsigned(L, i); + pushunsigned(L, trim(r)); return 1; } @@ -79,15 +83,15 @@ static int b_xor (lua_State *L) { int i, n = lua_gettop(L); lua_Unsigned r = 0; for (i = 1; i <= n; i++) - r ^= luaL_checkunsigned(L, i); - lua_pushunsigned(L, trim(r)); + r ^= checkunsigned(L, i); + pushunsigned(L, trim(r)); return 1; } static int b_not (lua_State *L) { - lua_Unsigned r = ~luaL_checkunsigned(L, 1); - lua_pushunsigned(L, trim(r)); + lua_Unsigned r = ~checkunsigned(L, 1); + pushunsigned(L, trim(r)); return 1; } @@ -104,23 +108,23 @@ static int b_shift (lua_State *L, lua_Unsigned r, lua_Integer i) { else r <<= i; r = trim(r); } - lua_pushunsigned(L, r); + pushunsigned(L, r); return 1; } static int b_lshift (lua_State *L) { - return b_shift(L, luaL_checkunsigned(L, 1), luaL_checkinteger(L, 2)); + return b_shift(L, checkunsigned(L, 1), luaL_checkinteger(L, 2)); } static int b_rshift (lua_State *L) { - return b_shift(L, luaL_checkunsigned(L, 1), -luaL_checkinteger(L, 2)); + return b_shift(L, checkunsigned(L, 1), -luaL_checkinteger(L, 2)); } static int b_arshift (lua_State *L) { - lua_Unsigned r = luaL_checkunsigned(L, 1); + lua_Unsigned r = checkunsigned(L, 1); lua_Integer i = luaL_checkinteger(L, 2); if (i < 0 || !(r & ((lua_Unsigned)1 << (LUA_NBITS - 1)))) return b_shift(L, r, -i); @@ -128,19 +132,19 @@ static int b_arshift (lua_State *L) { if (i >= LUA_NBITS) r = ALLONES; else r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i)); /* add signal bit */ - lua_pushunsigned(L, r); + pushunsigned(L, r); return 1; } } static int b_rot (lua_State *L, lua_Integer d) { - lua_Unsigned r = luaL_checkunsigned(L, 1); + lua_Unsigned r = checkunsigned(L, 1); int i = d & (LUA_NBITS - 1); /* i = d % NBITS */ r = trim(r); if (i != 0) /* avoid undefined shift of LUA_NBITS when i == 0 */ r = (r << i) | (r >> (LUA_NBITS - i)); - lua_pushunsigned(L, trim(r)); + pushunsigned(L, trim(r)); return 1; } @@ -175,23 +179,22 @@ static int fieldargs (lua_State *L, int farg, int *width) { static int b_extract (lua_State *L) { int w; - lua_Unsigned r = trim(luaL_checkunsigned(L, 1)); + lua_Unsigned r = trim(checkunsigned(L, 1)); int f = fieldargs(L, 2, &w); r = (r >> f) & mask(w); - lua_pushunsigned(L, r); + pushunsigned(L, r); return 1; } static int b_replace (lua_State *L) { int w; - lua_Unsigned r = trim(luaL_checkunsigned(L, 1)); - lua_Unsigned v = luaL_checkunsigned(L, 2); + lua_Unsigned r = trim(checkunsigned(L, 1)); + lua_Unsigned v = trim(checkunsigned(L, 2)); int f = fieldargs(L, 3, &w); - int m = mask(w); - v &= m; /* erase bits outside given width */ - r = (r & ~(m << f)) | (v << f); - lua_pushunsigned(L, r); + lua_Unsigned m = mask(w); + r = (r & ~(m << f)) | ((v & m) << f); + pushunsigned(L, r); return 1; } diff --git a/libs/lua-5.3.1/src/lcode.c b/libs/lua-5.3.2/src/lcode.c similarity index 99% rename from libs/lua-5.3.1/src/lcode.c rename to libs/lua-5.3.2/src/lcode.c index d6f0fcd..7c6918f 100644 --- a/libs/lua-5.3.1/src/lcode.c +++ b/libs/lua-5.3.2/src/lcode.c @@ -1,5 +1,5 @@ /* -** $Id: lcode.c,v 2.101 2015/04/29 18:24:11 roberto Exp $ +** $Id: lcode.c,v 2.103 2015/11/19 19:16:22 roberto Exp $ ** Code generator for Lua ** See Copyright Notice in lua.h */ @@ -37,7 +37,7 @@ static int tonumeral(expdesc *e, TValue *v) { - if (e->t != NO_JUMP || e->f != NO_JUMP) + if (hasjumps(e)) return 0; /* not a numeral */ switch (e->k) { case VKINT: @@ -816,7 +816,7 @@ static void codeexpval (FuncState *fs, OpCode op, freeexp(fs, e1); } e1->u.info = luaK_codeABC(fs, op, 0, o1, o2); /* generate opcode */ - e1->k = VRELOCABLE; /* all those operations are relocable */ + e1->k = VRELOCABLE; /* all those operations are relocatable */ luaK_fixline(fs, line); } } diff --git a/libs/lua-5.3.1/src/lcode.h b/libs/lua-5.3.2/src/lcode.h similarity index 100% rename from libs/lua-5.3.1/src/lcode.h rename to libs/lua-5.3.2/src/lcode.h diff --git a/libs/lua-5.3.1/src/lcorolib.c b/libs/lua-5.3.2/src/lcorolib.c similarity index 100% rename from libs/lua-5.3.1/src/lcorolib.c rename to libs/lua-5.3.2/src/lcorolib.c diff --git a/libs/lua-5.3.1/src/lctype.c b/libs/lua-5.3.2/src/lctype.c similarity index 100% rename from libs/lua-5.3.1/src/lctype.c rename to libs/lua-5.3.2/src/lctype.c diff --git a/libs/lua-5.3.1/src/lctype.h b/libs/lua-5.3.2/src/lctype.h similarity index 100% rename from libs/lua-5.3.1/src/lctype.h rename to libs/lua-5.3.2/src/lctype.h diff --git a/libs/lua-5.3.1/src/ldblib.c b/libs/lua-5.3.2/src/ldblib.c similarity index 98% rename from libs/lua-5.3.1/src/ldblib.c rename to libs/lua-5.3.2/src/ldblib.c index 9151458..786f6cd 100644 --- a/libs/lua-5.3.1/src/ldblib.c +++ b/libs/lua-5.3.2/src/ldblib.c @@ -1,5 +1,5 @@ /* -** $Id: ldblib.c,v 1.149 2015/02/19 17:06:21 roberto Exp $ +** $Id: ldblib.c,v 1.151 2015/11/23 11:29:43 roberto Exp $ ** Interface from Lua to its debug API ** See Copyright Notice in lua.h */ @@ -28,8 +28,8 @@ static const int HOOKKEY = 0; /* -** If L1 != L, L1 can be in any state, and therefore there is no -** garanties about its stack space; any push in L1 must be +** If L1 != L, L1 can be in any state, and therefore there are no +** guarantees about its stack space; any push in L1 must be ** checked. */ static void checkstack (lua_State *L, lua_State *L1, int n) { diff --git a/libs/lua-5.3.1/src/ldebug.c b/libs/lua-5.3.2/src/ldebug.c similarity index 98% rename from libs/lua-5.3.1/src/ldebug.c rename to libs/lua-5.3.2/src/ldebug.c index f76582c..9bd86d0 100644 --- a/libs/lua-5.3.1/src/ldebug.c +++ b/libs/lua-5.3.2/src/ldebug.c @@ -1,5 +1,5 @@ /* -** $Id: ldebug.c,v 2.115 2015/05/22 17:45:56 roberto Exp $ +** $Id: ldebug.c,v 2.117 2015/11/02 18:48:07 roberto Exp $ ** Debug Interface ** See Copyright Notice in lua.h */ @@ -618,7 +618,7 @@ l_noret luaG_errormsg (lua_State *L) { setobjs2s(L, L->top, L->top - 1); /* move argument */ setobjs2s(L, L->top - 1, errfunc); /* push function */ L->top++; /* assume EXTRA_STACK */ - luaD_call(L, L->top - 2, 1, 0); /* call it */ + luaD_callnoyield(L, L->top - 2, 1); /* call it */ } luaD_throw(L, LUA_ERRRUN); } @@ -640,9 +640,11 @@ l_noret luaG_runerror (lua_State *L, const char *fmt, ...) { void luaG_traceexec (lua_State *L) { CallInfo *ci = L->ci; lu_byte mask = L->hookmask; - int counthook = ((mask & LUA_MASKCOUNT) && L->hookcount == 0); + int counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT)); if (counthook) resethookcount(L); /* reset count */ + else if (!(mask & LUA_MASKLINE)) + return; /* no line hook and count != 0; nothing to be done */ if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */ ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */ return; /* do not call hook again (VM yielded, so it did not move) */ diff --git a/libs/lua-5.3.1/src/ldebug.h b/libs/lua-5.3.2/src/ldebug.h similarity index 100% rename from libs/lua-5.3.1/src/ldebug.h rename to libs/lua-5.3.2/src/ldebug.h diff --git a/libs/lua-5.3.1/src/ldo.c b/libs/lua-5.3.2/src/ldo.c similarity index 79% rename from libs/lua-5.3.1/src/ldo.c rename to libs/lua-5.3.2/src/ldo.c index 5c93a25..95efd56 100644 --- a/libs/lua-5.3.1/src/ldo.c +++ b/libs/lua-5.3.2/src/ldo.c @@ -1,5 +1,5 @@ /* -** $Id: ldo.c,v 2.138 2015/05/22 17:48:19 roberto Exp $ +** $Id: ldo.c,v 2.150 2015/11/19 19:16:22 roberto Exp $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ @@ -150,6 +150,11 @@ int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { /* }====================================================== */ +/* +** {================================================================== +** Stack reallocation +** =================================================================== +*/ static void correctstack (lua_State *L, TValue *oldstack) { CallInfo *ci; UpVal *up; @@ -221,14 +226,22 @@ void luaD_shrinkstack (lua_State *L) { luaE_freeCI(L); /* free all CIs (list grew because of an error) */ else luaE_shrinkCI(L); /* shrink list */ - if (inuse > LUAI_MAXSTACK || /* still handling stack overflow? */ - goodsize >= L->stacksize) /* would grow instead of shrink? */ - condmovestack(L); /* don't change stack (change only for debugging) */ - else + if (inuse <= LUAI_MAXSTACK && /* not handling stack overflow? */ + goodsize < L->stacksize) /* trying to shrink? */ luaD_reallocstack(L, goodsize); /* shrink it */ + else + condmovestack(L,,); /* don't change stack (change only for debugging) */ } +void luaD_inctop (lua_State *L) { + luaD_checkstack(L, 1); + L->top++; +} + +/* }================================================================== */ + + void luaD_hook (lua_State *L, int event, int line) { lua_Hook hook = L->hook; if (hook && L->allowhook) { @@ -273,15 +286,15 @@ static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { int i; int nfixargs = p->numparams; StkId base, fixed; - lua_assert(actual >= nfixargs); /* move fixed parameters to final position */ - luaD_checkstack(L, p->maxstacksize); /* check again for new 'base' */ fixed = L->top - actual; /* first fixed argument */ base = L->top; /* final position of first argument */ - for (i=0; itop++, fixed + i); - setnilvalue(fixed + i); + setnilvalue(fixed + i); /* erase original copy (for GC) */ } + for (; i < nfixargs; i++) + setnilvalue(L->top++); /* complete missing arguments */ return base; } @@ -308,26 +321,36 @@ static void tryfuncTM (lua_State *L, StkId func) { #define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L))) +/* macro to check stack size, preserving 'p' */ +#define checkstackp(L,n,p) \ + luaD_checkstackaux(L, n, \ + ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \ + luaC_checkGC(L), /* stack grow uses memory */ \ + p = restorestack(L, t__)) /* 'pos' part: restore 'p' */ + + /* -** returns true if function has been executed (C function) +** Prepares a function call: checks the stack, creates a new CallInfo +** entry, fills in the relevant information, calls hook if needed. +** If function is a C function, does the call, too. (Otherwise, leave +** the execution ('luaV_execute') to the caller, to allow stackless +** calls.) Returns true iff function has been executed (C function). */ int luaD_precall (lua_State *L, StkId func, int nresults) { lua_CFunction f; CallInfo *ci; - int n; /* number of arguments (Lua) or returns (C) */ - ptrdiff_t funcr = savestack(L, func); switch (ttype(func)) { + case LUA_TCCL: /* C closure */ + f = clCvalue(func)->f; + goto Cfunc; case LUA_TLCF: /* light C function */ f = fvalue(func); - goto Cfunc; - case LUA_TCCL: { /* C closure */ - f = clCvalue(func)->f; - Cfunc: - luaC_checkGC(L); /* stack grow uses memory */ - luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ + Cfunc: { + int n; /* number of returns */ + checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */ ci = next_ci(L); /* now 'enter' new function */ ci->nresults = nresults; - ci->func = restorestack(L, funcr); + ci->func = func; ci->top = L->top + LUA_MINSTACK; lua_assert(ci->top <= L->stack_last); ci->callstatus = 0; @@ -337,41 +360,36 @@ int luaD_precall (lua_State *L, StkId func, int nresults) { n = (*f)(L); /* do the actual call */ lua_lock(L); api_checknelems(L, n); - luaD_poscall(L, L->top - n, n); + luaD_poscall(L, ci, L->top - n, n); return 1; } case LUA_TLCL: { /* Lua function: prepare its call */ StkId base; Proto *p = clLvalue(func)->p; - n = cast_int(L->top - func) - 1; /* number of real arguments */ - luaC_checkGC(L); /* stack grow uses memory */ - luaD_checkstack(L, p->maxstacksize); - for (; n < p->numparams; n++) - setnilvalue(L->top++); /* complete missing arguments */ - if (!p->is_vararg) { - func = restorestack(L, funcr); + int n = cast_int(L->top - func) - 1; /* number of real arguments */ + int fsize = p->maxstacksize; /* frame size */ + checkstackp(L, fsize, func); + if (p->is_vararg != 1) { /* do not use vararg? */ + for (; n < p->numparams; n++) + setnilvalue(L->top++); /* complete missing arguments */ base = func + 1; } - else { + else base = adjust_varargs(L, p, n); - func = restorestack(L, funcr); /* previous call can change stack */ - } ci = next_ci(L); /* now 'enter' new function */ ci->nresults = nresults; ci->func = func; ci->u.l.base = base; - ci->top = base + p->maxstacksize; + L->top = ci->top = base + fsize; lua_assert(ci->top <= L->stack_last); ci->u.l.savedpc = p->code; /* starting point */ ci->callstatus = CIST_LUA; - L->top = ci->top; if (L->hookmask & LUA_MASKCALL) callhook(L, ci); return 0; } default: { /* not a function */ - luaD_checkstack(L, 1); /* ensure space for metamethod */ - func = restorestack(L, funcr); /* previous call may change stack */ + checkstackp(L, 1, func); /* ensure space for metamethod */ tryfuncTM(L, func); /* try to get '__call' metamethod */ return luaD_precall(L, func, nresults); /* now it must be a function */ } @@ -379,10 +397,57 @@ int luaD_precall (lua_State *L, StkId func, int nresults) { } -int luaD_poscall (lua_State *L, StkId firstResult, int nres) { +/* +** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'. +** Handle most typical cases (zero results for commands, one result for +** expressions, multiple results for tail calls/single parameters) +** separated. +*/ +static int moveresults (lua_State *L, const TValue *firstResult, StkId res, + int nres, int wanted) { + switch (wanted) { /* handle typical cases separately */ + case 0: break; /* nothing to move */ + case 1: { /* one result needed */ + if (nres == 0) /* no results? */ + firstResult = luaO_nilobject; /* adjust with nil */ + setobjs2s(L, res, firstResult); /* move it to proper place */ + break; + } + case LUA_MULTRET: { + int i; + for (i = 0; i < nres; i++) /* move all results to correct place */ + setobjs2s(L, res + i, firstResult + i); + L->top = res + nres; + return 0; /* wanted == LUA_MULTRET */ + } + default: { + int i; + if (wanted <= nres) { /* enough results? */ + for (i = 0; i < wanted; i++) /* move wanted results to correct place */ + setobjs2s(L, res + i, firstResult + i); + } + else { /* not enough results; use all of them plus nils */ + for (i = 0; i < nres; i++) /* move all results to correct place */ + setobjs2s(L, res + i, firstResult + i); + for (; i < wanted; i++) /* complete wanted number of results */ + setnilvalue(res + i); + } + break; + } + } + L->top = res + wanted; /* top points after the last result */ + return 1; +} + + +/* +** Finishes a function call: calls hook if necessary, removes CallInfo, +** moves current number of results to proper place; returns 0 iff call +** wanted multiple (variable number of) results. +*/ +int luaD_poscall (lua_State *L, CallInfo *ci, StkId firstResult, int nres) { StkId res; - int wanted, i; - CallInfo *ci = L->ci; + int wanted = ci->nresults; if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) { if (L->hookmask & LUA_MASKRET) { ptrdiff_t fr = savestack(L, firstResult); /* hook may change stack */ @@ -392,15 +457,24 @@ int luaD_poscall (lua_State *L, StkId firstResult, int nres) { L->oldpc = ci->previous->u.l.savedpc; /* 'oldpc' for caller function */ } res = ci->func; /* res == final position of 1st result */ - wanted = ci->nresults; L->ci = ci->previous; /* back to caller */ - /* move results to correct place */ - for (i = wanted; i != 0 && nres-- > 0; i--) - setobjs2s(L, res++, firstResult++); - while (i-- > 0) - setnilvalue(res++); - L->top = res; - return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ + /* move results to proper place */ + return moveresults(L, firstResult, res, nres, wanted); +} + + +/* +** Check appropriate error for stack overflow ("regular" overflow or +** overflow while handling stack overflow). If 'nCalls' is larger than +** LUAI_MAXCCALLS (which means it is handling a "regular" overflow) but +** smaller than 9/8 of LUAI_MAXCCALLS, does not report an error (to +** allow overflow handling to work) +*/ +static void stackerror (lua_State *L) { + if (L->nCcalls == LUAI_MAXCCALLS) + luaG_runerror(L, "C stack overflow"); + else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) + luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ } @@ -410,21 +484,25 @@ int luaD_poscall (lua_State *L, StkId firstResult, int nres) { ** When returns, all the results are on the stack, starting at the original ** function position. */ -void luaD_call (lua_State *L, StkId func, int nResults, int allowyield) { - if (++L->nCcalls >= LUAI_MAXCCALLS) { - if (L->nCcalls == LUAI_MAXCCALLS) - luaG_runerror(L, "C stack overflow"); - else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) - luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ - } - if (!allowyield) L->nny++; +void luaD_call (lua_State *L, StkId func, int nResults) { + if (++L->nCcalls >= LUAI_MAXCCALLS) + stackerror(L); if (!luaD_precall(L, func, nResults)) /* is a Lua function? */ luaV_execute(L); /* call it */ - if (!allowyield) L->nny--; L->nCcalls--; } +/* +** Similar to 'luaD_call', but does not allow yields during the call +*/ +void luaD_callnoyield (lua_State *L, StkId func, int nResults) { + L->nny++; + luaD_call(L, func, nResults); + L->nny--; +} + + /* ** Completes the execution of an interrupted C function, calling its ** continuation function. @@ -449,7 +527,7 @@ static void finishCcall (lua_State *L, int status) { lua_lock(L); api_checknelems(L, n); /* finish 'luaD_precall' */ - luaD_poscall(L, L->top - n, n); + luaD_poscall(L, ci, L->top - n, n); } @@ -560,7 +638,7 @@ static void resume (lua_State *L, void *ud) { api_checknelems(L, n); firstArg = L->top - n; /* yield results come from continuation */ } - luaD_poscall(L, firstArg, n); /* finish 'luaD_precall' */ + luaD_poscall(L, ci, firstArg, n); /* finish 'luaD_precall' */ } unroll(L, NULL); /* run continuation */ } @@ -570,7 +648,7 @@ static void resume (lua_State *L, void *ud) { LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) { int status; - int oldnny = L->nny; /* save "number of non-yieldable" calls */ + unsigned short oldnny = L->nny; /* save "number of non-yieldable" calls */ lua_lock(L); luai_userstateresume(L, nargs); L->nCcalls = (from) ? from->nCcalls + 1 : 1; @@ -684,7 +762,7 @@ static void f_parser (lua_State *L, void *ud) { int c = zgetc(p->z); /* read first character */ if (c == LUA_SIGNATURE[0]) { checkmode(L, p->mode, "binary"); - cl = luaU_undump(L, p->z, &p->buff, p->name); + cl = luaU_undump(L, p->z, p->name); } else { checkmode(L, p->mode, "text"); diff --git a/libs/lua-5.3.1/src/ldo.h b/libs/lua-5.3.2/src/ldo.h similarity index 57% rename from libs/lua-5.3.1/src/ldo.h rename to libs/lua-5.3.2/src/ldo.h index edade65..80582dc 100644 --- a/libs/lua-5.3.1/src/ldo.h +++ b/libs/lua-5.3.2/src/ldo.h @@ -1,5 +1,5 @@ /* -** $Id: ldo.h,v 2.22 2015/05/22 17:48:19 roberto Exp $ +** $Id: ldo.h,v 2.28 2015/11/23 11:29:43 roberto Exp $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ @@ -13,11 +13,21 @@ #include "lzio.h" -#define luaD_checkstack(L,n) if (L->stack_last - L->top <= (n)) \ - luaD_growstack(L, n); else condmovestack(L); +/* +** Macro to check stack size and grow stack if needed. Parameters +** 'pre'/'pos' allow the macro to preserve a pointer into the +** stack across reallocations, doing the work only when needed. +** 'condmovestack' is used in heavy tests to force a stack reallocation +** at every check. +*/ +#define luaD_checkstackaux(L,n,pre,pos) \ + if (L->stack_last - L->top <= (n)) \ + { pre; luaD_growstack(L, n); pos; } else { condmovestack(L,pre,pos); } + +/* In general, 'pre'/'pos' are empty (nothing to save) */ +#define luaD_checkstack(L,n) luaD_checkstackaux(L,n,,) -#define incr_top(L) {L->top++; luaD_checkstack(L,0);} #define savestack(L,p) ((char *)(p) - (char *)L->stack) #define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) @@ -30,14 +40,16 @@ LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, const char *mode); LUAI_FUNC void luaD_hook (lua_State *L, int event, int line); LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults); -LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults, - int allowyield); +LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); +LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults); LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t oldtop, ptrdiff_t ef); -LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult, int nres); +LUAI_FUNC int luaD_poscall (lua_State *L, CallInfo *ci, StkId firstResult, + int nres); LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize); LUAI_FUNC void luaD_growstack (lua_State *L, int n); LUAI_FUNC void luaD_shrinkstack (lua_State *L); +LUAI_FUNC void luaD_inctop (lua_State *L); LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode); LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); diff --git a/libs/lua-5.3.1/src/ldump.c b/libs/lua-5.3.2/src/ldump.c similarity index 97% rename from libs/lua-5.3.1/src/ldump.c rename to libs/lua-5.3.2/src/ldump.c index 4c04812..016e300 100644 --- a/libs/lua-5.3.1/src/ldump.c +++ b/libs/lua-5.3.2/src/ldump.c @@ -1,5 +1,5 @@ /* -** $Id: ldump.c,v 2.36 2015/03/30 15:43:51 roberto Exp $ +** $Id: ldump.c,v 2.37 2015/10/08 15:53:49 roberto Exp $ ** save precompiled Lua chunks ** See Copyright Notice in lua.h */ @@ -38,7 +38,7 @@ typedef struct { static void DumpBlock (const void *b, size_t size, DumpState *D) { - if (D->status == 0) { + if (D->status == 0 && size > 0) { lua_unlock(D->L); D->status = (*D->writer)(D->L, b, size, D->data); lua_lock(D->L); diff --git a/libs/lua-5.3.1/src/lfunc.c b/libs/lua-5.3.2/src/lfunc.c similarity index 100% rename from libs/lua-5.3.1/src/lfunc.c rename to libs/lua-5.3.2/src/lfunc.c diff --git a/libs/lua-5.3.1/src/lfunc.h b/libs/lua-5.3.2/src/lfunc.h similarity index 100% rename from libs/lua-5.3.1/src/lfunc.h rename to libs/lua-5.3.2/src/lfunc.h diff --git a/libs/lua-5.3.1/src/lgc.c b/libs/lua-5.3.2/src/lgc.c similarity index 97% rename from libs/lua-5.3.1/src/lgc.c rename to libs/lua-5.3.2/src/lgc.c index 973c269..49d8ecb 100644 --- a/libs/lua-5.3.1/src/lgc.c +++ b/libs/lua-5.3.2/src/lgc.c @@ -1,5 +1,5 @@ /* -** $Id: lgc.c,v 2.205 2015/03/25 13:42:19 roberto Exp $ +** $Id: lgc.c,v 2.210 2015/11/03 18:10:44 roberto Exp $ ** Garbage Collector ** See Copyright Notice in lua.h */ @@ -114,8 +114,13 @@ static void reallymarkobject (global_State *g, GCObject *o); /* -** if key is not marked, mark its entry as dead (therefore removing it -** from the table) +** If key is not marked, mark its entry as dead. This allows key to be +** collected, but keeps its entry in the table. A dead node is needed +** when Lua looks up for a key (it may be part of a chain) and when +** traversing a weak table (key might be removed from the table during +** traversal). Other places never manipulate dead keys, because its +** associated nil value is enough to signal that the entry is logically +** empty. */ static void removeentry (Node *n) { lua_assert(ttisnil(gval(n))); @@ -542,7 +547,8 @@ static lu_mem traversethread (global_State *g, lua_State *th) { } else if (g->gckind != KGC_EMERGENCY) luaD_shrinkstack(th); /* do not change stack in emergency cycle */ - return (sizeof(lua_State) + sizeof(TValue) * th->stacksize); + return (sizeof(lua_State) + sizeof(TValue) * th->stacksize + + sizeof(CallInfo) * th->nci); } @@ -769,12 +775,11 @@ static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) { */ /* -** If possible, free concatenation buffer and shrink string table +** If possible, shrink string table */ static void checkSizes (lua_State *L, global_State *g) { if (g->gckind != KGC_EMERGENCY) { l_mem olddebt = g->GCdebt; - luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */ if (g->strt.nuse < g->strt.size / 4) /* string table too big? */ luaS_resize(L, g->strt.size / 2); /* shrink it a little */ g->GCestimate += g->GCdebt - olddebt; /* update estimate */ @@ -797,7 +802,7 @@ static GCObject *udata2finalize (global_State *g) { static void dothecall (lua_State *L, void *ud) { UNUSED(ud); - luaD_call(L, L->top - 2, 0, 0); + luaD_callnoyield(L, L->top - 2, 0); } @@ -1114,9 +1119,12 @@ void luaC_runtilstate (lua_State *L, int statesmask) { static l_mem getdebt (global_State *g) { l_mem debt = g->GCdebt; int stepmul = g->gcstepmul; - debt = (debt / STEPMULADJ) + 1; - debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM; - return debt; + if (debt <= 0) return 0; /* minimal debt */ + else { + debt = (debt / STEPMULADJ) + 1; + debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM; + return debt; + } } /* diff --git a/libs/lua-5.3.1/src/lgc.h b/libs/lua-5.3.2/src/lgc.h similarity index 77% rename from libs/lua-5.3.1/src/lgc.h rename to libs/lua-5.3.2/src/lgc.h index 0eedf84..1775ca4 100644 --- a/libs/lua-5.3.1/src/lgc.h +++ b/libs/lua-5.3.2/src/lgc.h @@ -1,5 +1,5 @@ /* -** $Id: lgc.h,v 2.86 2014/10/25 11:50:46 roberto Exp $ +** $Id: lgc.h,v 2.90 2015/10/21 18:15:15 roberto Exp $ ** Garbage Collector ** See Copyright Notice in lua.h */ @@ -101,26 +101,35 @@ #define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) -#define luaC_condGC(L,c) \ - {if (G(L)->GCdebt > 0) {c;}; condchangemem(L);} -#define luaC_checkGC(L) luaC_condGC(L, luaC_step(L);) +/* +** Does one step of collection when debt becomes positive. 'pre'/'pos' +** allows some adjustments to be done only when needed. macro +** 'condchangemem' is used only for heavy tests (forcing a full +** GC cycle on every opportunity) +*/ +#define luaC_condGC(L,pre,pos) \ + { if (G(L)->GCdebt > 0) { pre; luaC_step(L); pos;}; \ + condchangemem(L,pre,pos); } + +/* more often than not, 'pre'/'pos' are empty */ +#define luaC_checkGC(L) luaC_condGC(L,,) -#define luaC_barrier(L,p,v) { \ - if (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) \ - luaC_barrier_(L,obj2gco(p),gcvalue(v)); } +#define luaC_barrier(L,p,v) ( \ + (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ + luaC_barrier_(L,obj2gco(p),gcvalue(v)) : cast_void(0)) -#define luaC_barrierback(L,p,v) { \ - if (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) \ - luaC_barrierback_(L,p); } +#define luaC_barrierback(L,p,v) ( \ + (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ + luaC_barrierback_(L,p) : cast_void(0)) -#define luaC_objbarrier(L,p,o) { \ - if (isblack(p) && iswhite(o)) \ - luaC_barrier_(L,obj2gco(p),obj2gco(o)); } +#define luaC_objbarrier(L,p,o) ( \ + (isblack(p) && iswhite(o)) ? \ + luaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0)) -#define luaC_upvalbarrier(L,uv) \ - { if (iscollectable((uv)->v) && !upisopen(uv)) \ - luaC_upvalbarrier_(L,uv); } +#define luaC_upvalbarrier(L,uv) ( \ + (iscollectable((uv)->v) && !upisopen(uv)) ? \ + luaC_upvalbarrier_(L,uv) : cast_void(0)) LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o); LUAI_FUNC void luaC_freeallobjects (lua_State *L); diff --git a/libs/lua-5.3.1/src/linit.c b/libs/lua-5.3.2/src/linit.c similarity index 100% rename from libs/lua-5.3.1/src/linit.c rename to libs/lua-5.3.2/src/linit.c diff --git a/libs/lua-5.3.1/src/liolib.c b/libs/lua-5.3.2/src/liolib.c similarity index 96% rename from libs/lua-5.3.1/src/liolib.c rename to libs/lua-5.3.2/src/liolib.c index 193cac6..a91ba39 100644 --- a/libs/lua-5.3.1/src/liolib.c +++ b/libs/lua-5.3.2/src/liolib.c @@ -1,5 +1,5 @@ /* -** $Id: liolib.c,v 2.144 2015/04/03 18:41:57 roberto Exp $ +** $Id: liolib.c,v 2.148 2015/11/23 11:36:11 roberto Exp $ ** Standard I/O (and system) library ** See Copyright Notice in lua.h */ @@ -23,18 +23,24 @@ #include "lualib.h" -#if !defined(l_checkmode) + /* -** Check whether 'mode' matches '[rwa]%+?b?'. ** Change this macro to accept other modes for 'fopen' besides ** the standard ones. */ +#if !defined(l_checkmode) + +/* accepted extensions to 'mode' in 'fopen' */ +#if !defined(L_MODEEXT) +#define L_MODEEXT "b" +#endif + +/* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */ #define l_checkmode(mode) \ (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \ - (*mode != '+' || ++mode) && /* skip if char is '+' */ \ - (*mode != 'b' || ++mode) && /* skip if char is 'b' */ \ - (*mode == '\0')) + (*mode != '+' || (++mode, 1)) && /* skip if char is '+' */ \ + (strspn(mode, L_MODEEXT) == strlen(mode))) #endif @@ -176,7 +182,7 @@ static FILE *tofile (lua_State *L) { /* ** When creating file handles, always creates a 'closed' file handle ** before opening the actual file; so, if there is a memory error, the -** file is not left opened. +** handle is in a consistent state. */ static LStream *newprefile (lua_State *L) { LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream)); @@ -318,8 +324,15 @@ static int io_output (lua_State *L) { static int io_readline (lua_State *L); +/* +** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit +** in the limit for upvalues of a closure) +*/ +#define MAXARGLINE 250 + static void aux_lines (lua_State *L, int toclose) { int n = lua_gettop(L) - 1; /* number of arguments to read */ + luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments"); lua_pushinteger(L, n); /* number of arguments to read */ lua_pushboolean(L, toclose); /* close/not close file when finished */ lua_rotate(L, 2, 2); /* move 'n' and 'toclose' to their positions */ @@ -462,7 +475,7 @@ static int read_line (lua_State *L, FILE *f, int chop) { int c = '\0'; luaL_buffinit(L, &b); while (c != EOF && c != '\n') { /* repeat until end of line */ - char *buff = luaL_prepbuffer(&b); /* pre-allocate buffer */ + char *buff = luaL_prepbuffer(&b); /* preallocate buffer */ int i = 0; l_lockfile(f); /* no memory errors can happen inside the lock */ while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n') @@ -483,7 +496,7 @@ static void read_all (lua_State *L, FILE *f) { luaL_Buffer b; luaL_buffinit(L, &b); do { /* read file in chunks of LUAL_BUFFERSIZE bytes */ - char *p = luaL_prepbuffsize(&b, LUAL_BUFFERSIZE); + char *p = luaL_prepbuffer(&b); nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f); luaL_addsize(&b, nr); } while (nr == LUAL_BUFFERSIZE); diff --git a/libs/lua-5.3.1/src/llex.c b/libs/lua-5.3.2/src/llex.c similarity index 98% rename from libs/lua-5.3.1/src/llex.c rename to libs/lua-5.3.2/src/llex.c index c35bd55..16ea3eb 100644 --- a/libs/lua-5.3.1/src/llex.c +++ b/libs/lua-5.3.2/src/llex.c @@ -1,5 +1,5 @@ /* -** $Id: llex.c,v 2.93 2015/05/22 17:45:56 roberto Exp $ +** $Id: llex.c,v 2.95 2015/11/19 19:16:22 roberto Exp $ ** Lexical Analyzer ** See Copyright Notice in lua.h */ @@ -220,8 +220,6 @@ static void buffreplace (LexState *ls, char from, char to) { } -#define buff2num(b,o) (luaO_str2num(luaZ_buffer(b), o) != 0) - /* ** in case of format error, try to change decimal point separator to ** the one defined in the current locale and check again @@ -230,7 +228,7 @@ static void trydecpoint (LexState *ls, TValue *o) { char old = ls->decpoint; ls->decpoint = lua_getlocaledecpoint(); buffreplace(ls, old, ls->decpoint); /* try new decimal separator */ - if (!buff2num(ls->buff, o)) { + if (luaO_str2num(luaZ_buffer(ls->buff), o) == 0) { /* format error with correct decimal point: no more options */ buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */ lexerror(ls, "malformed number", TK_FLT); @@ -262,7 +260,7 @@ static int read_numeral (LexState *ls, SemInfo *seminfo) { } save(ls, '\0'); buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */ - if (!buff2num(ls->buff, &obj)) /* format error? */ + if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */ trydecpoint(ls, &obj); /* try to update decimal point separator */ if (ttisinteger(&obj)) { seminfo->i = ivalue(&obj); @@ -277,7 +275,7 @@ static int read_numeral (LexState *ls, SemInfo *seminfo) { /* -** skip a sequence '[=*[' or ']=*]'; if sequence is wellformed, return +** skip a sequence '[=*[' or ']=*]'; if sequence is well formed, return ** its number of '='s; otherwise, return a negative number (-1 iff there ** are no '='s after initial bracket) */ diff --git a/libs/lua-5.3.1/src/llex.h b/libs/lua-5.3.2/src/llex.h similarity index 100% rename from libs/lua-5.3.1/src/llex.h rename to libs/lua-5.3.2/src/llex.h diff --git a/libs/lua-5.3.1/src/llimits.h b/libs/lua-5.3.2/src/llimits.h similarity index 89% rename from libs/lua-5.3.1/src/llimits.h rename to libs/lua-5.3.2/src/llimits.h index 277c724..f21377f 100644 --- a/libs/lua-5.3.1/src/llimits.h +++ b/libs/lua-5.3.2/src/llimits.h @@ -1,5 +1,5 @@ /* -** $Id: llimits.h,v 1.135 2015/06/09 14:21:00 roberto Exp $ +** $Id: llimits.h,v 1.141 2015/11/19 19:16:22 roberto Exp $ ** Limits, basic types, and some other 'installation-dependent' definitions ** See Copyright Notice in lua.h */ @@ -64,7 +64,13 @@ typedef unsigned char lu_byte; #if defined(LUAI_USER_ALIGNMENT_T) typedef LUAI_USER_ALIGNMENT_T L_Umaxalign; #else -typedef union { double u; void *s; lua_Integer i; long l; } L_Umaxalign; +typedef union { + lua_Number n; + double u; + void *s; + lua_Integer i; + long l; +} L_Umaxalign; #endif @@ -78,7 +84,7 @@ typedef LUAI_UACINT l_uacInt; #if defined(lua_assert) #define check_exp(c,e) (lua_assert(c), (e)) /* to avoid problems with conditions too long */ -#define lua_longassert(c) { if (!(c)) lua_assert(0); } +#define lua_longassert(c) ((c) ? (void)0 : lua_assert(0)) #else #define lua_assert(c) ((void)0) #define check_exp(c,e) (e) @@ -184,10 +190,13 @@ typedef unsigned long Instruction; /* -** Size of cache for strings in the API (better be a prime) +** Size of cache for strings in the API. 'N' is the number of +** sets (better be a prime) and "M" is the size of each set (M == 1 +** makes a direct cache.) */ -#if !defined(STRCACHE_SIZE) -#define STRCACHE_SIZE 127 +#if !defined(STRCACHE_N) +#define STRCACHE_N 53 +#define STRCACHE_M 2 #endif @@ -198,7 +207,7 @@ typedef unsigned long Instruction; /* -** macros that are executed whenether program enters the Lua core +** macros that are executed whenever program enters the Lua core ** ('lua_lock') and leaves the core ('lua_unlock') */ #if !defined(lua_lock) @@ -297,17 +306,18 @@ typedef unsigned long Instruction; ** macro to control inclusion of some hard tests on stack reallocation */ #if !defined(HARDSTACKTESTS) -#define condmovestack(L) ((void)0) +#define condmovestack(L,pre,pos) ((void)0) #else /* realloc stack keeping its size */ -#define condmovestack(L) luaD_reallocstack((L), (L)->stacksize) +#define condmovestack(L,pre,pos) \ + { int sz_ = (L)->stacksize; pre; luaD_reallocstack((L), sz_); pos; } #endif #if !defined(HARDMEMTESTS) -#define condchangemem(L) condmovestack(L) +#define condchangemem(L,pre,pos) ((void)0) #else -#define condchangemem(L) \ - ((void)(!(G(L)->gcrunning) || (luaC_fullgc(L, 0), 1))) +#define condchangemem(L,pre,pos) \ + { if (G(L)->gcrunning) { pre; luaC_fullgc(L, 0); pos; } } #endif #endif diff --git a/libs/lua-5.3.1/src/lmathlib.c b/libs/lua-5.3.2/src/lmathlib.c similarity index 98% rename from libs/lua-5.3.1/src/lmathlib.c rename to libs/lua-5.3.2/src/lmathlib.c index 4f2ec60..94815f1 100644 --- a/libs/lua-5.3.1/src/lmathlib.c +++ b/libs/lua-5.3.2/src/lmathlib.c @@ -1,5 +1,5 @@ /* -** $Id: lmathlib.c,v 1.115 2015/03/12 14:04:04 roberto Exp $ +** $Id: lmathlib.c,v 1.117 2015/10/02 15:39:23 roberto Exp $ ** Standard mathematical library ** See Copyright Notice in lua.h */ @@ -39,7 +39,7 @@ static int math_abs (lua_State *L) { if (lua_isinteger(L, 1)) { lua_Integer n = lua_tointeger(L, 1); - if (n < 0) n = (lua_Integer)(0u - n); + if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n); lua_pushinteger(L, n); } else @@ -273,7 +273,7 @@ static int math_random (lua_State *L) { static int math_randomseed (lua_State *L) { l_srand((unsigned int)(lua_Integer)luaL_checknumber(L, 1)); - (void)rand(); /* discard first value to avoid undesirable correlations */ + (void)l_rand(); /* discard first value to avoid undesirable correlations */ return 0; } diff --git a/libs/lua-5.3.1/src/lmem.c b/libs/lua-5.3.2/src/lmem.c similarity index 100% rename from libs/lua-5.3.1/src/lmem.c rename to libs/lua-5.3.2/src/lmem.c diff --git a/libs/lua-5.3.1/src/lmem.h b/libs/lua-5.3.2/src/lmem.h similarity index 100% rename from libs/lua-5.3.1/src/lmem.h rename to libs/lua-5.3.2/src/lmem.h diff --git a/libs/lua-5.3.1/src/loadlib.c b/libs/lua-5.3.2/src/loadlib.c similarity index 99% rename from libs/lua-5.3.1/src/loadlib.c rename to libs/lua-5.3.2/src/loadlib.c index bbf8f67..7911928 100644 --- a/libs/lua-5.3.1/src/loadlib.c +++ b/libs/lua-5.3.2/src/loadlib.c @@ -1,5 +1,5 @@ /* -** $Id: loadlib.c,v 1.126 2015/02/16 13:14:33 roberto Exp $ +** $Id: loadlib.c,v 1.127 2015/11/23 11:30:45 roberto Exp $ ** Dynamic library loader for Lua ** See Copyright Notice in lua.h ** @@ -732,7 +732,7 @@ static void createsearcherstable (lua_State *L) { int i; /* create 'searchers' table */ lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); - /* fill it with pre-defined searchers */ + /* fill it with predefined searchers */ for (i=0; searchers[i] != NULL; i++) { lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ lua_pushcclosure(L, searchers[i], 1); diff --git a/libs/lua-5.3.1/src/lobject.c b/libs/lua-5.3.2/src/lobject.c similarity index 95% rename from libs/lua-5.3.1/src/lobject.c rename to libs/lua-5.3.2/src/lobject.c index 6c53b98..e24723f 100644 --- a/libs/lua-5.3.1/src/lobject.c +++ b/libs/lua-5.3.2/src/lobject.c @@ -1,5 +1,5 @@ /* -** $Id: lobject.c,v 2.104 2015/04/11 18:30:08 roberto Exp $ +** $Id: lobject.c,v 2.108 2015/11/02 16:09:30 roberto Exp $ ** Some generic functions over Lua objects ** See Copyright Notice in lua.h */ @@ -55,9 +55,7 @@ int luaO_int2fb (unsigned int x) { /* converts back */ int luaO_fb2int (int x) { - int e = (x >> 3) & 0x1f; - if (e == 0) return x; - else return ((x & 7) + 8) << (e - 1); + return (x < 8) ? x : ((x & 7) + 8) << ((x >> 3) - 1); } @@ -333,9 +331,9 @@ void luaO_tostring (lua_State *L, StkId obj) { size_t len; lua_assert(ttisnumber(obj)); if (ttisinteger(obj)) - len = lua_integer2str(buff, ivalue(obj)); + len = lua_integer2str(buff, sizeof(buff), ivalue(obj)); else { - len = lua_number2str(buff, fltvalue(obj)); + len = lua_number2str(buff, sizeof(buff), fltvalue(obj)); #if !defined(LUA_COMPAT_FLOATSTRING) if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */ buff[len++] = lua_getlocaledecpoint(); @@ -348,7 +346,8 @@ void luaO_tostring (lua_State *L, StkId obj) { static void pushstr (lua_State *L, const char *str, size_t l) { - setsvalue2s(L, L->top++, luaS_newlstr(L, str, l)); + setsvalue2s(L, L->top, luaS_newlstr(L, str, l)); + luaD_inctop(L); } @@ -359,7 +358,6 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { for (;;) { const char *e = strchr(fmt, '%'); if (e == NULL) break; - luaD_checkstack(L, 2); /* fmt + item */ pushstr(L, fmt, e - fmt); switch (*(e+1)) { case 's': { @@ -377,23 +375,23 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { break; } case 'd': { - setivalue(L->top++, va_arg(argp, int)); - luaO_tostring(L, L->top - 1); - break; + setivalue(L->top, va_arg(argp, int)); + goto top2str; } case 'I': { - setivalue(L->top++, cast(lua_Integer, va_arg(argp, l_uacInt))); - luaO_tostring(L, L->top - 1); - break; + setivalue(L->top, cast(lua_Integer, va_arg(argp, l_uacInt))); + goto top2str; } case 'f': { - setfltvalue(L->top++, cast_num(va_arg(argp, l_uacNumber))); + setfltvalue(L->top, cast_num(va_arg(argp, l_uacNumber))); + top2str: + luaD_inctop(L); luaO_tostring(L, L->top - 1); break; } case 'p': { char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */ - int l = sprintf(buff, "%p", va_arg(argp, void *)); + int l = l_sprintf(buff, sizeof(buff), "%p", va_arg(argp, void *)); pushstr(L, buff, l); break; } diff --git a/libs/lua-5.3.1/src/lobject.h b/libs/lua-5.3.2/src/lobject.h similarity index 93% rename from libs/lua-5.3.1/src/lobject.h rename to libs/lua-5.3.2/src/lobject.h index 9230b7a..2d52b41 100644 --- a/libs/lua-5.3.1/src/lobject.h +++ b/libs/lua-5.3.2/src/lobject.h @@ -1,5 +1,5 @@ /* -** $Id: lobject.h,v 2.111 2015/06/09 14:21:42 roberto Exp $ +** $Id: lobject.h,v 2.116 2015/11/03 18:33:10 roberto Exp $ ** Type definitions for Lua objects ** See Copyright Notice in lua.h */ @@ -19,8 +19,8 @@ /* ** Extra tags for non-values */ -#define LUA_TPROTO LUA_NUMTAGS -#define LUA_TDEADKEY (LUA_NUMTAGS+1) +#define LUA_TPROTO LUA_NUMTAGS /* function prototypes */ +#define LUA_TDEADKEY (LUA_NUMTAGS+1) /* removed keys in tables */ /* ** number of all possible tags (including LUA_TNONE but excluding DEADKEY) @@ -88,22 +88,32 @@ struct GCObject { -/* -** Union of all Lua values -*/ -typedef union Value Value; - - - /* ** Tagged Values. This is the basic representation of values in Lua, ** an actual value plus a tag with its type. */ +/* +** Union of all Lua values +*/ +typedef union Value { + GCObject *gc; /* collectable objects */ + void *p; /* light userdata */ + int b; /* booleans */ + lua_CFunction f; /* light C functions */ + lua_Integer i; /* integer numbers */ + lua_Number n; /* float numbers */ +} Value; + + #define TValuefields Value value_; int tt_ -typedef struct lua_TValue TValue; + +typedef struct lua_TValue { + TValuefields; +} TValue; + /* macro defining a nil value */ @@ -177,9 +187,9 @@ typedef struct lua_TValue TValue; /* Macros for internal tests */ #define righttt(obj) (ttype(obj) == gcvalue(obj)->tt) -#define checkliveness(g,obj) \ +#define checkliveness(L,obj) \ lua_longassert(!iscollectable(obj) || \ - (righttt(obj) && !isdead(g,gcvalue(obj)))) + (righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj))))) /* Macros to set values */ @@ -215,32 +225,32 @@ typedef struct lua_TValue TValue; #define setsvalue(L,obj,x) \ { TValue *io = (obj); TString *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \ - checkliveness(G(L),io); } + checkliveness(L,io); } #define setuvalue(L,obj,x) \ { TValue *io = (obj); Udata *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TUSERDATA)); \ - checkliveness(G(L),io); } + checkliveness(L,io); } #define setthvalue(L,obj,x) \ { TValue *io = (obj); lua_State *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTHREAD)); \ - checkliveness(G(L),io); } + checkliveness(L,io); } #define setclLvalue(L,obj,x) \ { TValue *io = (obj); LClosure *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TLCL)); \ - checkliveness(G(L),io); } + checkliveness(L,io); } #define setclCvalue(L,obj,x) \ { TValue *io = (obj); CClosure *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TCCL)); \ - checkliveness(G(L),io); } + checkliveness(L,io); } #define sethvalue(L,obj,x) \ { TValue *io = (obj); Table *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTABLE)); \ - checkliveness(G(L),io); } + checkliveness(L,io); } #define setdeadvalue(obj) settt_(obj, LUA_TDEADKEY) @@ -248,7 +258,7 @@ typedef struct lua_TValue TValue; #define setobj(L,obj1,obj2) \ { TValue *io1=(obj1); *io1 = *(obj2); \ - (void)L; checkliveness(G(L),io1); } + (void)L; checkliveness(L,io1); } /* @@ -264,12 +274,13 @@ typedef struct lua_TValue TValue; #define setptvalue2s setptvalue /* from table to same table */ #define setobjt2t setobj -/* to table */ -#define setobj2t setobj /* to new object */ #define setobj2n setobj #define setsvalue2n setsvalue +/* to table (define it as an expression to be used in macros) */ +#define setobj2t(L,o1,o2) ((void)L, *(o1)=*(o2), checkliveness(L,(o1))) + @@ -280,21 +291,6 @@ typedef struct lua_TValue TValue; */ -union Value { - GCObject *gc; /* collectable objects */ - void *p; /* light userdata */ - int b; /* booleans */ - lua_CFunction f; /* light C functions */ - lua_Integer i; /* integer numbers */ - lua_Number n; /* float numbers */ -}; - - -struct lua_TValue { - TValuefields; -}; - - typedef TValue *StkId; /* index to stack elements */ @@ -329,9 +325,9 @@ typedef union UTString { ** Get the actual string (array of bytes) from a 'TString'. ** (Access to 'extra' ensures that value is really a 'TString'.) */ -#define getaddrstr(ts) (cast(char *, (ts)) + sizeof(UTString)) #define getstr(ts) \ - check_exp(sizeof((ts)->extra), cast(const char*, getaddrstr(ts))) + check_exp(sizeof((ts)->extra), cast(char *, (ts)) + sizeof(UTString)) + /* get the actual string (array of bytes) from a Lua value */ #define svalue(o) getstr(tsvalue(o)) @@ -375,13 +371,13 @@ typedef union UUdata { #define setuservalue(L,u,o) \ { const TValue *io=(o); Udata *iu = (u); \ iu->user_ = io->value_; iu->ttuv_ = rttype(io); \ - checkliveness(G(L),io); } + checkliveness(L,io); } #define getuservalue(L,u,o) \ { TValue *io=(o); const Udata *iu = (u); \ io->value_ = iu->user_; settt_(io, iu->ttuv_); \ - checkliveness(G(L),io); } + checkliveness(L,io); } /* @@ -411,7 +407,7 @@ typedef struct LocVar { typedef struct Proto { CommonHeader; lu_byte numparams; /* number of fixed parameters */ - lu_byte is_vararg; + lu_byte is_vararg; /* 2: declared vararg; 1: uses vararg */ lu_byte maxstacksize; /* number of registers needed by this function */ int sizeupvalues; /* size of 'upvalues' */ int sizek; /* size of 'k' */ @@ -419,8 +415,8 @@ typedef struct Proto { int sizelineinfo; int sizep; /* size of 'p' */ int sizelocvars; - int linedefined; - int lastlinedefined; + int linedefined; /* debug information */ + int lastlinedefined; /* debug information */ TValue *k; /* constants used by the function */ Instruction *code; /* opcodes */ struct Proto **p; /* functions defined inside the function */ @@ -489,7 +485,7 @@ typedef union TKey { #define setnodekey(L,key,obj) \ { TKey *k_=(key); const TValue *io_=(obj); \ k_->nk.value_ = io_->value_; k_->nk.tt_ = io_->tt_; \ - (void)L; checkliveness(G(L),io_); } + (void)L; checkliveness(L,io_); } typedef struct Node { diff --git a/libs/lua-5.3.1/src/lopcodes.c b/libs/lua-5.3.2/src/lopcodes.c similarity index 100% rename from libs/lua-5.3.1/src/lopcodes.c rename to libs/lua-5.3.2/src/lopcodes.c diff --git a/libs/lua-5.3.1/src/lopcodes.h b/libs/lua-5.3.2/src/lopcodes.h similarity index 100% rename from libs/lua-5.3.1/src/lopcodes.h rename to libs/lua-5.3.2/src/lopcodes.h diff --git a/libs/lua-5.3.1/src/loslib.c b/libs/lua-5.3.2/src/loslib.c similarity index 82% rename from libs/lua-5.3.1/src/loslib.c rename to libs/lua-5.3.2/src/loslib.c index cb8a3c3..7dae533 100644 --- a/libs/lua-5.3.1/src/loslib.c +++ b/libs/lua-5.3.2/src/loslib.c @@ -1,5 +1,5 @@ /* -** $Id: loslib.c,v 1.57 2015/04/10 17:41:04 roberto Exp $ +** $Id: loslib.c,v 1.60 2015/11/19 19:16:22 roberto Exp $ ** Standard Operating System library ** See Copyright Notice in lua.h */ @@ -54,7 +54,12 @@ */ #define l_timet lua_Integer #define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t)) -#define l_checktime(L,a) ((time_t)luaL_checkinteger(L,a)) + +static time_t l_checktime (lua_State *L, int arg) { + lua_Integer t = luaL_checkinteger(L, arg); + luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds"); + return (time_t)t; +} #endif /* } */ @@ -198,17 +203,29 @@ static int getboolfield (lua_State *L, const char *key) { } -static int getfield (lua_State *L, const char *key, int d) { - int res, isnum; - lua_getfield(L, -1, key); - res = (int)lua_tointegerx(L, -1, &isnum); - if (!isnum) { - if (d < 0) +/* maximum value for date fields (to avoid arithmetic overflows with 'int') */ +#if !defined(L_MAXDATEFIELD) +#define L_MAXDATEFIELD (INT_MAX / 2) +#endif + +static int getfield (lua_State *L, const char *key, int d, int delta) { + int isnum; + int t = lua_getfield(L, -1, key); + lua_Integer res = lua_tointegerx(L, -1, &isnum); + if (!isnum) { /* field is not a number? */ + if (t != LUA_TNIL) /* some other value? */ + return luaL_error(L, "field '%s' not an integer", key); + else if (d < 0) /* absent field; no default? */ return luaL_error(L, "field '%s' missing in date table", key); res = d; } + else { + if (!(-L_MAXDATEFIELD <= res && res <= L_MAXDATEFIELD)) + return luaL_error(L, "field '%s' out-of-bounds", key); + res -= delta; + } lua_pop(L, 1); - return res; + return (int)res; } @@ -236,6 +253,10 @@ static const char *checkoption (lua_State *L, const char *conv, char *buff) { } +/* maximum size for an individual 'strftime' item */ +#define SIZETIMEFMT 250 + + static int os_date (lua_State *L) { const char *s = luaL_optstring(L, 1, "%c"); time_t t = luaL_opt(L, l_checktime, 2, time(NULL)); @@ -247,8 +268,8 @@ static int os_date (lua_State *L) { else stm = l_localtime(&t, &tmr); if (stm == NULL) /* invalid date? */ - lua_pushnil(L); - else if (strcmp(s, "*t") == 0) { + luaL_error(L, "time result cannot be represented in this installation"); + if (strcmp(s, "*t") == 0) { lua_createtable(L, 0, 9); /* 9 = number of fields */ setfield(L, "sec", stm->tm_sec); setfield(L, "min", stm->tm_min); @@ -266,14 +287,14 @@ static int os_date (lua_State *L) { cc[0] = '%'; luaL_buffinit(L, &b); while (*s) { - if (*s != '%') /* no conversion specifier? */ + if (*s != '%') /* not a conversion specifier? */ luaL_addchar(&b, *s++); else { size_t reslen; - char buff[200]; /* should be big enough for any conversion result */ + char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT); s = checkoption(L, s + 1, cc); - reslen = strftime(buff, sizeof(buff), cc, stm); - luaL_addlstring(&b, buff, reslen); + reslen = strftime(buff, SIZETIMEFMT, cc, stm); + luaL_addsize(&b, reslen); } } luaL_pushresult(&b); @@ -290,21 +311,18 @@ static int os_time (lua_State *L) { struct tm ts; luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); /* make sure table is at the top */ - ts.tm_sec = getfield(L, "sec", 0); - ts.tm_min = getfield(L, "min", 0); - ts.tm_hour = getfield(L, "hour", 12); - ts.tm_mday = getfield(L, "day", -1); - ts.tm_mon = getfield(L, "month", -1) - 1; - ts.tm_year = getfield(L, "year", -1) - 1900; + ts.tm_sec = getfield(L, "sec", 0, 0); + ts.tm_min = getfield(L, "min", 0, 0); + ts.tm_hour = getfield(L, "hour", 12, 0); + ts.tm_mday = getfield(L, "day", -1, 0); + ts.tm_mon = getfield(L, "month", -1, 1); + ts.tm_year = getfield(L, "year", -1, 1900); ts.tm_isdst = getboolfield(L, "isdst"); t = mktime(&ts); } - if (t != (time_t)(l_timet)t) - luaL_error(L, "time result cannot be represented in this Lua installation"); - else if (t == (time_t)(-1)) - lua_pushnil(L); - else - l_pushtime(L, t); + if (t != (time_t)(l_timet)t || t == (time_t)(-1)) + luaL_error(L, "time result cannot be represented in this installation"); + l_pushtime(L, t); return 1; } diff --git a/libs/lua-5.3.1/src/lparser.c b/libs/lua-5.3.2/src/lparser.c similarity index 99% rename from libs/lua-5.3.1/src/lparser.c rename to libs/lua-5.3.2/src/lparser.c index 9a54dfc..282a6b1 100644 --- a/libs/lua-5.3.1/src/lparser.c +++ b/libs/lua-5.3.2/src/lparser.c @@ -1,5 +1,5 @@ /* -** $Id: lparser.c,v 2.147 2014/12/27 20:31:43 roberto Exp $ +** $Id: lparser.c,v 2.149 2015/11/02 16:09:30 roberto Exp $ ** Lua Parser ** See Copyright Notice in lua.h */ @@ -760,7 +760,7 @@ static void parlist (LexState *ls) { } case TK_DOTS: { /* param -> '...' */ luaX_next(ls); - f->is_vararg = 1; + f->is_vararg = 2; /* declared vararg */ break; } default: luaX_syntaxerror(ls, " or '...' expected"); @@ -956,6 +956,7 @@ static void simpleexp (LexState *ls, expdesc *v) { FuncState *fs = ls->fs; check_condition(ls, fs->f->is_vararg, "cannot use '...' outside a vararg function"); + fs->f->is_vararg = 1; /* function actually uses vararg */ init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0)); break; } @@ -1610,7 +1611,7 @@ static void mainfunc (LexState *ls, FuncState *fs) { BlockCnt bl; expdesc v; open_func(ls, fs, &bl); - fs->f->is_vararg = 1; /* main function is always vararg */ + fs->f->is_vararg = 2; /* main function is always declared vararg */ init_exp(&v, VLOCAL, 0); /* create and... */ newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */ luaX_next(ls); /* read first token */ @@ -1626,10 +1627,10 @@ LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, FuncState funcstate; LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */ setclLvalue(L, L->top, cl); /* anchor it (to avoid being collected) */ - incr_top(L); + luaD_inctop(L); lexstate.h = luaH_new(L); /* create table for scanner */ sethvalue(L, L->top, lexstate.h); /* anchor it */ - incr_top(L); + luaD_inctop(L); funcstate.f = cl->p = luaF_newproto(L); funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ lua_assert(iswhite(funcstate.f)); /* do not need barrier here */ diff --git a/libs/lua-5.3.1/src/lparser.h b/libs/lua-5.3.2/src/lparser.h similarity index 100% rename from libs/lua-5.3.1/src/lparser.h rename to libs/lua-5.3.2/src/lparser.h diff --git a/libs/lua-5.3.1/src/lprefix.h b/libs/lua-5.3.2/src/lprefix.h similarity index 100% rename from libs/lua-5.3.1/src/lprefix.h rename to libs/lua-5.3.2/src/lprefix.h diff --git a/libs/lua-5.3.1/src/lstate.c b/libs/lua-5.3.2/src/lstate.c similarity index 92% rename from libs/lua-5.3.1/src/lstate.c rename to libs/lua-5.3.2/src/lstate.c index 12e51d2..9194ac3 100644 --- a/libs/lua-5.3.1/src/lstate.c +++ b/libs/lua-5.3.2/src/lstate.c @@ -1,5 +1,5 @@ /* -** $Id: lstate.c,v 2.128 2015/03/04 13:31:21 roberto Exp $ +** $Id: lstate.c,v 2.133 2015/11/13 12:16:51 roberto Exp $ ** Global State ** See Copyright Notice in lua.h */ @@ -76,7 +76,7 @@ typedef struct LG { */ #define addbuff(b,p,e) \ { size_t t = cast(size_t, e); \ - memcpy(buff + p, &t, sizeof(t)); p += sizeof(t); } + memcpy(b + p, &t, sizeof(t)); p += sizeof(t); } static unsigned int makeseed (lua_State *L) { char buff[4 * sizeof(size_t)]; @@ -93,10 +93,14 @@ static unsigned int makeseed (lua_State *L) { /* ** set GCdebt to a new value keeping the value (totalbytes + GCdebt) -** invariant +** invariant (and avoiding underflows in 'totalbytes') */ void luaE_setdebt (global_State *g, l_mem debt) { - g->totalbytes -= (debt - g->GCdebt); + l_mem tb = gettotalbytes(g); + lua_assert(tb > 0); + if (debt < tb - MAX_LMEM) + debt = tb - MAX_LMEM; /* will make 'totalbytes == MAX_LMEM' */ + g->totalbytes = tb - debt; g->GCdebt = debt; } @@ -107,6 +111,7 @@ CallInfo *luaE_extendCI (lua_State *L) { L->ci->next = ci; ci->previous = L->ci; ci->next = NULL; + L->nci++; return ci; } @@ -121,6 +126,7 @@ void luaE_freeCI (lua_State *L) { while ((ci = next) != NULL) { next = ci->next; luaM_free(L, ci); + L->nci--; } } @@ -130,13 +136,14 @@ void luaE_freeCI (lua_State *L) { */ void luaE_shrinkCI (lua_State *L) { CallInfo *ci = L->ci; - while (ci->next != NULL) { /* while there is 'next' */ - CallInfo *next2 = ci->next->next; /* next's next */ - if (next2 == NULL) break; - luaM_free(L, ci->next); /* remove next */ + CallInfo *next2; /* next's next */ + /* while there are two nexts */ + while (ci->next != NULL && (next2 = ci->next->next) != NULL) { + luaM_free(L, ci->next); /* free next */ + L->nci--; ci->next = next2; /* remove 'next' from the list */ next2->previous = ci; - ci = next2; + ci = next2; /* keep next's next */ } } @@ -166,6 +173,7 @@ static void freestack (lua_State *L) { return; /* stack not completely built yet */ L->ci = &L->base_ci; /* free the entire 'ci' list */ luaE_freeCI(L); + lua_assert(L->nci == 0); luaM_freearray(L, L->stack, L->stacksize); /* free stack array */ } @@ -214,6 +222,7 @@ static void preinit_thread (lua_State *L, global_State *g) { G(L) = g; L->stack = NULL; L->ci = NULL; + L->nci = 0; L->stacksize = 0; L->twups = L; /* thread has no upvalues */ L->errorJmp = NULL; @@ -237,7 +246,6 @@ static void close_state (lua_State *L) { if (g->version) /* closing a fully built state? */ luai_userstateclose(L); luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size); - luaZ_freebuffer(L, &g->buff); freestack(L); lua_assert(gettotalbytes(g) == sizeof(LG)); (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */ @@ -306,7 +314,6 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { g->strt.size = g->strt.nuse = 0; g->strt.hash = NULL; setnilvalue(&g->l_registry); - luaZ_initbuffer(L, &g->buff); g->panic = NULL; g->version = NULL; g->gcstate = GCSpause; diff --git a/libs/lua-5.3.1/src/lstate.h b/libs/lua-5.3.2/src/lstate.h similarity index 93% rename from libs/lua-5.3.1/src/lstate.h rename to libs/lua-5.3.2/src/lstate.h index eefc217..65c914d 100644 --- a/libs/lua-5.3.1/src/lstate.h +++ b/libs/lua-5.3.2/src/lstate.h @@ -1,5 +1,5 @@ /* -** $Id: lstate.h,v 2.122 2015/06/01 16:34:37 roberto Exp $ +** $Id: lstate.h,v 2.128 2015/11/13 12:16:51 roberto Exp $ ** Global State ** See Copyright Notice in lua.h */ @@ -89,8 +89,8 @@ typedef struct CallInfo { #define CIST_OAH (1<<0) /* original value of 'allowhook' */ #define CIST_LUA (1<<1) /* call is running a Lua function */ #define CIST_HOOKED (1<<2) /* call is running a debug hook */ -#define CIST_REENTRY (1<<3) /* call is running on same invocation of - luaV_execute of previous call */ +#define CIST_FRESH (1<<3) /* call is running on a fresh invocation + of luaV_execute */ #define CIST_YPCALL (1<<4) /* call is a yieldable protected call */ #define CIST_TAIL (1<<5) /* call was tail called */ #define CIST_HOOKYIELD (1<<6) /* last hook called yielded */ @@ -109,7 +109,7 @@ typedef struct CallInfo { typedef struct global_State { lua_Alloc frealloc; /* function to reallocate memory */ void *ud; /* auxiliary data to 'frealloc' */ - lu_mem totalbytes; /* number of bytes currently allocated - GCdebt */ + l_mem totalbytes; /* number of bytes currently allocated - GCdebt */ l_mem GCdebt; /* bytes allocated not yet compensated by the collector */ lu_mem GCmemtrav; /* memory traversed by the GC */ lu_mem GCestimate; /* an estimate of the non-garbage memory in use */ @@ -131,7 +131,6 @@ typedef struct global_State { GCObject *tobefnz; /* list of userdata to be GC */ GCObject *fixedgc; /* list of objects not to be collected */ struct lua_State *twups; /* list of threads with open upvalues */ - Mbuffer buff; /* temporary buffer for string concatenation */ unsigned int gcfinnum; /* number of finalizers to call in each GC step */ int gcpause; /* size of pause between successive GCs */ int gcstepmul; /* GC 'granularity' */ @@ -141,7 +140,7 @@ typedef struct global_State { TString *memerrmsg; /* memory-error message */ TString *tmname[TM_N]; /* array with tag-method names */ struct Table *mt[LUA_NUMTAGS]; /* metatables for basic types */ - TString *strcache[STRCACHE_SIZE][1]; /* cache for strings in API */ + TString *strcache[STRCACHE_N][STRCACHE_M]; /* cache for strings in API */ } global_State; @@ -150,6 +149,7 @@ typedef struct global_State { */ struct lua_State { CommonHeader; + unsigned short nci; /* number of items in 'ci' list */ lu_byte status; StkId top; /* first free slot in the stack */ global_State *l_G; @@ -212,7 +212,7 @@ union GCUnion { /* actual number of total bytes allocated */ -#define gettotalbytes(g) ((g)->totalbytes + (g)->GCdebt) +#define gettotalbytes(g) cast(lu_mem, (g)->totalbytes + (g)->GCdebt) LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt); LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); diff --git a/libs/lua-5.3.1/src/lstring.c b/libs/lua-5.3.2/src/lstring.c similarity index 73% rename from libs/lua-5.3.1/src/lstring.c rename to libs/lua-5.3.2/src/lstring.c index 5e0e3c4..9351766 100644 --- a/libs/lua-5.3.1/src/lstring.c +++ b/libs/lua-5.3.2/src/lstring.c @@ -1,5 +1,5 @@ /* -** $Id: lstring.c,v 2.49 2015/06/01 16:34:37 roberto Exp $ +** $Id: lstring.c,v 2.56 2015/11/23 11:32:51 roberto Exp $ ** String table (keeps all strings handled by Lua) ** See Copyright Notice in lua.h */ @@ -48,14 +48,23 @@ int luaS_eqlngstr (TString *a, TString *b) { unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) { unsigned int h = seed ^ cast(unsigned int, l); - size_t l1; size_t step = (l >> LUAI_HASHLIMIT) + 1; - for (l1 = l; l1 >= step; l1 -= step) - h = h ^ ((h<<5) + (h>>2) + cast_byte(str[l1 - 1])); + for (; l >= step; l -= step) + h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1])); return h; } +unsigned int luaS_hashlongstr (TString *ts) { + lua_assert(ts->tt == LUA_TLNGSTR); + if (ts->extra == 0) { /* no hash? */ + ts->hash = luaS_hash(getstr(ts), ts->u.lnglen, ts->hash); + ts->extra = 1; /* now it has its hash */ + } + return ts->hash; +} + + /* ** resizes the string table */ @@ -92,11 +101,12 @@ void luaS_resize (lua_State *L, int newsize) { ** a non-collectable string.) */ void luaS_clearcache (global_State *g) { - int i; - for (i = 0; i < STRCACHE_SIZE; i++) { - if (iswhite(g->strcache[i][0])) /* will entry be collected? */ - g->strcache[i][0] = g->memerrmsg; /* replace it with something fixed */ - } + int i, j; + for (i = 0; i < STRCACHE_N; i++) + for (j = 0; j < STRCACHE_M; j++) { + if (iswhite(g->strcache[i][j])) /* will entry be collected? */ + g->strcache[i][j] = g->memerrmsg; /* replace it with something fixed */ + } } @@ -105,13 +115,14 @@ void luaS_clearcache (global_State *g) { */ void luaS_init (lua_State *L) { global_State *g = G(L); - int i; + int i, j; luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */ /* pre-create memory-error message */ g->memerrmsg = luaS_newliteral(L, MEMERRMSG); luaC_fix(L, obj2gco(g->memerrmsg)); /* it should never be collected */ - for (i = 0; i < STRCACHE_SIZE; i++) /* fill cache with valid strings */ - g->strcache[i][0] = g->memerrmsg; + for (i = 0; i < STRCACHE_N; i++) /* fill cache with valid strings */ + for (j = 0; j < STRCACHE_M; j++) + g->strcache[i][j] = g->memerrmsg; } @@ -119,8 +130,7 @@ void luaS_init (lua_State *L) { /* ** creates a new string object */ -static TString *createstrobj (lua_State *L, const char *str, size_t l, - int tag, unsigned int h) { +static TString *createstrobj (lua_State *L, size_t l, int tag, unsigned int h) { TString *ts; GCObject *o; size_t totalsize; /* total size of TString object */ @@ -129,8 +139,14 @@ static TString *createstrobj (lua_State *L, const char *str, size_t l, ts = gco2ts(o); ts->hash = h; ts->extra = 0; - memcpy(getaddrstr(ts), str, l * sizeof(char)); - getaddrstr(ts)[l] = '\0'; /* ending 0 */ + getstr(ts)[l] = '\0'; /* ending 0 */ + return ts; +} + + +TString *luaS_createlngstrobj (lua_State *L, size_t l) { + TString *ts = createstrobj(L, l, LUA_TLNGSTR, G(L)->seed); + ts->u.lnglen = l; return ts; } @@ -153,6 +169,7 @@ static TString *internshrstr (lua_State *L, const char *str, size_t l) { global_State *g = G(L); unsigned int h = luaS_hash(str, l, g->seed); TString **list = &g->strt.hash[lmod(h, g->strt.size)]; + lua_assert(str != NULL); /* otherwise 'memcmp'/'memcpy' are undefined */ for (ts = *list; ts != NULL; ts = ts->u.hnext) { if (l == ts->shrlen && (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) { @@ -166,7 +183,8 @@ static TString *internshrstr (lua_State *L, const char *str, size_t l) { luaS_resize(L, g->strt.size * 2); list = &g->strt.hash[lmod(h, g->strt.size)]; /* recompute with new size */ } - ts = createstrobj(L, str, l, LUA_TSHRSTR, h); + ts = createstrobj(L, l, LUA_TSHRSTR, h); + memcpy(getstr(ts), str, l * sizeof(char)); ts->shrlen = cast_byte(l); ts->u.hnext = *list; *list = ts; @@ -183,10 +201,10 @@ TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { return internshrstr(L, str, l); else { TString *ts; - if (l + 1 > (MAX_SIZE - sizeof(TString))/sizeof(char)) + if (l >= (MAX_SIZE - sizeof(TString))/sizeof(char)) luaM_toobig(L); - ts = createstrobj(L, str, l, LUA_TLNGSTR, G(L)->seed); - ts->u.lnglen = l; + ts = luaS_createlngstrobj(L, l); + memcpy(getstr(ts), str, l * sizeof(char)); return ts; } } @@ -199,15 +217,19 @@ TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { ** check hits. */ TString *luaS_new (lua_State *L, const char *str) { - unsigned int i = point2uint(str) % STRCACHE_SIZE; /* hash */ + unsigned int i = point2uint(str) % STRCACHE_N; /* hash */ + int j; TString **p = G(L)->strcache[i]; - if (strcmp(str, getstr(p[0])) == 0) /* hit? */ - return p[0]; /* that it is */ - else { /* normal route */ - TString *s = luaS_newlstr(L, str, strlen(str)); - p[0] = s; - return s; + for (j = 0; j < STRCACHE_M; j++) { + if (strcmp(str, getstr(p[j])) == 0) /* hit? */ + return p[j]; /* that is it */ } + /* normal route */ + for (j = STRCACHE_M - 1; j > 0; j--) + p[j] = p[j - 1]; /* move out last element */ + /* new element is first in the list */ + p[0] = luaS_newlstr(L, str, strlen(str)); + return p[0]; } diff --git a/libs/lua-5.3.1/src/lstring.h b/libs/lua-5.3.2/src/lstring.h similarity index 87% rename from libs/lua-5.3.1/src/lstring.h rename to libs/lua-5.3.2/src/lstring.h index e746f5f..27efd20 100644 --- a/libs/lua-5.3.1/src/lstring.h +++ b/libs/lua-5.3.2/src/lstring.h @@ -1,5 +1,5 @@ /* -** $Id: lstring.h,v 1.59 2015/03/25 13:42:19 roberto Exp $ +** $Id: lstring.h,v 1.61 2015/11/03 15:36:01 roberto Exp $ ** String table (keep all strings handled by Lua) ** See Copyright Notice in lua.h */ @@ -34,6 +34,7 @@ LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed); +LUAI_FUNC unsigned int luaS_hashlongstr (TString *ts); LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b); LUAI_FUNC void luaS_resize (lua_State *L, int newsize); LUAI_FUNC void luaS_clearcache (global_State *g); @@ -42,6 +43,7 @@ LUAI_FUNC void luaS_remove (lua_State *L, TString *ts); LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s); LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); LUAI_FUNC TString *luaS_new (lua_State *L, const char *str); +LUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l); #endif diff --git a/libs/lua-5.3.1/src/lstrlib.c b/libs/lua-5.3.2/src/lstrlib.c similarity index 90% rename from libs/lua-5.3.1/src/lstrlib.c rename to libs/lua-5.3.2/src/lstrlib.c index 19c350d..fe30e34 100644 --- a/libs/lua-5.3.1/src/lstrlib.c +++ b/libs/lua-5.3.2/src/lstrlib.c @@ -1,5 +1,5 @@ /* -** $Id: lstrlib.c,v 1.229 2015/05/20 17:39:23 roberto Exp $ +** $Id: lstrlib.c,v 1.239 2015/11/25 16:28:17 roberto Exp $ ** Standard library for string operations and pattern-matching ** See Copyright Notice in lua.h */ @@ -41,8 +41,10 @@ ** Some sizes are better limited to fit in 'int', but must also fit in ** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.) */ +#define MAX_SIZET ((size_t)(~(size_t)0)) + #define MAXSIZE \ - (sizeof(size_t) < sizeof(int) ? (~(size_t)0) : (size_t)(INT_MAX)) + (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX)) @@ -208,11 +210,12 @@ static int str_dump (lua_State *L) { typedef struct MatchState { - int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ const char *src_init; /* init of source string */ const char *src_end; /* end ('\0') of source string */ const char *p_end; /* end ('\0') of pattern */ lua_State *L; + size_t nrep; /* limit to avoid non-linear complexity */ + int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ int level; /* total number of captures (finished or unfinished) */ struct { const char *init; @@ -231,6 +234,17 @@ static const char *match (MatchState *ms, const char *s, const char *p); #endif +/* +** parameters to control the maximum number of operators handled in +** a match (to avoid non-linear complexity). The maximum will be: +** (subject length) * A_REPS + B_REPS +*/ +#if !defined(A_REPS) +#define A_REPS 4 +#define B_REPS 100000 +#endif + + #define L_ESC '%' #define SPECIALS "^$*+?.([%-" @@ -488,6 +502,8 @@ static const char *match (MatchState *ms, const char *s, const char *p) { s = NULL; /* fail */ } else { /* matched once */ + if (ms->nrep-- == 0) + luaL_error(ms->L, "pattern too complex"); switch (*ep) { /* handle optional suffix */ case '?': { /* optional */ const char *res; @@ -584,6 +600,26 @@ static int nospecials (const char *p, size_t l) { } +static void prepstate (MatchState *ms, lua_State *L, + const char *s, size_t ls, const char *p, size_t lp) { + ms->L = L; + ms->matchdepth = MAXCCALLS; + ms->src_init = s; + ms->src_end = s + ls; + ms->p_end = p + lp; + if (ls < (MAX_SIZET - B_REPS) / A_REPS) + ms->nrep = A_REPS * ls + B_REPS; + else /* overflow (very long subject) */ + ms->nrep = MAX_SIZET; /* no limit */ +} + + +static void reprepstate (MatchState *ms) { + ms->level = 0; + lua_assert(ms->matchdepth == MAXCCALLS); +} + + static int str_find_aux (lua_State *L, int find) { size_t ls, lp; const char *s = luaL_checklstring(L, 1, &ls); @@ -611,15 +647,10 @@ static int str_find_aux (lua_State *L, int find) { if (anchor) { p++; lp--; /* skip anchor character */ } - ms.L = L; - ms.matchdepth = MAXCCALLS; - ms.src_init = s; - ms.src_end = s + ls; - ms.p_end = p + lp; + prepstate(&ms, L, s, ls, p, lp); do { const char *res; - ms.level = 0; - lua_assert(ms.matchdepth == MAXCCALLS); + reprepstate(&ms); if ((res=match(&ms, s1, p)) != NULL) { if (find) { lua_pushinteger(L, (s1 - s) + 1); /* start */ @@ -646,29 +677,26 @@ static int str_match (lua_State *L) { } +/* state for 'gmatch' */ +typedef struct GMatchState { + const char *src; /* current position */ + const char *p; /* pattern */ + MatchState ms; /* match state */ +} GMatchState; + + static int gmatch_aux (lua_State *L) { - MatchState ms; - size_t ls, lp; - const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls); - const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp); + GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3)); const char *src; - ms.L = L; - ms.matchdepth = MAXCCALLS; - ms.src_init = s; - ms.src_end = s+ls; - ms.p_end = p + lp; - for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3)); - src <= ms.src_end; - src++) { + for (src = gm->src; src <= gm->ms.src_end; src++) { const char *e; - ms.level = 0; - lua_assert(ms.matchdepth == MAXCCALLS); - if ((e = match(&ms, src, p)) != NULL) { - lua_Integer newstart = e-s; - if (e == src) newstart++; /* empty match? go at least one position */ - lua_pushinteger(L, newstart); - lua_replace(L, lua_upvalueindex(3)); - return push_captures(&ms, src, e); + reprepstate(&gm->ms); + if ((e = match(&gm->ms, src, gm->p)) != NULL) { + if (e == src) /* empty match? */ + gm->src =src + 1; /* go at least one position */ + else + gm->src = e; + return push_captures(&gm->ms, src, e); } } return 0; /* not found */ @@ -676,10 +704,14 @@ static int gmatch_aux (lua_State *L) { static int gmatch (lua_State *L) { - luaL_checkstring(L, 1); - luaL_checkstring(L, 2); - lua_settop(L, 2); - lua_pushinteger(L, 0); + size_t ls, lp; + const char *s = luaL_checklstring(L, 1, &ls); + const char *p = luaL_checklstring(L, 2, &lp); + GMatchState *gm; + lua_settop(L, 2); /* keep them on closure to avoid being collected */ + gm = (GMatchState *)lua_newuserdata(L, sizeof(GMatchState)); + prepstate(&gm->ms, L, s, ls, p, lp); + gm->src = s; gm->p = p; lua_pushcclosure(L, gmatch_aux, 3); return 1; } @@ -761,17 +793,11 @@ static int str_gsub (lua_State *L) { if (anchor) { p++; lp--; /* skip anchor character */ } - ms.L = L; - ms.matchdepth = MAXCCALLS; - ms.src_init = src; - ms.src_end = src+srcl; - ms.p_end = p + lp; + prepstate(&ms, L, src, srcl, p, lp); while (n < max_s) { const char *e; - ms.level = 0; - lua_assert(ms.matchdepth == MAXCCALLS); - e = match(&ms, src, p); - if (e) { + reprepstate(&ms); + if ((e = match(&ms, src, p)) != NULL) { n++; add_value(&ms, &b, src, e, tr); } @@ -830,13 +856,12 @@ static lua_Number adddigit (char *buff, int n, lua_Number x) { } -static int num2straux (char *buff, lua_Number x) { +static int num2straux (char *buff, int sz, lua_Number x) { if (x != x || x == HUGE_VAL || x == -HUGE_VAL) /* inf or NaN? */ - return sprintf(buff, LUA_NUMBER_FMT, x); /* equal to '%g' */ + return l_sprintf(buff, sz, LUA_NUMBER_FMT, x); /* equal to '%g' */ else if (x == 0) { /* can be -0... */ - sprintf(buff, LUA_NUMBER_FMT, x); - strcat(buff, "x0p+0"); /* reuses '0/-0' from 'sprintf'... */ - return strlen(buff); + /* create "0" or "-0" followed by exponent */ + return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", x); } else { int e; @@ -855,15 +880,16 @@ static int num2straux (char *buff, lua_Number x) { m = adddigit(buff, n++, m * 16); } while (m > 0); } - n += sprintf(buff + n, "p%+d", e); /* add exponent */ + n += l_sprintf(buff + n, sz - n, "p%+d", e); /* add exponent */ + lua_assert(n < sz); return n; } } -static int lua_number2strx (lua_State *L, char *buff, const char *fmt, - lua_Number x) { - int n = num2straux(buff, x); +static int lua_number2strx (lua_State *L, char *buff, int sz, + const char *fmt, lua_Number x) { + int n = num2straux(buff, sz, x); if (fmt[SIZELENMOD] == 'A') { int i; for (i = 0; i < n; i++) @@ -879,10 +905,12 @@ static int lua_number2strx (lua_State *L, char *buff, const char *fmt, /* ** Maximum size of each formatted item. This maximum size is produced -** by format('%.99f', minfloat), and is equal to 99 + 2 ('-' and '.') + -** number of decimal digits to represent minfloat. +** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.', +** and '\0') + number of decimal digits to represent maxfloat (which +** is maximum exponent + 1). (99+3+1 then rounded to 120 for "extra +** expenses", such as locale-dependent stuff) */ -#define MAX_ITEM (120 + l_mathlim(MAX_10_EXP)) +#define MAX_ITEM (120 + l_mathlim(MAX_10_EXP)) /* valid flags in a format specification */ @@ -906,9 +934,9 @@ static void addquoted (lua_State *L, luaL_Buffer *b, int arg) { else if (*s == '\0' || iscntrl(uchar(*s))) { char buff[10]; if (!isdigit(uchar(*(s+1)))) - sprintf(buff, "\\%d", (int)uchar(*s)); + l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s)); else - sprintf(buff, "\\%03d", (int)uchar(*s)); + l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s)); luaL_addstring(b, buff); } else @@ -975,24 +1003,25 @@ static int str_format (lua_State *L) { strfrmt = scanformat(L, strfrmt, form); switch (*strfrmt++) { case 'c': { - nb = sprintf(buff, form, (int)luaL_checkinteger(L, arg)); + nb = l_sprintf(buff, MAX_ITEM, form, (int)luaL_checkinteger(L, arg)); break; } case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': { lua_Integer n = luaL_checkinteger(L, arg); addlenmod(form, LUA_INTEGER_FRMLEN); - nb = sprintf(buff, form, n); + nb = l_sprintf(buff, MAX_ITEM, form, n); break; } case 'a': case 'A': addlenmod(form, LUA_NUMBER_FRMLEN); - nb = lua_number2strx(L, buff, form, luaL_checknumber(L, arg)); + nb = lua_number2strx(L, buff, MAX_ITEM, form, + luaL_checknumber(L, arg)); break; case 'e': case 'E': case 'f': case 'g': case 'G': { addlenmod(form, LUA_NUMBER_FRMLEN); - nb = sprintf(buff, form, luaL_checknumber(L, arg)); + nb = l_sprintf(buff, MAX_ITEM, form, luaL_checknumber(L, arg)); break; } case 'q': { @@ -1002,14 +1031,18 @@ static int str_format (lua_State *L) { case 's': { size_t l; const char *s = luaL_tolstring(L, arg, &l); - if (!strchr(form, '.') && l >= 100) { - /* no precision and string is too long to be formatted; - keep original string */ - luaL_addvalue(&b); - } + if (form[2] == '\0') /* no modifiers? */ + luaL_addvalue(&b); /* keep entire string */ else { - nb = sprintf(buff, form, s); - lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ + luaL_argcheck(L, l == strlen(s), arg, "string contains zeros"); + if (!strchr(form, '.') && l >= 100) { + /* no precision and string is too long to be formatted */ + luaL_addvalue(&b); /* keep entire string */ + } + else { /* format the string into 'buff' */ + nb = l_sprintf(buff, MAX_ITEM, form, s); + lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ + } } break; } @@ -1018,6 +1051,7 @@ static int str_format (lua_State *L) { *(strfrmt - 1)); } } + lua_assert(nb < MAX_ITEM); luaL_addsize(&b, nb); } } @@ -1309,8 +1343,13 @@ static int str_pack (lua_State *L) { case Kchar: { /* fixed-size string */ size_t len; const char *s = luaL_checklstring(L, arg, &len); - luaL_argcheck(L, len == (size_t)size, arg, "wrong length"); - luaL_addlstring(&b, s, size); + if ((size_t)size <= len) /* string larger than (or equal to) needed? */ + luaL_addlstring(&b, s, size); /* truncate string to asked size */ + else { /* string smaller than needed */ + luaL_addlstring(&b, s, len); /* add it all */ + while (len++ < (size_t)size) /* pad extra space */ + luaL_addchar(&b, LUA_PACKPADBYTE); + } break; } case Kstring: { /* strings with length count */ @@ -1360,7 +1399,7 @@ static int str_packsize (lua_State *L) { case Kstring: /* strings with length count */ case Kzstr: /* zero-terminated string */ luaL_argerror(L, 1, "variable-length format"); - break; + /* call never return, but to avoid warnings: *//* FALLTHROUGH */ default: break; } } diff --git a/libs/lua-5.3.1/src/ltable.c b/libs/lua-5.3.2/src/ltable.c similarity index 93% rename from libs/lua-5.3.1/src/ltable.c rename to libs/lua-5.3.2/src/ltable.c index 04f2a34..7e15b71 100644 --- a/libs/lua-5.3.1/src/ltable.c +++ b/libs/lua-5.3.2/src/ltable.c @@ -1,5 +1,5 @@ /* -** $Id: ltable.c,v 2.111 2015/06/09 14:21:13 roberto Exp $ +** $Id: ltable.c,v 2.117 2015/11/19 19:16:22 roberto Exp $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ @@ -85,7 +85,7 @@ static const Node dummynode_ = { /* ** Hash for floating-point numbers. ** The main computation should be just -** n = frepx(n, &i); return (n * INT_MAX) + i +** n = frexp(n, &i); return (n * INT_MAX) + i ** but there are some numerical subtleties. ** In a two-complement representation, INT_MAX does not has an exact ** representation as a float, but INT_MIN does; because the absolute @@ -101,7 +101,7 @@ static int l_hashfloat (lua_Number n) { lua_Integer ni; n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN); if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */ - lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == HUGE_VAL); + lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL)); return 0; } else { /* normal case */ @@ -124,14 +124,8 @@ static Node *mainposition (const Table *t, const TValue *key) { return hashmod(t, l_hashfloat(fltvalue(key))); case LUA_TSHRSTR: return hashstr(t, tsvalue(key)); - case LUA_TLNGSTR: { - TString *s = tsvalue(key); - if (s->extra == 0) { /* no hash? */ - s->hash = luaS_hash(getstr(s), s->u.lnglen, s->hash); - s->extra = 1; /* now it has its hash */ - } - return hashstr(t, tsvalue(key)); - } + case LUA_TLNGSTR: + return hashpow2(t, luaS_hashlongstr(tsvalue(key))); case LUA_TBOOLEAN: return hashboolean(t, bvalue(key)); case LUA_TLIGHTUSERDATA: @@ -139,6 +133,7 @@ static Node *mainposition (const Table *t, const TValue *key) { case LUA_TLCF: return hashpointer(t, fvalue(key)); default: + lua_assert(!ttisdeadkey(key)); return hashpointer(t, gcvalue(key)); } } @@ -463,7 +458,7 @@ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) { Node *f = getfreepos(t); /* get a free place */ if (f == NULL) { /* cannot find a free place? */ rehash(L, t, key); /* grow table */ - /* whatever called 'newkey' takes care of TM cache and GC barrier */ + /* whatever called 'newkey' takes care of TM cache */ return luaH_set(L, t, key); /* insert key into grown table */ } lua_assert(!isdummy(f)); @@ -501,7 +496,7 @@ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) { */ const TValue *luaH_getint (Table *t, lua_Integer key) { /* (1 <= key && key <= t->sizearray) */ - if (l_castS2U(key - 1) < t->sizearray) + if (l_castS2U(key) - 1 < t->sizearray) return &t->array[key - 1]; else { Node *n = hashint(t, key); @@ -513,7 +508,7 @@ const TValue *luaH_getint (Table *t, lua_Integer key) { if (nx == 0) break; n += nx; } - }; + } return luaO_nilobject; } } @@ -522,7 +517,7 @@ const TValue *luaH_getint (Table *t, lua_Integer key) { /* ** search function for short strings */ -const TValue *luaH_getstr (Table *t, TString *key) { +const TValue *luaH_getshortstr (Table *t, TString *key) { Node *n = hashstr(t, key); lua_assert(key->tt == LUA_TSHRSTR); for (;;) { /* check whether 'key' is somewhere in the chain */ @@ -531,11 +526,41 @@ const TValue *luaH_getstr (Table *t, TString *key) { return gval(n); /* that's it */ else { int nx = gnext(n); - if (nx == 0) break; + if (nx == 0) + return luaO_nilobject; /* not found */ n += nx; } - }; - return luaO_nilobject; + } +} + + +/* +** "Generic" get version. (Not that generic: not valid for integers, +** which may be in array part, nor for floats with integral values.) +*/ +static const TValue *getgeneric (Table *t, const TValue *key) { + Node *n = mainposition(t, key); + for (;;) { /* check whether 'key' is somewhere in the chain */ + if (luaV_rawequalobj(gkey(n), key)) + return gval(n); /* that's it */ + else { + int nx = gnext(n); + if (nx == 0) + return luaO_nilobject; /* not found */ + n += nx; + } + } +} + + +const TValue *luaH_getstr (Table *t, TString *key) { + if (key->tt == LUA_TSHRSTR) + return luaH_getshortstr(t, key); + else { /* for long strings, use generic case */ + TValue ko; + setsvalue(cast(lua_State *, NULL), &ko, key); + return getgeneric(t, &ko); + } } @@ -544,7 +569,7 @@ const TValue *luaH_getstr (Table *t, TString *key) { */ const TValue *luaH_get (Table *t, const TValue *key) { switch (ttype(key)) { - case LUA_TSHRSTR: return luaH_getstr(t, tsvalue(key)); + case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key)); case LUA_TNUMINT: return luaH_getint(t, ivalue(key)); case LUA_TNIL: return luaO_nilobject; case LUA_TNUMFLT: { @@ -553,19 +578,8 @@ const TValue *luaH_get (Table *t, const TValue *key) { return luaH_getint(t, k); /* use specialized version */ /* else... */ } /* FALLTHROUGH */ - default: { - Node *n = mainposition(t, key); - for (;;) { /* check whether 'key' is somewhere in the chain */ - if (luaV_rawequalobj(gkey(n), key)) - return gval(n); /* that's it */ - else { - int nx = gnext(n); - if (nx == 0) break; - n += nx; - } - }; - return luaO_nilobject; - } + default: + return getgeneric(t, key); } } diff --git a/libs/lua-5.3.1/src/ltable.h b/libs/lua-5.3.2/src/ltable.h similarity index 86% rename from libs/lua-5.3.1/src/ltable.h rename to libs/lua-5.3.2/src/ltable.h index 53d2551..213cc13 100644 --- a/libs/lua-5.3.1/src/ltable.h +++ b/libs/lua-5.3.2/src/ltable.h @@ -1,5 +1,5 @@ /* -** $Id: ltable.h,v 2.20 2014/09/04 18:15:29 roberto Exp $ +** $Id: ltable.h,v 2.21 2015/11/03 15:47:30 roberto Exp $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ @@ -18,6 +18,10 @@ /* 'const' to avoid wrong writings that can mess up field 'next' */ #define gkey(n) cast(const TValue*, (&(n)->i_key.tvk)) +/* +** writable version of 'gkey'; allows updates to individual fields, +** but not to the whole (which has incompatible type) +*/ #define wgkey(n) (&(n)->i_key.nk) #define invalidateTMcache(t) ((t)->flags = 0) @@ -31,6 +35,7 @@ LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key); LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value); +LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key); LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key); diff --git a/libs/lua-5.3.2/src/ltablib.c b/libs/lua-5.3.2/src/ltablib.c new file mode 100644 index 0000000..b3c9a7c --- /dev/null +++ b/libs/lua-5.3.2/src/ltablib.c @@ -0,0 +1,449 @@ +/* +** $Id: ltablib.c,v 1.90 2015/11/25 12:48:57 roberto Exp $ +** Library for Table Manipulation +** See Copyright Notice in lua.h +*/ + +#define ltablib_c +#define LUA_LIB + +#include "lprefix.h" + + +#include +#include +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "lualib.h" + + +/* +** Operations that an object must define to mimic a table +** (some functions only need some of them) +*/ +#define TAB_R 1 /* read */ +#define TAB_W 2 /* write */ +#define TAB_L 4 /* length */ +#define TAB_RW (TAB_R | TAB_W) /* read/write */ + + +#define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n)) + + +static int checkfield (lua_State *L, const char *key, int n) { + lua_pushstring(L, key); + return (lua_rawget(L, -n) != LUA_TNIL); +} + + +/* +** Check that 'arg' either is a table or can behave like one (that is, +** has a metatable with the required metamethods) +*/ +static void checktab (lua_State *L, int arg, int what) { + if (lua_type(L, arg) != LUA_TTABLE) { /* is it not a table? */ + int n = 1; /* number of elements to pop */ + if (lua_getmetatable(L, arg) && /* must have metatable */ + (!(what & TAB_R) || checkfield(L, "__index", ++n)) && + (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) && + (!(what & TAB_L) || checkfield(L, "__len", ++n))) { + lua_pop(L, n); /* pop metatable and tested metamethods */ + } + else + luaL_argerror(L, arg, "table expected"); /* force an error */ + } +} + + +#if defined(LUA_COMPAT_MAXN) +static int maxn (lua_State *L) { + lua_Number max = 0; + luaL_checktype(L, 1, LUA_TTABLE); + lua_pushnil(L); /* first key */ + while (lua_next(L, 1)) { + lua_pop(L, 1); /* remove value */ + if (lua_type(L, -1) == LUA_TNUMBER) { + lua_Number v = lua_tonumber(L, -1); + if (v > max) max = v; + } + } + lua_pushnumber(L, max); + return 1; +} +#endif + + +static int tinsert (lua_State *L) { + lua_Integer e = aux_getn(L, 1, TAB_RW) + 1; /* first empty element */ + lua_Integer pos; /* where to insert new element */ + switch (lua_gettop(L)) { + case 2: { /* called with only 2 arguments */ + pos = e; /* insert new element at the end */ + break; + } + case 3: { + lua_Integer i; + pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */ + luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds"); + for (i = e; i > pos; i--) { /* move up elements */ + lua_geti(L, 1, i - 1); + lua_seti(L, 1, i); /* t[i] = t[i - 1] */ + } + break; + } + default: { + return luaL_error(L, "wrong number of arguments to 'insert'"); + } + } + lua_seti(L, 1, pos); /* t[pos] = v */ + return 0; +} + + +static int tremove (lua_State *L) { + lua_Integer size = aux_getn(L, 1, TAB_RW); + lua_Integer pos = luaL_optinteger(L, 2, size); + if (pos != size) /* validate 'pos' if given */ + luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds"); + lua_geti(L, 1, pos); /* result = t[pos] */ + for ( ; pos < size; pos++) { + lua_geti(L, 1, pos + 1); + lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */ + } + lua_pushnil(L); + lua_seti(L, 1, pos); /* t[pos] = nil */ + return 1; +} + + +/* +** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever +** possible, copy in increasing order, which is better for rehashing. +** "possible" means destination after original range, or smaller +** than origin, or copying to another table. +*/ +static int tmove (lua_State *L) { + lua_Integer f = luaL_checkinteger(L, 2); + lua_Integer e = luaL_checkinteger(L, 3); + lua_Integer t = luaL_checkinteger(L, 4); + int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */ + checktab(L, 1, TAB_R); + checktab(L, tt, TAB_W); + if (e >= f) { /* otherwise, nothing to move */ + lua_Integer n, i; + luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3, + "too many elements to move"); + n = e - f + 1; /* number of elements to move */ + luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4, + "destination wrap around"); + if (t > e || t <= f || tt != 1) { + for (i = 0; i < n; i++) { + lua_geti(L, 1, f + i); + lua_seti(L, tt, t + i); + } + } + else { + for (i = n - 1; i >= 0; i--) { + lua_geti(L, 1, f + i); + lua_seti(L, tt, t + i); + } + } + } + lua_pushvalue(L, tt); /* return "to table" */ + return 1; +} + + +static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) { + lua_geti(L, 1, i); + if (!lua_isstring(L, -1)) + luaL_error(L, "invalid value (%s) at index %d in table for 'concat'", + luaL_typename(L, -1), i); + luaL_addvalue(b); +} + + +static int tconcat (lua_State *L) { + luaL_Buffer b; + lua_Integer last = aux_getn(L, 1, TAB_R); + size_t lsep; + const char *sep = luaL_optlstring(L, 2, "", &lsep); + lua_Integer i = luaL_optinteger(L, 3, 1); + last = luaL_opt(L, luaL_checkinteger, 4, last); + luaL_buffinit(L, &b); + for (; i < last; i++) { + addfield(L, &b, i); + luaL_addlstring(&b, sep, lsep); + } + if (i == last) /* add last value (if interval was not empty) */ + addfield(L, &b, i); + luaL_pushresult(&b); + return 1; +} + + +/* +** {====================================================== +** Pack/unpack +** ======================================================= +*/ + +static int pack (lua_State *L) { + int i; + int n = lua_gettop(L); /* number of elements to pack */ + lua_createtable(L, n, 1); /* create result table */ + lua_insert(L, 1); /* put it at index 1 */ + for (i = n; i >= 1; i--) /* assign elements */ + lua_seti(L, 1, i); + lua_pushinteger(L, n); + lua_setfield(L, 1, "n"); /* t.n = number of elements */ + return 1; /* return table */ +} + + +static int unpack (lua_State *L) { + lua_Unsigned n; + lua_Integer i = luaL_optinteger(L, 2, 1); + lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1)); + if (i > e) return 0; /* empty range */ + n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */ + if (n >= (unsigned int)INT_MAX || !lua_checkstack(L, (int)(++n))) + return luaL_error(L, "too many results to unpack"); + for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */ + lua_geti(L, 1, i); + } + lua_geti(L, 1, e); /* push last element */ + return (int)n; +} + +/* }====================================================== */ + + + +/* +** {====================================================== +** Quicksort +** (based on 'Algorithms in MODULA-3', Robert Sedgewick; +** Addison-Wesley, 1993.) +** ======================================================= +*/ + + +/* +** Produce a "random" 'unsigned int' to randomize pivot choice. This +** macro is used only when 'sort' detects a big imbalance in the result +** of a partition. (If you don't want/need this "randomness", ~0 is a +** good choice.) +*/ +#if !defined(l_randomizePivot) /* { */ + +#include + +/* size of 'e' measured in number of 'unsigned int's */ +#define sof(e) (sizeof(e) / sizeof(unsigned int)) + +/* +** Use 'time' and 'clock' as sources of "randomness". Because we don't +** know the types 'clock_t' and 'time_t', we cannot cast them to +** anything without risking overflows. A safe way to use their values +** is to copy them to an array of a known type and use the array values. +*/ +static unsigned int l_randomizePivot (void) { + clock_t c = clock(); + time_t t = time(NULL); + unsigned int buff[sof(c) + sof(t)]; + unsigned int i, rnd = 0; + memcpy(buff, &c, sof(c) * sizeof(unsigned int)); + memcpy(buff + sof(c), &t, sof(t) * sizeof(unsigned int)); + for (i = 0; i < sof(buff); i++) + rnd += buff[i]; + return rnd; +} + +#endif /* } */ + + +/* arrays larger than 'RANLIMIT' may use randomized pivots */ +#define RANLIMIT 100u + + +static void set2 (lua_State *L, unsigned int i, unsigned int j) { + lua_seti(L, 1, i); + lua_seti(L, 1, j); +} + + +/* +** Return true iff value at stack index 'a' is less than the value at +** index 'b' (according to the order of the sort). +*/ +static int sort_comp (lua_State *L, int a, int b) { + if (lua_isnil(L, 2)) /* no function? */ + return lua_compare(L, a, b, LUA_OPLT); /* a < b */ + else { /* function */ + int res; + lua_pushvalue(L, 2); /* push function */ + lua_pushvalue(L, a-1); /* -1 to compensate function */ + lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */ + lua_call(L, 2, 1); /* call function */ + res = lua_toboolean(L, -1); /* get result */ + lua_pop(L, 1); /* pop result */ + return res; + } +} + + +/* +** Does the partition: Pivot P is at the top of the stack. +** precondition: a[lo] <= P == a[up-1] <= a[up], +** so it only needs to do the partition from lo + 1 to up - 2. +** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up] +** returns 'i'. +*/ +static unsigned int partition (lua_State *L, unsigned int lo, + unsigned int up) { + unsigned int i = lo; /* will be incremented before first use */ + unsigned int j = up - 1; /* will be decremented before first use */ + /* loop invariant: a[lo .. i] <= P <= a[j .. up] */ + for (;;) { + /* next loop: repeat ++i while a[i] < P */ + while (lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) { + if (i == up - 1) /* a[i] < P but a[up - 1] == P ?? */ + luaL_error(L, "invalid order function for sorting"); + lua_pop(L, 1); /* remove a[i] */ + } + /* after the loop, a[i] >= P and a[lo .. i - 1] < P */ + /* next loop: repeat --j while P < a[j] */ + while (lua_geti(L, 1, --j), sort_comp(L, -3, -1)) { + if (j < i) /* j < i but a[j] > P ?? */ + luaL_error(L, "invalid order function for sorting"); + lua_pop(L, 1); /* remove a[j] */ + } + /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */ + if (j < i) { /* no elements out of place? */ + /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */ + lua_pop(L, 1); /* pop a[j] */ + /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */ + set2(L, up - 1, i); + return i; + } + /* otherwise, swap a[i] - a[j] to restore invariant and repeat */ + set2(L, i, j); + } +} + + +/* +** Choose an element in the middle (2nd-3th quarters) of [lo,up] +** "randomized" by 'rnd' +*/ +static unsigned int choosePivot (unsigned int lo, unsigned int up, + unsigned int rnd) { + unsigned int r4 = (unsigned int)(up - lo) / 4u; /* range/4 */ + unsigned int p = rnd % (r4 * 2) + (lo + r4); + lua_assert(lo + r4 <= p && p <= up - r4); + return p; +} + + +/* +** QuickSort algorithm (recursive function) +*/ +static void auxsort (lua_State *L, unsigned int lo, unsigned int up, + unsigned int rnd) { + while (lo < up) { /* loop for tail recursion */ + unsigned int p; /* Pivot index */ + unsigned int n; /* to be used later */ + /* sort elements 'lo', 'p', and 'up' */ + lua_geti(L, 1, lo); + lua_geti(L, 1, up); + if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */ + set2(L, lo, up); /* swap a[lo] - a[up] */ + else + lua_pop(L, 2); /* remove both values */ + if (up - lo == 1) /* only 2 elements? */ + return; /* already sorted */ + if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */ + p = (lo + up)/2; /* middle element is a good pivot */ + else /* for larger intervals, it is worth a random pivot */ + p = choosePivot(lo, up, rnd); + lua_geti(L, 1, p); + lua_geti(L, 1, lo); + if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */ + set2(L, p, lo); /* swap a[p] - a[lo] */ + else { + lua_pop(L, 1); /* remove a[lo] */ + lua_geti(L, 1, up); + if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */ + set2(L, p, up); /* swap a[up] - a[p] */ + else + lua_pop(L, 2); + } + if (up - lo == 2) /* only 3 elements? */ + return; /* already sorted */ + lua_geti(L, 1, p); /* get middle element (Pivot) */ + lua_pushvalue(L, -1); /* push Pivot */ + lua_geti(L, 1, up - 1); /* push a[up - 1] */ + set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */ + p = partition(L, lo, up); + /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */ + if (p - lo < up - p) { /* lower interval is smaller? */ + auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */ + n = p - lo; /* size of smaller interval */ + lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */ + } + else { + auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */ + n = up - p; /* size of smaller interval */ + up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */ + } + if ((up - lo) / 128u > n) /* partition too imbalanced? */ + rnd = l_randomizePivot(); /* try a new randomization */ + } /* tail call auxsort(L, lo, up, rnd) */ +} + + +static int sort (lua_State *L) { + lua_Integer n = aux_getn(L, 1, TAB_RW); + if (n > 1) { /* non-trivial interval? */ + luaL_argcheck(L, n < INT_MAX, 1, "array too big"); + luaL_checkstack(L, 40, ""); /* assume array is smaller than 2^40 */ + if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */ + luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */ + lua_settop(L, 2); /* make sure there are two arguments */ + auxsort(L, 1, (unsigned int)n, 0u); + } + return 0; +} + +/* }====================================================== */ + + +static const luaL_Reg tab_funcs[] = { + {"concat", tconcat}, +#if defined(LUA_COMPAT_MAXN) + {"maxn", maxn}, +#endif + {"insert", tinsert}, + {"pack", pack}, + {"unpack", unpack}, + {"remove", tremove}, + {"move", tmove}, + {"sort", sort}, + {NULL, NULL} +}; + + +LUAMOD_API int luaopen_table (lua_State *L) { + luaL_newlib(L, tab_funcs); +#if defined(LUA_COMPAT_UNPACK) + /* _G.unpack = table.unpack */ + lua_getfield(L, -1, "unpack"); + lua_setglobal(L, "unpack"); +#endif + return 1; +} + diff --git a/libs/lua-5.3.1/src/ltm.c b/libs/lua-5.3.2/src/ltm.c similarity index 88% rename from libs/lua-5.3.1/src/ltm.c rename to libs/lua-5.3.2/src/ltm.c index c38e5c3..22b4df3 100644 --- a/libs/lua-5.3.1/src/ltm.c +++ b/libs/lua-5.3.2/src/ltm.c @@ -1,5 +1,5 @@ /* -** $Id: ltm.c,v 2.34 2015/03/30 15:42:27 roberto Exp $ +** $Id: ltm.c,v 2.36 2015/11/03 15:47:30 roberto Exp $ ** Tag methods ** See Copyright Notice in lua.h */ @@ -57,7 +57,7 @@ void luaT_init (lua_State *L) { ** tag methods */ const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { - const TValue *tm = luaH_getstr(events, ename); + const TValue *tm = luaH_getshortstr(events, ename); lua_assert(event <= TM_EQ); if (ttisnil(tm)) { /* no tag method? */ events->flags |= cast_byte(1u<mt[ttnov(o)]; } - return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject); + return (mt ? luaH_getshortstr(mt, G(L)->tmname[event]) : luaO_nilobject); } void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, const TValue *p2, TValue *p3, int hasres) { ptrdiff_t result = savestack(L, p3); - setobj2s(L, L->top++, f); /* push function (assume EXTRA_STACK) */ - setobj2s(L, L->top++, p1); /* 1st argument */ - setobj2s(L, L->top++, p2); /* 2nd argument */ + StkId func = L->top; + setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ + setobj2s(L, func + 1, p1); /* 1st argument */ + setobj2s(L, func + 2, p2); /* 2nd argument */ + L->top += 3; if (!hasres) /* no result? 'p3' is third argument */ setobj2s(L, L->top++, p3); /* 3rd argument */ /* metamethod may yield only when called from Lua code */ - luaD_call(L, L->top - (4 - hasres), hasres, isLua(L->ci)); + if (isLua(L->ci)) + luaD_call(L, func, hasres); + else + luaD_callnoyield(L, func, hasres); if (hasres) { /* if has result, move it to its place */ p3 = restorestack(L, result); setobjs2s(L, p3, --L->top); diff --git a/libs/lua-5.3.1/src/ltm.h b/libs/lua-5.3.2/src/ltm.h similarity index 100% rename from libs/lua-5.3.1/src/ltm.h rename to libs/lua-5.3.2/src/ltm.h diff --git a/libs/lua-5.3.1/src/lua.dontcompile b/libs/lua-5.3.2/src/lua.dontcompile similarity index 96% rename from libs/lua-5.3.1/src/lua.dontcompile rename to libs/lua-5.3.2/src/lua.dontcompile index 7a47582..545d23d 100644 --- a/libs/lua-5.3.1/src/lua.dontcompile +++ b/libs/lua-5.3.2/src/lua.dontcompile @@ -1,5 +1,5 @@ /* -** $Id: lua.c,v 1.225 2015/03/30 15:42:59 roberto Exp $ +** $Id: lua.c,v 1.226 2015/08/14 19:11:20 roberto Exp $ ** Lua stand-alone interpreter ** See Copyright Notice in lua.h */ @@ -324,24 +324,20 @@ static int pushline (lua_State *L, int firstline) { /* -** Try to compile line on the stack as 'return '; on return, stack +** Try to compile line on the stack as 'return ;'; on return, stack ** has either compiled chunk or original line (if compilation failed). */ static int addreturn (lua_State *L) { - int status; - size_t len; const char *line; - lua_pushliteral(L, "return "); - lua_pushvalue(L, -2); /* duplicate line */ - lua_concat(L, 2); /* new line is "return ..." */ - line = lua_tolstring(L, -1, &len); - if ((status = luaL_loadbuffer(L, line, len, "=stdin")) == LUA_OK) { - lua_remove(L, -3); /* remove original line */ - line += sizeof("return")/sizeof(char); /* remove 'return' for history */ + const char *line = lua_tostring(L, -1); /* original line */ + const char *retline = lua_pushfstring(L, "return %s;", line); + int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin"); + if (status == LUA_OK) { + lua_remove(L, -2); /* remove modified line */ if (line[0] != '\0') /* non empty? */ lua_saveline(L, line); /* keep history */ } else - lua_pop(L, 2); /* remove result from 'luaL_loadbuffer' and new line */ + lua_pop(L, 2); /* pop result from 'luaL_loadbuffer' and modified line */ return status; } diff --git a/libs/lua-5.3.1/src/lua.h b/libs/lua-5.3.2/src/lua.h similarity index 99% rename from libs/lua-5.3.1/src/lua.h rename to libs/lua-5.3.2/src/lua.h index 1c2b95a..06381d7 100644 --- a/libs/lua-5.3.1/src/lua.h +++ b/libs/lua-5.3.2/src/lua.h @@ -1,5 +1,5 @@ /* -** $Id: lua.h,v 1.328 2015/06/03 13:03:38 roberto Exp $ +** $Id: lua.h,v 1.329 2015/11/13 17:18:42 roberto Exp $ ** Lua - A Scripting Language ** Lua.org, PUC-Rio, Brazil (http://www.lua.org) ** See Copyright Notice at the end of this file @@ -19,7 +19,7 @@ #define LUA_VERSION_MAJOR "5" #define LUA_VERSION_MINOR "3" #define LUA_VERSION_NUM 503 -#define LUA_VERSION_RELEASE "1" +#define LUA_VERSION_RELEASE "2" #define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR #define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE diff --git a/libs/lua-5.3.1/src/lua.hpp b/libs/lua-5.3.2/src/lua.hpp similarity index 100% rename from libs/lua-5.3.1/src/lua.hpp rename to libs/lua-5.3.2/src/lua.hpp diff --git a/libs/lua-5.3.1/src/luac.dontcompile b/libs/lua-5.3.2/src/luac.dontcompile similarity index 100% rename from libs/lua-5.3.1/src/luac.dontcompile rename to libs/lua-5.3.2/src/luac.dontcompile diff --git a/libs/lua-5.3.1/src/luaconf.h b/libs/lua-5.3.2/src/luaconf.h similarity index 91% rename from libs/lua-5.3.1/src/luaconf.h rename to libs/lua-5.3.2/src/luaconf.h index 4cc26f7..8d0e536 100644 --- a/libs/lua-5.3.1/src/luaconf.h +++ b/libs/lua-5.3.2/src/luaconf.h @@ -1,5 +1,5 @@ /* -** $Id: luaconf.h,v 1.251 2015/05/20 17:39:23 roberto Exp $ +** $Id: luaconf.h,v 1.254 2015/10/21 18:17:40 roberto Exp $ ** Configuration file for Lua ** See Copyright Notice in lua.h */ @@ -145,7 +145,7 @@ #if !defined(LUA_FLOAT_TYPE) #define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE -#endif /* } */ +#endif /* }================================================================== */ @@ -167,17 +167,38 @@ ** hierarchy or if you want to install your libraries in ** non-conventional directories. */ -#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "/" - -#define LUA_ROOT "sdmc:/" -#define LUA_LDIR LUA_ROOT "3ds/ctruLua/libs/" -#define LUA_CDIR LUA_ROOT "3ds/ctruLua/libs/" +#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR +#if defined(_WIN32) /* { */ +/* +** In Windows, any exclamation mark ('!') in the path is replaced by the +** path of the directory of the executable file of the current process. +*/ +#define LUA_LDIR "!\\lua\\" +#define LUA_CDIR "!\\" +#define LUA_SHRDIR "!\\..\\share\\lua\\" LUA_VDIR "\\" #define LUA_PATH_DEFAULT \ - LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ - LUA_LDIR LUA_VDIR"?.lua;" LUA_LDIR LUA_VDIR"?/init.lua;" \ + LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ + LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \ + LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \ + ".\\?.lua;" ".\\?\\init.lua" +#define LUA_CPATH_DEFAULT \ + LUA_CDIR"?.dll;" \ + LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \ + LUA_CDIR"loadall.dll;" ".\\?.dll" + +#else /* }{ */ + +#define LUA_ROOT "/usr/local/" +#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR "/" +#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR "/" +#define LUA_PATH_DEFAULT \ + LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ + LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \ "./?.lua;" "./?/init.lua" #define LUA_CPATH_DEFAULT \ LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" +#endif /* } */ + /* @@ LUA_DIRSEP is the directory separator (for submodules). @@ -391,9 +412,33 @@ @@ LUA_NUMBER_FMT is the format for writing floats. @@ lua_number2str converts a float to a string. @@ l_mathop allows the addition of an 'l' or 'f' to all math operations. +@@ l_floor takes the floor of a float. @@ lua_str2number converts a decimal numeric string to a number. */ + +/* The following definitions are good for most cases here */ + +#define l_floor(x) (l_mathop(floor)(x)) + +#define lua_number2str(s,sz,n) l_sprintf((s), sz, LUA_NUMBER_FMT, (n)) + +/* +@@ lua_numbertointeger converts a float number to an integer, or +** returns 0 if float is not within the range of a lua_Integer. +** (The range comparisons are tricky because of rounding. The tests +** here assume a two-complement representation, where MININTEGER always +** has an exact representation as a float; MAXINTEGER may not have one, +** and therefore its conversion to float may have an ill-defined value.) +*/ +#define lua_numbertointeger(n,p) \ + ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ + (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ + (*(p) = (LUA_INTEGER)(n), 1)) + + +/* now the variable definitions */ + #if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */ #define LUA_NUMBER float @@ -447,25 +492,6 @@ #endif /* } */ -#define l_floor(x) (l_mathop(floor)(x)) - -#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) - - -/* -@@ lua_numbertointeger converts a float number to an integer, or -** returns 0 if float is not within the range of a lua_Integer. -** (The range comparisons are tricky because of rounding. The tests -** here assume a two-complement representation, where MININTEGER always -** has an exact representation as a float; MAXINTEGER may not have one, -** and therefore its conversion to float may have an ill-defined value.) -*/ -#define lua_numbertointeger(n,p) \ - ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ - (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ - (*(p) = (LUA_INTEGER)(n), 1)) - - /* @@ LUA_INTEGER is the integer type used by Lua. @@ -485,7 +511,7 @@ /* The following definitions are good for most cases here */ #define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d" -#define lua_integer2str(s,n) sprintf((s), LUA_INTEGER_FMT, (n)) +#define lua_integer2str(s,sz,n) l_sprintf((s), sz, LUA_INTEGER_FMT, (n)) #define LUAI_UACINT LUA_INTEGER @@ -516,6 +542,7 @@ #elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */ +/* use presence of macro LLONG_MAX as proxy for C99 compliance */ #if defined(LLONG_MAX) /* { */ /* use ISO C99 stuff */ @@ -556,6 +583,17 @@ ** =================================================================== */ +/* +@@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89. +** (All uses in Lua have only one format item.) +*/ +#if !defined(LUA_USE_C89) +#define l_sprintf(s,sz,f,i) snprintf(s,sz,f,i) +#else +#define l_sprintf(s,sz,f,i) ((void)(sz), sprintf(s,f,i)) +#endif + + /* @@ lua_strx2number converts an hexadecimal numeric string to a number. ** In C99, 'strtod' does that conversion. Otherwise, you can @@ -563,7 +601,7 @@ ** implementation. */ #if !defined(LUA_USE_C89) -#define lua_strx2number(s,p) lua_str2number(s,p) +#define lua_strx2number(s,p) lua_str2number(s,p) #endif @@ -574,7 +612,7 @@ ** provide its own implementation. */ #if !defined(LUA_USE_C89) -#define lua_number2strx(L,b,f,n) sprintf(b,f,n) +#define lua_number2strx(L,b,sz,f,n) l_sprintf(b,sz,f,n) #endif diff --git a/libs/lua-5.3.1/src/lualib.h b/libs/lua-5.3.2/src/lualib.h similarity index 100% rename from libs/lua-5.3.1/src/lualib.h rename to libs/lua-5.3.2/src/lualib.h diff --git a/libs/lua-5.3.1/src/lundump.c b/libs/lua-5.3.2/src/lundump.c similarity index 92% rename from libs/lua-5.3.1/src/lundump.c rename to libs/lua-5.3.2/src/lundump.c index 510f325..4080af9 100644 --- a/libs/lua-5.3.1/src/lundump.c +++ b/libs/lua-5.3.2/src/lundump.c @@ -1,5 +1,5 @@ /* -** $Id: lundump.c,v 2.41 2014/11/02 19:19:04 roberto Exp $ +** $Id: lundump.c,v 2.44 2015/11/02 16:09:30 roberto Exp $ ** load precompiled Lua chunks ** See Copyright Notice in lua.h */ @@ -32,7 +32,6 @@ typedef struct { lua_State *L; ZIO *Z; - Mbuffer *b; const char *name; } LoadState; @@ -92,10 +91,15 @@ static TString *LoadString (LoadState *S) { LoadVar(S, size); if (size == 0) return NULL; - else { - char *s = luaZ_openspace(S->L, S->b, --size); - LoadVector(S, s, size); - return luaS_newlstr(S->L, s, size); + else if (--size <= LUAI_MAXSHORTLEN) { /* short string? */ + char buff[LUAI_MAXSHORTLEN]; + LoadVector(S, buff, size); + return luaS_newlstr(S->L, buff, size); + } + else { /* long string */ + TString *ts = luaS_createlngstrobj(S->L, size); + LoadVector(S, getstr(ts), size); /* load directly in final place */ + return ts; } } @@ -251,8 +255,7 @@ static void checkHeader (LoadState *S) { /* ** load precompiled chunk */ -LClosure *luaU_undump(lua_State *L, ZIO *Z, Mbuffer *buff, - const char *name) { +LClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) { LoadState S; LClosure *cl; if (*name == '@' || *name == '=') @@ -263,11 +266,10 @@ LClosure *luaU_undump(lua_State *L, ZIO *Z, Mbuffer *buff, S.name = name; S.L = L; S.Z = Z; - S.b = buff; checkHeader(&S); cl = luaF_newLclosure(L, LoadByte(&S)); setclLvalue(L, L->top, cl); - incr_top(L); + luaD_inctop(L); cl->p = luaF_newproto(L); LoadFunction(&S, cl->p, NULL); lua_assert(cl->nupvalues == cl->p->sizeupvalues); diff --git a/libs/lua-5.3.1/src/lundump.h b/libs/lua-5.3.2/src/lundump.h similarity index 78% rename from libs/lua-5.3.1/src/lundump.h rename to libs/lua-5.3.2/src/lundump.h index ef43d51..aa5cc82 100644 --- a/libs/lua-5.3.1/src/lundump.h +++ b/libs/lua-5.3.2/src/lundump.h @@ -1,5 +1,5 @@ /* -** $Id: lundump.h,v 1.44 2014/06/19 18:27:20 roberto Exp $ +** $Id: lundump.h,v 1.45 2015/09/08 15:41:05 roberto Exp $ ** load precompiled Lua chunks ** See Copyright Notice in lua.h */ @@ -23,8 +23,7 @@ #define LUAC_FORMAT 0 /* this is the official format */ /* load one chunk; from lundump.c */ -LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, - const char* name); +LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, const char* name); /* dump one chunk; from ldump.c */ LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, diff --git a/libs/lua-5.3.1/src/lutf8lib.c b/libs/lua-5.3.2/src/lutf8lib.c similarity index 100% rename from libs/lua-5.3.1/src/lutf8lib.c rename to libs/lua-5.3.2/src/lutf8lib.c diff --git a/libs/lua-5.3.1/src/lvm.c b/libs/lua-5.3.2/src/lvm.c similarity index 88% rename from libs/lua-5.3.1/src/lvm.c rename to libs/lua-5.3.2/src/lvm.c index a8cefc5..aba7ace 100644 --- a/libs/lua-5.3.1/src/lvm.c +++ b/libs/lua-5.3.2/src/lvm.c @@ -1,5 +1,5 @@ /* -** $Id: lvm.c,v 2.245 2015/06/09 15:53:35 roberto Exp $ +** $Id: lvm.c,v 2.265 2015/11/23 11:30:45 roberto Exp $ ** Lua virtual machine ** See Copyright Notice in lua.h */ @@ -153,30 +153,28 @@ static int forlimit (const TValue *obj, lua_Integer *p, lua_Integer step, /* -** Main function for table access (invoking metamethods if needed). -** Compute 'val = t[key]' +** Complete a table access: if 't' is a table, 'tm' has its metamethod; +** otherwise, 'tm' is NULL. */ -void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { +void luaV_finishget (lua_State *L, const TValue *t, TValue *key, StkId val, + const TValue *tm) { int loop; /* counter to avoid infinite loops */ + lua_assert(tm != NULL || !ttistable(t)); for (loop = 0; loop < MAXTAGLOOP; loop++) { - const TValue *tm; - if (ttistable(t)) { /* 't' is a table? */ - Table *h = hvalue(t); - const TValue *res = luaH_get(h, key); /* do a primitive get */ - if (!ttisnil(res) || /* result is not nil? */ - (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */ - setobj2s(L, val, res); /* result is the raw get */ - return; - } - /* else will try metamethod */ + if (tm == NULL) { /* no metamethod (from a table)? */ + if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX))) + luaG_typeerror(L, t, "index"); /* no metamethod */ } - else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX))) - luaG_typeerror(L, t, "index"); /* no metamethod */ if (ttisfunction(tm)) { /* metamethod is a function */ - luaT_callTM(L, tm, t, key, val, 1); + luaT_callTM(L, tm, t, key, val, 1); /* call it */ return; } t = tm; /* else repeat access over 'tm' */ + if (luaV_fastget(L,t,key,tm,luaH_get)) { /* try fast track */ + setobj2s(L, val, tm); /* done */ + return; + } + /* else repeat */ } luaG_runerror(L, "gettable chain too long; possible loop"); } @@ -186,40 +184,41 @@ void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { ** Main function for table assignment (invoking metamethods if needed). ** Compute 't[key] = val' */ -void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { +void luaV_finishset (lua_State *L, const TValue *t, TValue *key, + StkId val, const TValue *oldval) { int loop; /* counter to avoid infinite loops */ for (loop = 0; loop < MAXTAGLOOP; loop++) { const TValue *tm; - if (ttistable(t)) { /* 't' is a table? */ - Table *h = hvalue(t); - TValue *oldval = cast(TValue *, luaH_get(h, key)); - /* if previous value is not nil, there must be a previous entry - in the table; a metamethod has no relevance */ - if (!ttisnil(oldval) || - /* previous value is nil; must check the metamethod */ - ((tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL && + if (oldval != NULL) { + lua_assert(ttistable(t) && ttisnil(oldval)); + /* must check the metamethod */ + if ((tm = fasttm(L, hvalue(t)->metatable, TM_NEWINDEX)) == NULL && /* no metamethod; is there a previous entry in the table? */ (oldval != luaO_nilobject || /* no previous entry; must create one. (The next test is always true; we only need the assignment.) */ - (oldval = luaH_newkey(L, h, key), 1)))) { + (oldval = luaH_newkey(L, hvalue(t), key), 1))) { /* no metamethod and (now) there is an entry with given key */ - setobj2t(L, oldval, val); /* assign new value to that entry */ - invalidateTMcache(h); - luaC_barrierback(L, h, val); + setobj2t(L, cast(TValue *, oldval), val); + invalidateTMcache(hvalue(t)); + luaC_barrierback(L, hvalue(t), val); return; } /* else will try the metamethod */ } - else /* not a table; check metamethod */ + else { /* not a table; check metamethod */ if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) luaG_typeerror(L, t, "index"); + } /* try the metamethod */ if (ttisfunction(tm)) { luaT_callTM(L, tm, t, key, val, 0); return; } t = tm; /* else repeat assignment over 'tm' */ + if (luaV_fastset(L, t, key, oldval, luaH_get, val)) + return; /* done */ + /* else loop */ } luaG_runerror(L, "settable chain too long; possible loop"); } @@ -443,6 +442,17 @@ int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) { #define isemptystr(o) (ttisshrstring(o) && tsvalue(o)->shrlen == 0) +/* copy strings in stack from top - n up to top - 1 to buffer */ +static void copy2buff (StkId top, int n, char *buff) { + size_t tl = 0; /* size already copied */ + do { + size_t l = vslen(top - n); /* length of string being copied */ + memcpy(buff + tl, svalue(top - n), l * sizeof(char)); + tl += l; + } while (--n > 0); +} + + /* ** Main operation for concatenation: concat 'total' values in the stack, ** from 'L->top - total' up to 'L->top - 1'. @@ -462,24 +472,24 @@ void luaV_concat (lua_State *L, int total) { else { /* at least two non-empty string values; get as many as possible */ size_t tl = vslen(top - 1); - char *buffer; - int i; - /* collect total length */ - for (i = 1; i < total && tostring(L, top-i-1); i++) { - size_t l = vslen(top - i - 1); + TString *ts; + /* collect total length and number of strings */ + for (n = 1; n < total && tostring(L, top - n - 1); n++) { + size_t l = vslen(top - n - 1); if (l >= (MAX_SIZE/sizeof(char)) - tl) luaG_runerror(L, "string length overflow"); tl += l; } - buffer = luaZ_openspace(L, &G(L)->buff, tl); - tl = 0; - n = i; - do { /* copy all strings to buffer */ - size_t l = vslen(top - i); - memcpy(buffer+tl, svalue(top-i), l * sizeof(char)); - tl += l; - } while (--i > 0); - setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl)); /* create result */ + if (tl <= LUAI_MAXSHORTLEN) { /* is result a short string? */ + char buff[LUAI_MAXSHORTLEN]; + copy2buff(top, n, buff); /* copy strings to buffer */ + ts = luaS_newlstr(L, buff, tl); + } + else { /* long string; copy strings directly to final result */ + ts = luaS_createlngstrobj(L, tl); + copy2buff(top, n, getstr(ts)); + } + setsvalue2s(L, top - n, ts); /* create result */ } total -= n-1; /* got 'n' strings to create 1 new */ L->top -= n-1; /* popped 'n' strings and pushed one */ @@ -700,27 +710,20 @@ void luaV_finishOp (lua_State *L) { ** some macros for common tasks in 'luaV_execute' */ -#if !defined(luai_runtimecheck) -#define luai_runtimecheck(L, c) /* void */ -#endif - #define RA(i) (base+GETARG_A(i)) -/* to be used after possible stack reallocation */ #define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i)) #define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i)) #define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \ ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i)) #define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \ ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i)) -#define KBx(i) \ - (k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++))) /* execute a jump instruction */ #define dojump(ci,i,e) \ { int a = GETARG_A(i); \ - if (a > 0) luaF_close(L, ci->u.l.base + a - 1); \ + if (a != 0) luaF_close(L, ci->u.l.base + a - 1); \ ci->u.l.savedpc += GETARG_sBx(i) + e; } /* for test instructions, execute the jump instruction that follows it */ @@ -730,34 +733,49 @@ void luaV_finishOp (lua_State *L) { #define Protect(x) { {x;}; base = ci->u.l.base; } #define checkGC(L,c) \ - Protect( luaC_condGC(L,{L->top = (c); /* limit of live values */ \ - luaC_step(L); \ - L->top = ci->top;}) /* restore top */ \ - luai_threadyield(L); ) + { luaC_condGC(L, L->top = (c), /* limit of live values */ \ + Protect(L->top = ci->top)); /* restore top */ \ + luai_threadyield(L); } #define vmdispatch(o) switch(o) #define vmcase(l) case l: #define vmbreak break + +/* +** copy of 'luaV_gettable', but protecting call to potential metamethod +** (which can reallocate the stack) +*/ +#define gettableProtected(L,t,k,v) { const TValue *aux; \ + if (luaV_fastget(L,t,k,aux,luaH_get)) { setobj2s(L, v, aux); } \ + else Protect(luaV_finishget(L,t,k,v,aux)); } + + +/* same for 'luaV_settable' */ +#define settableProtected(L,t,k,v) { const TValue *slot; \ + if (!luaV_fastset(L,t,k,slot,luaH_get,v)) \ + Protect(luaV_finishset(L,t,k,v,slot)); } + + + void luaV_execute (lua_State *L) { CallInfo *ci = L->ci; LClosure *cl; TValue *k; StkId base; + ci->callstatus |= CIST_FRESH; /* fresh invocation of 'luaV_execute" */ newframe: /* reentry point when frame changes (call/return) */ lua_assert(ci == L->ci); - cl = clLvalue(ci->func); - k = cl->p->k; - base = ci->u.l.base; + cl = clLvalue(ci->func); /* local reference to function's closure */ + k = cl->p->k; /* local reference to function's constant table */ + base = ci->u.l.base; /* local copy of function's base */ /* main loop of interpreter */ for (;;) { Instruction i = *(ci->u.l.savedpc++); StkId ra; - if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) && - (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { + if (L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) Protect(luaG_traceexec(L)); - } /* WARNING: several calls may realloc the stack and invalidate 'ra' */ ra = RA(i); lua_assert(base == ci->u.l.base); @@ -797,17 +815,22 @@ void luaV_execute (lua_State *L) { vmbreak; } vmcase(OP_GETTABUP) { - int b = GETARG_B(i); - Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra)); + TValue *upval = cl->upvals[GETARG_B(i)]->v; + TValue *rc = RKC(i); + gettableProtected(L, upval, rc, ra); vmbreak; } vmcase(OP_GETTABLE) { - Protect(luaV_gettable(L, RB(i), RKC(i), ra)); + StkId rb = RB(i); + TValue *rc = RKC(i); + gettableProtected(L, rb, rc, ra); vmbreak; } vmcase(OP_SETTABUP) { - int a = GETARG_A(i); - Protect(luaV_settable(L, cl->upvals[a]->v, RKB(i), RKC(i))); + TValue *upval = cl->upvals[GETARG_A(i)]->v; + TValue *rb = RKB(i); + TValue *rc = RKC(i); + settableProtected(L, upval, rb, rc); vmbreak; } vmcase(OP_SETUPVAL) { @@ -817,7 +840,9 @@ void luaV_execute (lua_State *L) { vmbreak; } vmcase(OP_SETTABLE) { - Protect(luaV_settable(L, ra, RKB(i), RKC(i))); + TValue *rb = RKB(i); + TValue *rc = RKC(i); + settableProtected(L, ra, rb, rc); vmbreak; } vmcase(OP_NEWTABLE) { @@ -831,9 +856,15 @@ void luaV_execute (lua_State *L) { vmbreak; } vmcase(OP_SELF) { + const TValue *aux; StkId rb = RB(i); - setobjs2s(L, ra+1, rb); - Protect(luaV_gettable(L, rb, RKC(i), ra)); + TValue *rc = RKC(i); + TString *key = tsvalue(rc); /* key must be a string */ + setobjs2s(L, ra + 1, rb); + if (luaV_fastget(L, rb, key, aux, luaH_getstr)) { + setobj2s(L, ra, aux); + } + else Protect(luaV_finishget(L, rb, rc, ra, aux)); vmbreak; } vmcase(OP_ADD) { @@ -1020,7 +1051,7 @@ void luaV_execute (lua_State *L) { StkId rb; L->top = base + c + 1; /* mark the end of concat operands */ Protect(luaV_concat(L, c - b + 1)); - ra = RA(i); /* 'luav_concat' may invoke TMs and move the stack */ + ra = RA(i); /* 'luaV_concat' may invoke TMs and move the stack */ rb = base + b; setobjs2s(L, ra, rb); checkGC(L, (ra >= rb ? ra + 1 : rb)); @@ -1035,7 +1066,7 @@ void luaV_execute (lua_State *L) { TValue *rb = RKB(i); TValue *rc = RKC(i); Protect( - if (cast_int(luaV_equalobj(L, rb, rc)) != GETARG_A(i)) + if (luaV_equalobj(L, rb, rc) != GETARG_A(i)) ci->u.l.savedpc++; else donextjump(ci); @@ -1082,12 +1113,12 @@ void luaV_execute (lua_State *L) { int nresults = GETARG_C(i) - 1; if (b != 0) L->top = ra+b; /* else previous instruction set top */ if (luaD_precall(L, ra, nresults)) { /* C function? */ - if (nresults >= 0) L->top = ci->top; /* adjust results */ - base = ci->u.l.base; + if (nresults >= 0) + L->top = ci->top; /* adjust results */ + Protect((void)0); /* update 'base' */ } else { /* Lua function */ ci = L->ci; - ci->callstatus |= CIST_REENTRY; goto newframe; /* restart luaV_execute over new Lua function */ } vmbreak; @@ -1096,8 +1127,9 @@ void luaV_execute (lua_State *L) { int b = GETARG_B(i); if (b != 0) L->top = ra+b; /* else previous instruction set top */ lua_assert(GETARG_C(i) - 1 == LUA_MULTRET); - if (luaD_precall(L, ra, LUA_MULTRET)) /* C function? */ - base = ci->u.l.base; + if (luaD_precall(L, ra, LUA_MULTRET)) { /* C function? */ + Protect((void)0); /* update 'base' */ + } else { /* tail call: put called frame (n) in place of caller one (o) */ CallInfo *nci = L->ci; /* called frame */ @@ -1125,8 +1157,8 @@ void luaV_execute (lua_State *L) { vmcase(OP_RETURN) { int b = GETARG_B(i); if (cl->p->sizep > 0) luaF_close(L, base); - b = luaD_poscall(L, ra, (b != 0 ? b - 1 : L->top - ra)); - if (!(ci->callstatus & CIST_REENTRY)) /* 'ci' still the called one */ + b = luaD_poscall(L, ci, ra, (b != 0 ? b - 1 : cast_int(L->top - ra))); + if (ci->callstatus & CIST_FRESH) /* local 'ci' still from callee */ return; /* external invocation: return */ else { /* invocation via reentry: continue execution */ ci = L->ci; @@ -1139,7 +1171,7 @@ void luaV_execute (lua_State *L) { vmcase(OP_FORLOOP) { if (ttisinteger(ra)) { /* integer loop? */ lua_Integer step = ivalue(ra + 2); - lua_Integer idx = ivalue(ra) + step; /* increment index */ + lua_Integer idx = intop(+, ivalue(ra), step); /* increment index */ lua_Integer limit = ivalue(ra + 1); if ((0 < step) ? (idx <= limit) : (limit <= idx)) { ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ @@ -1171,7 +1203,7 @@ void luaV_execute (lua_State *L) { /* all values are integer */ lua_Integer initv = (stopnow ? 0 : ivalue(init)); setivalue(plimit, ilimit); - setivalue(init, initv - ivalue(pstep)); + setivalue(init, intop(-, initv, ivalue(pstep))); } else { /* try making all values floats */ lua_Number ninit; lua_Number nlimit; lua_Number nstep; @@ -1194,7 +1226,7 @@ void luaV_execute (lua_State *L) { setobjs2s(L, cb+1, ra+1); setobjs2s(L, cb, ra); L->top = cb + 3; /* func. + 2 args (state and index) */ - Protect(luaD_call(L, cb, GETARG_C(i), 1)); + Protect(luaD_call(L, cb, GETARG_C(i))); L->top = ci->top; i = *(ci->u.l.savedpc++); /* go to next instruction */ ra = RA(i); @@ -1219,11 +1251,10 @@ void luaV_execute (lua_State *L) { lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG); c = GETARG_Ax(*ci->u.l.savedpc++); } - luai_runtimecheck(L, ttistable(ra)); h = hvalue(ra); last = ((c-1)*LFIELDS_PER_FLUSH) + n; if (last > h->sizearray) /* needs more space? */ - luaH_resizearray(L, h, last); /* pre-allocate it at once */ + luaH_resizearray(L, h, last); /* preallocate it at once */ for (; n > 0; n--) { TValue *val = ra+n; luaH_setint(L, h, last--, val); @@ -1243,23 +1274,21 @@ void luaV_execute (lua_State *L) { vmbreak; } vmcase(OP_VARARG) { - int b = GETARG_B(i) - 1; + int b = GETARG_B(i) - 1; /* required results */ int j; int n = cast_int(base - ci->func) - cl->p->numparams - 1; + if (n < 0) /* less arguments than parameters? */ + n = 0; /* no vararg arguments */ if (b < 0) { /* B == 0? */ b = n; /* get all var. arguments */ Protect(luaD_checkstack(L, n)); ra = RA(i); /* previous call may change the stack */ L->top = ra + n; } - for (j = 0; j < b; j++) { - if (j < n) { - setobjs2s(L, ra + j, base - n + j); - } - else { - setnilvalue(ra + j); - } - } + for (j = 0; j < b && j < n; j++) + setobjs2s(L, ra + j, base - n + j); + for (; j < b; j++) /* complete required results with nil */ + setnilvalue(ra + j); vmbreak; } vmcase(OP_EXTRAARG) { diff --git a/libs/lua-5.3.2/src/lvm.h b/libs/lua-5.3.2/src/lvm.h new file mode 100644 index 0000000..fd0e748 --- /dev/null +++ b/libs/lua-5.3.2/src/lvm.h @@ -0,0 +1,114 @@ +/* +** $Id: lvm.h,v 2.39 2015/09/09 13:44:07 roberto Exp $ +** Lua virtual machine +** See Copyright Notice in lua.h +*/ + +#ifndef lvm_h +#define lvm_h + + +#include "ldo.h" +#include "lobject.h" +#include "ltm.h" + + +#if !defined(LUA_NOCVTN2S) +#define cvt2str(o) ttisnumber(o) +#else +#define cvt2str(o) 0 /* no conversion from numbers to strings */ +#endif + + +#if !defined(LUA_NOCVTS2N) +#define cvt2num(o) ttisstring(o) +#else +#define cvt2num(o) 0 /* no conversion from strings to numbers */ +#endif + + +/* +** You can define LUA_FLOORN2I if you want to convert floats to integers +** by flooring them (instead of raising an error if they are not +** integral values) +*/ +#if !defined(LUA_FLOORN2I) +#define LUA_FLOORN2I 0 +#endif + + +#define tonumber(o,n) \ + (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n)) + +#define tointeger(o,i) \ + (ttisinteger(o) ? (*(i) = ivalue(o), 1) : luaV_tointeger(o,i,LUA_FLOORN2I)) + +#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2)) + +#define luaV_rawequalobj(t1,t2) luaV_equalobj(NULL,t1,t2) + + +/* +** fast track for 'gettable': 1 means 'aux' points to resulted value; +** 0 means 'aux' is metamethod (if 't' is a table) or NULL. 'f' is +** the raw get function to use. +*/ +#define luaV_fastget(L,t,k,aux,f) \ + (!ttistable(t) \ + ? (aux = NULL, 0) /* not a table; 'aux' is NULL and result is 0 */ \ + : (aux = f(hvalue(t), k), /* else, do raw access */ \ + !ttisnil(aux) ? 1 /* result not nil? 'aux' has it */ \ + : (aux = fasttm(L, hvalue(t)->metatable, TM_INDEX), /* get metamethod */\ + aux != NULL ? 0 /* has metamethod? must call it */ \ + : (aux = luaO_nilobject, 1)))) /* else, final result is nil */ + +/* +** standard implementation for 'gettable' +*/ +#define luaV_gettable(L,t,k,v) { const TValue *aux; \ + if (luaV_fastget(L,t,k,aux,luaH_get)) { setobj2s(L, v, aux); } \ + else luaV_finishget(L,t,k,v,aux); } + + +/* +** Fast track for set table. If 't' is a table and 't[k]' is not nil, +** call GC barrier, do a raw 't[k]=v', and return true; otherwise, +** return false with 'slot' equal to NULL (if 't' is not a table) or +** 'nil'. (This is needed by 'luaV_finishget'.) Note that, if the macro +** returns true, there is no need to 'invalidateTMcache', because the +** call is not creating a new entry. +*/ +#define luaV_fastset(L,t,k,slot,f,v) \ + (!ttistable(t) \ + ? (slot = NULL, 0) \ + : (slot = f(hvalue(t), k), \ + ttisnil(slot) ? 0 \ + : (luaC_barrierback(L, hvalue(t), v), \ + setobj2t(L, cast(TValue *,slot), v), \ + 1))) + + +#define luaV_settable(L,t,k,v) { const TValue *slot; \ + if (!luaV_fastset(L,t,k,slot,luaH_get,v)) \ + luaV_finishset(L,t,k,v,slot); } + + + +LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2); +LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); +LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r); +LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n); +LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, int mode); +LUAI_FUNC void luaV_finishget (lua_State *L, const TValue *t, TValue *key, + StkId val, const TValue *tm); +LUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key, + StkId val, const TValue *oldval); +LUAI_FUNC void luaV_finishOp (lua_State *L); +LUAI_FUNC void luaV_execute (lua_State *L); +LUAI_FUNC void luaV_concat (lua_State *L, int total); +LUAI_FUNC lua_Integer luaV_div (lua_State *L, lua_Integer x, lua_Integer y); +LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y); +LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y); +LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb); + +#endif diff --git a/libs/lua-5.3.1/src/lzio.c b/libs/lua-5.3.2/src/lzio.c similarity index 79% rename from libs/lua-5.3.1/src/lzio.c rename to libs/lua-5.3.2/src/lzio.c index 4649392..c9e1f49 100644 --- a/libs/lua-5.3.1/src/lzio.c +++ b/libs/lua-5.3.2/src/lzio.c @@ -1,5 +1,5 @@ /* -** $Id: lzio.c,v 1.36 2014/11/02 19:19:04 roberto Exp $ +** $Id: lzio.c,v 1.37 2015/09/08 15:41:05 roberto Exp $ ** Buffered streams ** See Copyright Notice in lua.h */ @@ -66,13 +66,3 @@ size_t luaZ_read (ZIO *z, void *b, size_t n) { return 0; } -/* ------------------------------------------------------------------------ */ -char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) { - if (n > buff->buffsize) { - if (n < LUA_MINBUFFER) n = LUA_MINBUFFER; - luaZ_resizebuffer(L, buff, n); - } - return buff->buffer; -} - - diff --git a/libs/lua-5.3.1/src/lzio.h b/libs/lua-5.3.2/src/lzio.h similarity index 91% rename from libs/lua-5.3.1/src/lzio.h rename to libs/lua-5.3.2/src/lzio.h index b2e56bc..e7b6f34 100644 --- a/libs/lua-5.3.1/src/lzio.h +++ b/libs/lua-5.3.2/src/lzio.h @@ -1,5 +1,5 @@ /* -** $Id: lzio.h,v 1.30 2014/12/19 17:26:14 roberto Exp $ +** $Id: lzio.h,v 1.31 2015/09/08 15:41:05 roberto Exp $ ** Buffered streams ** See Copyright Notice in lua.h */ @@ -44,7 +44,6 @@ typedef struct Mbuffer { #define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) -LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n); LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data); LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n); /* read next n bytes */ diff --git a/libs/sf2dlib/.gitignore b/libs/sf2dlib/.gitignore index e1071b6..a020760 100644 --- a/libs/sf2dlib/.gitignore +++ b/libs/sf2dlib/.gitignore @@ -1,2 +1,7 @@ -libsf2d/build/ -libsf2d/lib/ \ No newline at end of file +*.d +*.o +*.project +*.cproject +libsf2d/.settings/* +libsf2d/build/* +libsf2d/lib/* diff --git a/libs/sf2dlib/libsf2d/.gitignore b/libs/sf2dlib/libsf2d/.gitignore new file mode 100644 index 0000000..e63ddd8 --- /dev/null +++ b/libs/sf2dlib/libsf2d/.gitignore @@ -0,0 +1 @@ +/Default/ diff --git a/libs/sf2dlib/libsf2d/Makefile b/libs/sf2dlib/libsf2d/Makefile index 99c44b9..28ccec1 100644 --- a/libs/sf2dlib/libsf2d/Makefile +++ b/libs/sf2dlib/libsf2d/Makefile @@ -30,6 +30,11 @@ CFLAGS := -g -Wall -O2\ $(ARCH) CFLAGS += $(INCLUDE) -DARM11 -D_3DS +#CFLAGS += -std=c11 + +#WILL HAVE TO BE REMOVED SOON +CFLAGS += -DLIBCTRU_NO_DEPRECATION + CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions ASFLAGS := -g $(ARCH) @@ -125,15 +130,16 @@ $(OUTPUT) : $(OFILES) # WARNING: This is not the right way to do this! TODO: Do it right! #--------------------------------------------------------------------------------- -%_vsh.h %.vsh.o : %.vsh +%.vsh.o : %.vsh #--------------------------------------------------------------------------------- @echo $(notdir $<) - @python ../../../aemstro/aemstro_as.py $< ../$(notdir $<).shbin - @bin2s ../$(notdir $<).shbin | $(PREFIX)as -o $@ + @picasso -o $(notdir $<).shbin $< + @bin2s $(notdir $<).shbin | $(PREFIX)as -o $@ @echo "extern const u8" `(echo $(notdir $<).shbin | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`"_end[];" > `(echo $(notdir $<).shbin | tr . _)`.h @echo "extern const u8" `(echo $(notdir $<).shbin | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`"[];" >> `(echo $(notdir $<).shbin | tr . _)`.h @echo "extern const u32" `(echo $(notdir $<).shbin | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`_size";" >> `(echo $(notdir $<).shbin | tr . _)`.h - @rm ../$(notdir $<).shbin + +sf2d.c: shader.vsh -include $(DEPENDS) diff --git a/libs/sf2dlib/libsf2d/data/shader.vsh b/libs/sf2dlib/libsf2d/data/shader.vsh index 2a604d5..3793136 100644 --- a/libs/sf2dlib/libsf2d/data/shader.vsh +++ b/libs/sf2dlib/libsf2d/data/shader.vsh @@ -1,39 +1,30 @@ -; setup constants - .const c20, 0.0, 0.0, 0.0, 1.0 +; Outputs +.out outpos position +.out outtc0 texcoord0 +.out outclr color -; setup outmap - .out o0, result.position, 0xF - .out o1, result.texcoord0, 0x3 - .out o2, result.color, 0xF +; Inputs +.alias inpos v0 +.alias inarg v1 -; setup uniform map (not required) - .uniform c0, c3, projection +; Uniforms +.fvec projection[4] - .vsh vmain, end_vmain +; Constants +.constf RGBA8_TO_FLOAT4(0.00392156862, 0, 0, 0) -;code - vmain: - ; result.pos = projMtx * in.pos - dp4 o0, c0, v0 (0x0) - dp4 o0, c1, v0 (0x1) - dp4 o0, c2, v0 (0x2) - dp4 o0, c3, v0 (0x3) - ; result.texcoord = in.texcoord - mov o1, v1 (0x5) - ; result.color = in.color - mov o2, v1 (0x5) - nop - end - end_vmain: - -;operand descriptors - .opdesc x___, xyzw, xyzw ; 0x0 - .opdesc _y__, xyzw, xyzw ; 0x1 - .opdesc __z_, xyzw, xyzw ; 0x2 - .opdesc ___w, xyzw, xyzw ; 0x3 - .opdesc xyz_, xyzw, xyzw ; 0x4 - .opdesc xyzw, xyzw, xyzw ; 0x5 - .opdesc x_zw, xyzw, xyzw ; 0x6 - .opdesc xyzw, yyyw, xyzw ; 0x7 - .opdesc xyz_, wwww, wwww ; 0x8 - .opdesc xyz_, yyyy, xyzw ; 0x9 +.proc main + ; outpos = projection * in.pos + dp4 outpos.x, projection[0].wzyx, inpos + dp4 outpos.y, projection[1].wzyx, inpos + dp4 outpos.z, projection[2].wzyx, inpos + dp4 outpos.w, projection[3].wzyx, inpos + + ; outtc0 = in.texcoord + mov outtc0, inarg + + ; outclr = RGBA8_TO_FLOAT4(in.color) + mul outclr, RGBA8_TO_FLOAT4.xxxx, inarg + + end +.end diff --git a/libs/sf2dlib/libsf2d/include/sf2d.h b/libs/sf2dlib/libsf2d/include/sf2d.h index 9df8d08..b6f3277 100644 --- a/libs/sf2dlib/libsf2d/include/sf2d.h +++ b/libs/sf2dlib/libsf2d/include/sf2d.h @@ -4,7 +4,6 @@ * @date 22 March 2015 * @brief sf2dlib header */ - #ifndef SF2D_H #define SF2D_H @@ -23,7 +22,12 @@ extern "C" { * @param b the blue component of the color to create * @param a the alpha component of the color to create */ -#define RGBA8(r, g, b, a) ((((r)&0xFF)<<24) | (((g)&0xFF)<<16) | (((b)&0xFF)<<8) | (((a)&0xFF)<<0)) +#define RGBA8(r, g, b, a) ((((a)&0xFF)<<24) | (((b)&0xFF)<<16) | (((g)&0xFF)<<8) | (((r)&0xFF)<<0)) + +#define RGBA8_GET_R(c) (((c) >> 0) & 0xFF) +#define RGBA8_GET_G(c) (((c) >> 8) & 0xFF) +#define RGBA8_GET_B(c) (((c) >> 16) & 0xFF) +#define RGBA8_GET_A(c) (((c) >> 24) & 0xFF) /** * @brief Default size of the GPU commands FIFO buffer @@ -63,6 +67,14 @@ typedef enum { TEXFMT_ETC1A4 = 13 } sf2d_texfmt; +/** + * @brief Represents a direction for drawing a gradient + */ + +typedef enum { + SF2D_TOP_TO_BOTTOM, + SF2D_LEFT_TO_RIGHT +} sf2d_gradient_dir; /** * @brief Data allocated on the RAM or VRAM @@ -96,23 +108,13 @@ typedef struct { } sf2d_vector_3f; /** - * @brief Represents a four dimensional float vector - */ - -typedef struct { - float r; /**< Red component of the vector/color */ - float g; /**< Green component of the vector/color */ - float b; /**< Blue component of the vector/color */ - float a; /**< Alpha component of the vector/color */ -} sf2d_vector_4f; - -/** - * @brief Represents a vertex containing position and color attributes + * @brief Represents a vertex containing position (float) + * and color (unsigned int) */ typedef struct { sf2d_vector_3f position; /**< Position of the vertex */ - sf2d_vector_4f color; /**< Color of the vertex */ + u32 color; /**< Color of the vertex */ } sf2d_vertex_pos_col; /** @@ -132,6 +134,7 @@ typedef struct { sf2d_place place; /**< Where the texture data resides, RAM or VRAM */ int tiled; /**< Whether the tetxure is tiled or not */ sf2d_texfmt pixel_format; /**< Pixel format */ + u32 params; /**< Texture filters and wrapping */ int width; /**< Texture width */ int height; /**< Texture height */ int pow2_w; /**< Nearest power of 2 >= width */ @@ -140,6 +143,11 @@ typedef struct { void *data; /**< Pointer to the data */ } sf2d_texture; +typedef struct { + sf2d_texture texture; // "inherit"/extend standard texture + float projection[4*4]; /**< Orthographic projection matrix for this target */ +} sf2d_rendertarget; + // Basic functions /** @@ -175,6 +183,12 @@ void sf2d_set_3D(int enable); */ void sf2d_start_frame(gfxScreen_t screen, gfx3dSide_t side); +/** + * @brief Starts a frame bound to a rendertarget + * @param target rendertarget to draw to + */ +void sf2d_start_frame_target(sf2d_rendertarget *target); + /** * @brief Ends a frame, should be called on pair with sf2d_start_frame */ @@ -210,6 +224,15 @@ void *sf2d_pool_malloc(u32 size); */ void *sf2d_pool_memalign(u32 size, u32 alignment); +/** + * @brief Allocates aligned memory for an array from a temporary pool. Works as sf2d_pool_malloc + * @param nmemb the number of elements to allocate + * @param size the size (and alignment) of each element to allocate + * @note Unlike libc's calloc, this function does not initialize to 0, + * and returns a pointer aligned to size. + */ +void *sf2d_pool_calloc(u32 nmemb, u32 size); + /** * @brief Returns the temporary pool's free space * @return the temporary pool's free space @@ -234,9 +257,10 @@ void sf2d_set_clear_color(u32 color); * @param y0 y coordinate of the first dot * @param x1 x coordinate of the second dot * @param y1 y coordinate of the sceond dot + * @param width thickness of the line * @param color the color to draw the line */ -void sf2d_draw_line(int x0, int y0, int x1, int y1, u32 color); + void sf2d_draw_line(float x0, float y0, float x1, float y1, float width, u32 color); /** * @brief Draws a rectangle @@ -248,6 +272,18 @@ void sf2d_draw_line(int x0, int y0, int x1, int y1, u32 color); */ void sf2d_draw_rectangle(int x, int y, int w, int h, u32 color); +/** + * @brief Draws a triangle + * @param x1 x coordinate of a vertex of the triangle + * @param y1 y coordinate of a vertex of the triangle + * @param x2 x coordinate of a vertex of the triangle + * @param y2 y coordinate of a vertex of the triangle + * @param x3 x coordinate of a vertex of the triangle + * @param y3 y coordinate of a vertex of the triangle + * @param color the color to draw the triangle + */ +void sf2d_draw_triangle(float x1, float y1, float x2, float y2, float x3, float y3, u32 color); + /** * @brief Draws a rotated rectangle * @param x x coordinate of the top left corner of the rectangle @@ -259,6 +295,31 @@ void sf2d_draw_rectangle(int x, int y, int w, int h, u32 color); */ void sf2d_draw_rectangle_rotate(int x, int y, int w, int h, u32 color, float rad); +/** + * @brief Draws a rectangle + * @param x x coordinate of the top left corner of the rectangle + * @param y y coordinate of the top left corner of the rectangle + * @param w rectangle width + * @param h rectangle height + * @param color1 the color at the start of the gradient + * @param color2 the color at the end of the gradient + * @param left_to_right determines which direction the gradient is in + */ +void sf2d_draw_rectangle_gradient(int x, int y, int w, int h, u32 color1, u32 color2, sf2d_gradient_dir direction); + +/** + * @brief Draws a rotated rectangle + * @param x x coordinate of the top left corner of the rectangle + * @param y y coordinate of the top left corner of the rectangle + * @param w rectangle width + * @param h rectangle height + * @param color1 the color at the start of the gradient + * @param color2 the color at the end of the gradient + * @param left_to_right determines which direction the gradient is in + * @param rad rotation (in radians) to draw the rectangle + */ +void sf2d_draw_rectangle_gradient_rotate(int x, int y, int w, int h, u32 color1, u32 color2, sf2d_gradient_dir direction, float rad); + /** * @brief Draws a filled circle * @param x x coordinate of the center of the circle @@ -282,15 +343,42 @@ void sf2d_draw_fill_circle(int x, int y, int radius, u32 color); * @return a pointer to the newly created texture * @note Before drawing the texture, it needs to be tiled * by calling sf2d_texture_tile32. + * The default texture params are both min and mag filters + * GPU_NEAREST, and both S and T wrappings GPU_CLAMP_TO_BORDER. */ sf2d_texture *sf2d_create_texture(int width, int height, sf2d_texfmt pixel_format, sf2d_place place); +/** + * @brief Creates an empty rendertarget. + * Functions similarly to sf2d_create_texture. + * @param width the width of the texture + * @param height the height of the texture + * @return a pointer to the newly created rendertarget + * @note Before drawing the texture, it needs to be tiled + * by calling sf2d_texture_tile32. + * The default texture params are both min and mag filters + * GPU_NEAREST, and both S and T wrappings GPU_CLAMP_TO_BORDER. + */ +sf2d_rendertarget *sf2d_create_rendertarget(int width, int height); + /** * @brief Frees a texture * @param texture pointer to the texture to freeze */ void sf2d_free_texture(sf2d_texture *texture); +/** + * @brief Frees a rendertarget + * @param target pointer to the rendertarget to free + */ +void sf2d_free_target(sf2d_rendertarget *target); + +/** + * @brief Clears a rendertarget to the specified color + * @param target pointer to the rendertarget to clear + */ +void sf2d_clear_target(sf2d_rendertarget *target, u32 color); + /** * @brief Fills an already allocated texture from a RGBA8 source * @param dst pointer to the destination texture to fill @@ -336,6 +424,22 @@ void sf2d_bind_texture_color(const sf2d_texture *texture, GPU_TEXUNIT unit, u32 */ void sf2d_bind_texture_parameters(const sf2d_texture *texture, GPU_TEXUNIT unit, unsigned int params); +/** + * @brief Changes the texture params (filters and wrapping) + * @param texture the texture to change the params + * @param params the new texture params to use. You can use the + * GPU_TEXTURE_[MIN,MAG]_FILTER and GPU_TEXTURE_WRAP_[S,T] + * macros as helpers. + */ +void sf2d_texture_set_params(sf2d_texture *texture, u32 params); + +/** + * @brief Returns the texture params + * @param texture the texture to get the params + * @return the current texture params of texture + */ +int sf2d_texture_get_params(const sf2d_texture *texture); + /** * @brief Draws a texture * @param texture the texture to draw @@ -396,6 +500,33 @@ void sf2d_draw_texture_rotate(const sf2d_texture *texture, int x, int y, float r */ void sf2d_draw_texture_rotate_blend(const sf2d_texture *texture, int x, int y, float rad, u32 color); +/** + * @brief Draws a scaled texture with rotation around its hotspot + * @param texture the texture to draw + * @param x the x coordinate to draw the texture to + * @param y the y coordinate to draw the texture to + * @param rad rotation (in radians) to draw the texture + * @param x_scale the x scale + * @param y_scale the y scale + * @param center_x the x position of the hotspot + * @param center_y the y position of the hotspot + */ +void sf2d_draw_texture_rotate_scale_hotspot(const sf2d_texture *texture, int x, int y, float rad, float scale_x, float scale_y, float center_x, float center_y); + +/** + * @brief Draws a scaled texture with rotation around its hotspot with color + * @param texture the texture to draw + * @param x the x coordinate to draw the texture to + * @param y the y coordinate to draw the texture to + * @param rad rotation (in radians) to draw the texture + * @param x_scale the x scale + * @param y_scale the y scale + * @param center_x the x position of the hotspot + * @param center_y the y position of the hotspot + * @param color the color to blend with the texture + */ +void sf2d_draw_texture_rotate_scale_hotspot_blend(const sf2d_texture *texture, int x, int y, float rad, float scale_x, float scale_y, float center_x, float center_y, u32 color); + /** * @brief Draws a part of a texture * @param texture the texture to draw @@ -502,6 +633,24 @@ void sf2d_draw_texture_part_rotate_scale(const sf2d_texture *texture, int x, int */ void sf2d_draw_texture_part_rotate_scale_blend(const sf2d_texture *texture, int x, int y, float rad, int tex_x, int tex_y, int tex_w, int tex_h, float x_scale, float y_scale, u32 color); +/** + * @brief Draws a part of a texture, with rotation, scaling, color and hotspot + * @param texture the texture to draw + * @param x the x coordinate to draw the texture to + * @param y the y coordinate to draw the texture to + * @param rad rotation (in radians) to draw the texture + * @param tex_x the starting point (x coordinate) where to start drawing + * @param tex_y the starting point (y coordinate) where to start drawing + * @param tex_w the width to draw from the starting point + * @param tex_h the height to draw from the starting point + * @param x_scale the x scale + * @param y_scale the y scale + * @param center_x the x position of the hotspot + * @param center_y the y position of the hotspot + * @param color the color to blend with the texture + */ +void sf2d_draw_texture_part_rotate_scale_hotspot_blend(const sf2d_texture *texture, int x, int y, float rad, int tex_x, int tex_y, int tex_w, int tex_h, float x_scale, float y_scale, float center_x, float center_y, u32 color); + /** * @brief Draws a texture blended in a certain depth * @param texture the texture to draw diff --git a/libs/sf2dlib/libsf2d/include/sf2d_private.h b/libs/sf2dlib/libsf2d/include/sf2d_private.h index 76cf70d..07579ca 100644 --- a/libs/sf2dlib/libsf2d/include/sf2d_private.h +++ b/libs/sf2dlib/libsf2d/include/sf2d_private.h @@ -7,6 +7,8 @@ void GPU_SetDummyTexEnv(u8 num); +void sf2d_draw_rectangle_internal(const sf2d_vertex_pos_col *vertices); + // Vector operations void vector_mult_matrix4x4(const float *msrc, const sf2d_vector_3f *vsrc, sf2d_vector_3f *vdst); diff --git a/libs/sf2dlib/libsf2d/source/sf2d.c b/libs/sf2dlib/libsf2d/source/sf2d.c index 6f564fa..0b76e62 100644 --- a/libs/sf2dlib/libsf2d/source/sf2d.c +++ b/libs/sf2dlib/libsf2d/source/sf2d.c @@ -1,10 +1,11 @@ +#include #include "sf2d.h" #include "sf2d_private.h" #include "shader_vsh_shbin.h" static int sf2d_initialized = 0; -static u32 clear_color = RGBA8(0x00, 0x00, 0x00, 0xFF); +static u32 clear_color = 0; static u32 *gpu_cmd = NULL; //GPU init variables static int gpu_cmd_size = 0; @@ -32,10 +33,14 @@ static u32 projection_desc = -1; //Matrix static float ortho_matrix_top[4*4]; static float ortho_matrix_bot[4*4]; +//Rendertarget things +static sf2d_rendertarget * currentRenderTarget = NULL; +static void * targetDepthBuffer; +static int targetDepthBufferLen = 0; //Apt hook cookie static aptHookCookie apt_hook_cookie; //Functions -static void apt_hook_func(int hook, void* param); +static void apt_hook_func(APT_HookType hook, void *param); static void reset_gpu_apt_resume(); int sf2d_init() @@ -87,7 +92,7 @@ int sf2d_init_advanced(int gpucmd_size, int temppool_size) cur_side = GFX_LEFT; GPUCMD_Finalize(); - GPUCMD_FlushAndRun(NULL); + GPUCMD_FlushAndRun(); gspWaitForP3D(); sf2d_pool_reset(); @@ -111,6 +116,7 @@ int sf2d_fini() linearFree(gpu_cmd); vramFree(gpu_fb_addr); vramFree(gpu_depth_fb_addr); + linearFree(targetDepthBuffer); sf2d_initialized = 0; @@ -144,8 +150,8 @@ void sf2d_start_frame(gfxScreen_t screen, gfx3dSide_t side) } else { screen_w = 320; } - GPU_SetViewport((u32 *)osConvertVirtToPhys((u32)gpu_depth_fb_addr), - (u32 *)osConvertVirtToPhys((u32)gpu_fb_addr), + GPU_SetViewport((u32 *)osConvertVirtToPhys(gpu_depth_fb_addr), + (u32 *)osConvertVirtToPhys(gpu_fb_addr), 0, 0, 240, screen_w); GPU_DepthMap(-1.0f, 0.0f); @@ -154,8 +160,55 @@ void sf2d_start_frame(gfxScreen_t screen, gfx3dSide_t side) GPU_SetStencilOp(GPU_STENCIL_KEEP, GPU_STENCIL_KEEP, GPU_STENCIL_KEEP); GPU_SetBlendingColor(0,0,0,0); GPU_SetDepthTestAndWriteMask(true, GPU_GEQUAL, GPU_WRITE_ALL); - GPUCMD_AddMaskedWrite(GPUREG_0062, 0x1, 0); - GPUCMD_AddWrite(GPUREG_0118, 0); + GPUCMD_AddMaskedWrite(GPUREG_EARLYDEPTH_TEST1, 0x1, 0); + GPUCMD_AddWrite(GPUREG_EARLYDEPTH_TEST2, 0); + + GPU_SetAlphaBlending( + GPU_BLEND_ADD, + GPU_BLEND_ADD, + GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, + GPU_ONE, GPU_ZERO + ); + + GPU_SetAlphaTest(false, GPU_ALWAYS, 0x00); + + GPU_SetDummyTexEnv(1); + GPU_SetDummyTexEnv(2); + GPU_SetDummyTexEnv(3); + GPU_SetDummyTexEnv(4); + GPU_SetDummyTexEnv(5); +} + +void sf2d_start_frame_target(sf2d_rendertarget *target) +{ + sf2d_pool_reset(); + GPUCMD_SetBufferOffset(0); + + // Upload saved uniform + matrix_gpu_set_uniform(target->projection, projection_desc); + + int bufferLen = target->texture.width * target->texture.height * 4; // apparently depth buffer is (or can be) 32bit? + if (bufferLen > targetDepthBufferLen) { // expand depth buffer + if (targetDepthBufferLen > 0) linearFree(targetDepthBuffer); + targetDepthBuffer = linearAlloc(bufferLen); + memset(targetDepthBuffer, 0, bufferLen); + targetDepthBufferLen = bufferLen; + } + + GPU_SetViewport((u32 *)osConvertVirtToPhys(targetDepthBuffer), + (u32 *)osConvertVirtToPhys(target->texture.data), + 0, 0, target->texture.height, target->texture.width); + + currentRenderTarget = target; + + GPU_DepthMap(-1.0f, 0.0f); + GPU_SetFaceCulling(GPU_CULL_NONE); + GPU_SetStencilTest(false, GPU_ALWAYS, 0x00, 0xFF, 0x00); + GPU_SetStencilOp(GPU_STENCIL_KEEP, GPU_STENCIL_KEEP, GPU_STENCIL_KEEP); + GPU_SetBlendingColor(0,0,0,0); + GPU_SetDepthTestAndWriteMask(true, GPU_GEQUAL, GPU_WRITE_ALL); + GPUCMD_AddMaskedWrite(GPUREG_EARLYDEPTH_TEST1, 0x1, 0); + GPUCMD_AddWrite(GPUREG_EARLYDEPTH_TEST2, 0); GPU_SetAlphaBlending( GPU_BLEND_ADD, @@ -177,32 +230,40 @@ void sf2d_end_frame() { GPU_FinishDrawing(); GPUCMD_Finalize(); - GPUCMD_FlushAndRun(NULL); + GPUCMD_FlushAndRun(); gspWaitForP3D(); - //Copy the GPU rendered FB to the screen FB - if (cur_screen == GFX_TOP) { - GX_SetDisplayTransfer(NULL, gpu_fb_addr, GX_BUFFER_DIM(240, 400), - (u32 *)gfxGetFramebuffer(GFX_TOP, cur_side, NULL, NULL), - GX_BUFFER_DIM(240, 400), 0x1000); - } else { - GX_SetDisplayTransfer(NULL, gpu_fb_addr, GX_BUFFER_DIM(240, 320), - (u32 *)gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL), - GX_BUFFER_DIM(240, 320), 0x1000); - } - gspWaitForPPF(); + if (!currentRenderTarget) { + //Copy the GPU rendered FB to the screen FB + if (cur_screen == GFX_TOP) { + GX_DisplayTransfer(gpu_fb_addr, GX_BUFFER_DIM(240, 400), + (u32 *)gfxGetFramebuffer(GFX_TOP, cur_side, NULL, NULL), + GX_BUFFER_DIM(240, 400), 0x1000); + } else { + GX_DisplayTransfer(gpu_fb_addr, GX_BUFFER_DIM(240, 320), + (u32 *)gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL), + GX_BUFFER_DIM(240, 320), 0x1000); + } + gspWaitForPPF(); - //Clear the screen - GX_SetMemoryFill(NULL, gpu_fb_addr, clear_color, &gpu_fb_addr[0x2EE00], - 0x201, gpu_depth_fb_addr, 0x00000000, &gpu_depth_fb_addr[0x2EE00], 0x201); - gspWaitForPSC0(); + //Clear the screen + GX_MemoryFill( + gpu_fb_addr, clear_color, &gpu_fb_addr[240*400], GX_FILL_TRIGGER | GX_FILL_32BIT_DEPTH, + gpu_depth_fb_addr, 0, &gpu_depth_fb_addr[240*400], GX_FILL_TRIGGER | GX_FILL_32BIT_DEPTH); + gspWaitForPSC0(); + } else { + //gspWaitForPPF(); + //gspWaitForPSC0(); + sf2d_texture_tile32(&(currentRenderTarget->texture)); + } + currentRenderTarget = NULL; } void sf2d_swapbuffers() { gfxSwapBuffersGpu(); if (vblank_wait) { - gspWaitForEvent(GSPEVENT_VBlank0, false); + gspWaitForEvent(GSPGPU_EVENT_VBlank0, false); } //Calculate FPS frames++; @@ -245,6 +306,11 @@ void *sf2d_pool_memalign(u32 size, u32 alignment) return NULL; } +void *sf2d_pool_calloc(u32 nmemb, u32 size) +{ + return sf2d_pool_memalign(nmemb * size, size); +} + unsigned int sf2d_pool_space_free() { return pool_size - pool_index; @@ -257,7 +323,11 @@ void sf2d_pool_reset() void sf2d_set_clear_color(u32 color) { - clear_color = color; + // GX_SetMemoryFill wants the color inverted? + clear_color = RGBA8_GET_R(color) << 24 | + RGBA8_GET_G(color) << 16 | + RGBA8_GET_B(color) << 8 | + RGBA8_GET_A(color) << 0; } void sf2d_set_scissor_test(GPU_SCISSORMODE mode, u32 x, u32 y, u32 w, u32 h) @@ -279,7 +349,7 @@ gfx3dSide_t sf2d_get_current_side() return cur_side; } -static void apt_hook_func(int hook, void* param) +static void apt_hook_func(APT_HookType hook, void *param) { if (hook == APTHOOK_ONRESTORE) { reset_gpu_apt_resume(); @@ -298,6 +368,6 @@ static void reset_gpu_apt_resume() } GPUCMD_Finalize(); - GPUCMD_FlushAndRun(NULL); + GPUCMD_FlushAndRun(); gspWaitForP3D(); } diff --git a/libs/sf2dlib/libsf2d/source/sf2d_draw.c b/libs/sf2dlib/libsf2d/source/sf2d_draw.c index bf8f896..a28e818 100644 --- a/libs/sf2dlib/libsf2d/source/sf2d_draw.c +++ b/libs/sf2dlib/libsf2d/source/sf2d_draw.c @@ -2,26 +2,11 @@ #include "sf2d_private.h" #include -void sf2d_draw_line(int x0, int y0, int x1, int y1, u32 color) -{ - sf2d_vertex_pos_col *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_col)); - if (!vertices) return; - - vertices[0].position = (sf2d_vector_3f){(float)x0+1.0f, (float)y0+1.0f, SF2D_DEFAULT_DEPTH}; - vertices[1].position = (sf2d_vector_3f){(float)x0-1.0f, (float)y0-1.0f, SF2D_DEFAULT_DEPTH}; - vertices[2].position = (sf2d_vector_3f){(float)x1+1.0f, (float)y1+1.0f, SF2D_DEFAULT_DEPTH}; - vertices[3].position = (sf2d_vector_3f){(float)x1-1.0f, (float)y1-1.0f, SF2D_DEFAULT_DEPTH}; - - u8 r = (color>>24) & 0xFF; - u8 g = (color>>16) & 0xFF; - u8 b = (color>>8) & 0xFF; - u8 a = color & 0xFF; - - vertices[0].color = (sf2d_vector_4f){r/255.0f, g/255.0f, b/255.0f, a/255.0f}; - vertices[1].color = vertices[0].color; - vertices[2].color = vertices[0].color; - vertices[3].color = vertices[0].color; +#ifndef M_PI +#define M_PI (3.14159265358979323846) +#endif +void sf2d_setup_env_internal(const sf2d_vertex_pos_col* vertices) { GPU_SetTexEnv( 0, GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR), @@ -34,8 +19,8 @@ void sf2d_draw_line(int x0, int y0, int x1, int y1, u32 color) GPU_SetAttributeBuffers( 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), - GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_FLOAT), + (u32*)osConvertVirtToPhys(vertices), + GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_UNSIGNED_BYTE), 0xFFFC, //0b1100 0x10, 1, //number of buffers @@ -43,13 +28,62 @@ void sf2d_draw_line(int x0, int y0, int x1, int y1, u32 color) (u64[]){0x10}, // attribute permutations for each buffer (u8[]){2} // number of attributes for each buffer ); +} + +void sf2d_draw_line(float x0, float y0, float x1, float y1, float width, u32 color) +{ + sf2d_vertex_pos_col *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_col), 8); + if (!vertices) return; + + float dx = x1 - x0; + float dy = y1 - y0; + + float nx = -dy; + float ny = dx; + + float len = sqrt(nx * nx + ny * ny); + + if (len > 0 ){ + nx /= len; + ny /= len; + } + + nx *= width*0.5f; + ny *= width*0.5f; + + vertices[0].position = (sf2d_vector_3f){x0+nx, y0+ny, SF2D_DEFAULT_DEPTH}; + vertices[1].position = (sf2d_vector_3f){x0-nx, y0-ny, SF2D_DEFAULT_DEPTH}; + + vertices[2].position = (sf2d_vector_3f){x1+nx, y1+ny, SF2D_DEFAULT_DEPTH}; + vertices[3].position = (sf2d_vector_3f){x1-nx, y1-ny, SF2D_DEFAULT_DEPTH}; + + vertices[0].color = color; + vertices[1].color = vertices[0].color; + vertices[2].color = vertices[0].color; + vertices[3].color = vertices[0].color; + + sf2d_setup_env_internal(vertices); GPU_DrawArray(GPU_TRIANGLE_STRIP, 0, 4); } +void sf2d_draw_rectangle_internal(const sf2d_vertex_pos_col *vertices) +{ + sf2d_setup_env_internal(vertices); + + GPU_DrawArray(GPU_TRIANGLE_STRIP, 0, 4); +} + +void sf2d_draw_triangle_internal(const sf2d_vertex_pos_col *vertices) +{ + sf2d_setup_env_internal(vertices); + + GPU_DrawArray(GPU_TRIANGLES, 0, 3); +} + void sf2d_draw_rectangle(int x, int y, int w, int h, u32 color) { - sf2d_vertex_pos_col *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_col)); + sf2d_vertex_pos_col *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_col), 8); if (!vertices) return; vertices[0].position = (sf2d_vector_3f){(float)x, (float)y, SF2D_DEFAULT_DEPTH}; @@ -57,44 +91,33 @@ void sf2d_draw_rectangle(int x, int y, int w, int h, u32 color) vertices[2].position = (sf2d_vector_3f){(float)x, (float)y+h, SF2D_DEFAULT_DEPTH}; vertices[3].position = (sf2d_vector_3f){(float)x+w, (float)y+h, SF2D_DEFAULT_DEPTH}; - u8 r = (color>>24) & 0xFF; - u8 g = (color>>16) & 0xFF; - u8 b = (color>>8) & 0xFF; - u8 a = color & 0xFF; - - vertices[0].color = (sf2d_vector_4f){r/255.0f, g/255.0f, b/255.0f, a/255.0f}; + vertices[0].color = color; vertices[1].color = vertices[0].color; vertices[2].color = vertices[0].color; vertices[3].color = vertices[0].color; - GPU_SetTexEnv( - 0, - GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR), - GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR), - GPU_TEVOPERANDS(0, 0, 0), - GPU_TEVOPERANDS(0, 0, 0), - GPU_REPLACE, GPU_REPLACE, - 0xFFFFFFFF - ); + sf2d_draw_rectangle_internal(vertices); +} - GPU_SetAttributeBuffers( - 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), - GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_FLOAT), - 0xFFFC, //0b1100 - 0x10, - 1, //number of buffers - (u32[]){0x0}, // buffer offsets (placeholders) - (u64[]){0x10}, // attribute permutations for each buffer - (u8[]){2} // number of attributes for each buffer - ); +void sf2d_draw_triangle(float x1, float y1, float x2, float y2, float x3, float y3, u32 color) +{ + sf2d_vertex_pos_col *vertices = sf2d_pool_memalign(3 * sizeof(sf2d_vertex_pos_col), 8); + if (!vertices) return; - GPU_DrawArray(GPU_TRIANGLE_STRIP, 0, 4); + vertices[0].position = (sf2d_vector_3f){(float)x1, (float)y1, SF2D_DEFAULT_DEPTH}; + vertices[1].position = (sf2d_vector_3f){(float)x2, (float)y2, SF2D_DEFAULT_DEPTH}; + vertices[2].position = (sf2d_vector_3f){(float)x3, (float)y3, SF2D_DEFAULT_DEPTH}; + + vertices[0].color = color; + vertices[1].color = vertices[0].color; + vertices[2].color = vertices[0].color; + + sf2d_draw_triangle_internal(vertices); } void sf2d_draw_rectangle_rotate(int x, int y, int w, int h, u32 color, float rad) { - sf2d_vertex_pos_col *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_col)); + sf2d_vertex_pos_col *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_col), 8); if (!vertices) return; int w2 = w/2.0f; @@ -105,12 +128,7 @@ void sf2d_draw_rectangle_rotate(int x, int y, int w, int h, u32 color, float rad vertices[2].position = (sf2d_vector_3f){(float)-w2, (float) h2, SF2D_DEFAULT_DEPTH}; vertices[3].position = (sf2d_vector_3f){(float) w2, (float) h2, SF2D_DEFAULT_DEPTH}; - u8 r = (color>>24) & 0xFF; - u8 g = (color>>16) & 0xFF; - u8 b = (color>>8) & 0xFF; - u8 a = color & 0xFF; - - vertices[0].color = (sf2d_vector_4f){r/255.0f, g/255.0f, b/255.0f, a/255.0f}; + vertices[0].color = color; vertices[1].color = vertices[0].color; vertices[2].color = vertices[0].color; vertices[3].color = vertices[0].color; @@ -125,45 +143,66 @@ void sf2d_draw_rectangle_rotate(int x, int y, int w, int h, u32 color, float rad vertices[i].position = (sf2d_vector_3f){rot[i].x + x + w2, rot[i].y + y + h2, rot[i].z}; } - GPU_SetTexEnv( - 0, - GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR), - GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR), - GPU_TEVOPERANDS(0, 0, 0), - GPU_TEVOPERANDS(0, 0, 0), - GPU_REPLACE, GPU_REPLACE, - 0xFFFFFFFF - ); + sf2d_draw_rectangle_internal(vertices); +} - GPU_SetAttributeBuffers( - 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), - GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_FLOAT), - 0xFFFC, //0b1100 - 0x10, - 1, //number of buffers - (u32[]){0x0}, // buffer offsets (placeholders) - (u64[]){0x10}, // attribute permutations for each buffer - (u8[]){2} // number of attributes for each buffer - ); +void sf2d_draw_rectangle_gradient(int x, int y, int w, int h, u32 color1, u32 color2, sf2d_gradient_dir direction) +{ + sf2d_vertex_pos_col *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_col), 8); + if (!vertices) return; - GPU_DrawArray(GPU_TRIANGLE_STRIP, 0, 4); + vertices[0].position = (sf2d_vector_3f){(float)x, (float)y, SF2D_DEFAULT_DEPTH}; + vertices[1].position = (sf2d_vector_3f){(float)x+w, (float)y, SF2D_DEFAULT_DEPTH}; + vertices[2].position = (sf2d_vector_3f){(float)x, (float)y+h, SF2D_DEFAULT_DEPTH}; + vertices[3].position = (sf2d_vector_3f){(float)x+w, (float)y+h, SF2D_DEFAULT_DEPTH}; + + vertices[0].color = color1; + vertices[1].color = (direction == SF2D_LEFT_TO_RIGHT) ? color2 : color1; + vertices[2].color = (direction == SF2D_LEFT_TO_RIGHT) ? color1 : color2; + vertices[3].color = color2; + + sf2d_draw_rectangle_internal(vertices); +} + +void sf2d_draw_rectangle_gradient_rotate(int x, int y, int w, int h, u32 color1, u32 color2, sf2d_gradient_dir direction, float rad) +{ + sf2d_vertex_pos_col *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_col), 8); + if (!vertices) return; + + int w2 = w/2.0f; + int h2 = h/2.0f; + + vertices[0].position = (sf2d_vector_3f){(float)-w2, (float)-h2, SF2D_DEFAULT_DEPTH}; + vertices[1].position = (sf2d_vector_3f){(float) w2, (float)-h2, SF2D_DEFAULT_DEPTH}; + vertices[2].position = (sf2d_vector_3f){(float)-w2, (float) h2, SF2D_DEFAULT_DEPTH}; + vertices[3].position = (sf2d_vector_3f){(float) w2, (float) h2, SF2D_DEFAULT_DEPTH}; + + vertices[0].color = color1; + vertices[1].color = (direction == SF2D_LEFT_TO_RIGHT) ? color2 : color1; + vertices[2].color = (direction == SF2D_LEFT_TO_RIGHT) ? color1 : color2; + vertices[3].color = color2; + + float m[4*4]; + matrix_set_z_rotation(m, rad); + sf2d_vector_3f rot[4]; + + int i; + for (i = 0; i < 4; i++) { + vector_mult_matrix4x4(m, &vertices[i].position, &rot[i]); + vertices[i].position = (sf2d_vector_3f){rot[i].x + x + w2, rot[i].y + y + h2, rot[i].z}; + } + + sf2d_draw_rectangle_internal(vertices); } void sf2d_draw_fill_circle(int x, int y, int radius, u32 color) { static const int num_segments = 100; - sf2d_vertex_pos_col *vertices = sf2d_pool_malloc((num_segments + 2) * sizeof(sf2d_vertex_pos_col)); + sf2d_vertex_pos_col *vertices = sf2d_pool_memalign((num_segments + 2) * sizeof(sf2d_vertex_pos_col), 8); if (!vertices) return; vertices[0].position = (sf2d_vector_3f){(float)x, (float)y, SF2D_DEFAULT_DEPTH}; - - u8 r = (color>>24) & 0xFF; - u8 g = (color>>16) & 0xFF; - u8 b = (color>>8) & 0xFF; - u8 a = color & 0xFF; - - vertices[0].color = (sf2d_vector_4f){r/255.0f, g/255.0f, b/255.0f, a/255.0f}; + vertices[0].color = color; float theta = 2 * M_PI / (float)num_segments; float c = cosf(theta); @@ -186,27 +225,7 @@ void sf2d_draw_fill_circle(int x, int y, int radius, u32 color) vertices[num_segments + 1].position = vertices[1].position; vertices[num_segments + 1].color = vertices[1].color; - GPU_SetTexEnv( - 0, - GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR), - GPU_TEVSOURCES(GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR), - GPU_TEVOPERANDS(0, 0, 0), - GPU_TEVOPERANDS(0, 0, 0), - GPU_REPLACE, GPU_REPLACE, - 0xFFFFFFFF - ); - - GPU_SetAttributeBuffers( - 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), - GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 4, GPU_FLOAT), - 0xFFFC, //0b1100 - 0x10, - 1, //number of buffers - (u32[]){0x0}, // buffer offsets (placeholders) - (u64[]){0x10}, // attribute permutations for each buffer - (u8[]){2} // number of attributes for each buffer - ); + sf2d_setup_env_internal(vertices); GPU_DrawArray(GPU_TRIANGLE_FAN, 0, num_segments + 2); } diff --git a/libs/sf2dlib/libsf2d/source/sf2d_private.c b/libs/sf2dlib/libsf2d/source/sf2d_private.c index 44819a0..30b0ed8 100644 --- a/libs/sf2dlib/libsf2d/source/sf2d_private.c +++ b/libs/sf2dlib/libsf2d/source/sf2d_private.c @@ -2,6 +2,10 @@ #include #include "sf2d_private.h" +#ifndef M_PI +#define M_PI (3.14159265358979323846) +#endif + //stolen from staplebutt void GPU_SetDummyTexEnv(u8 num) { @@ -24,16 +28,7 @@ void vector_mult_matrix4x4(const float *msrc, const sf2d_vector_3f *vsrc, sf2d_v void matrix_gpu_set_uniform(const float *m, u32 startreg) { - float mu[4*4]; - - int i, j; - for (i = 0; i < 4; i++) { - for (j = 0; j < 4; j++) { - mu[i*4 + j] = m[i*4 + (3-j)]; - } - } - - GPU_SetFloatUniform(GPU_VERTEX_SHADER, startreg, (u32 *)mu, 4); + GPU_SetFloatUniform(GPU_VERTEX_SHADER, startreg, (u32 *)m, 4); } void matrix_copy(float *dst, const float *src) @@ -109,7 +104,7 @@ void matrix_swap_xy(float *m) void matrix_init_orthographic(float *m, float left, float right, float bottom, float top, float near, float far) { float mo[4*4], mp[4*4]; - + mo[0x0] = 2.0f/(right-left); mo[0x1] = 0.0f; mo[0x2] = 0.0f; @@ -129,7 +124,7 @@ void matrix_init_orthographic(float *m, float left, float right, float bottom, f mo[0xD] = 0.0f; mo[0xE] = 0.0f; mo[0xF] = 1.0f; - + matrix_identity4x4(mp); mp[0xA] = 0.5; mp[0xB] = -0.5; diff --git a/libs/sf2dlib/libsf2d/source/sf2d_texture.c b/libs/sf2dlib/libsf2d/source/sf2d_texture.c index 2dc9fce..d0b7f09 100644 --- a/libs/sf2dlib/libsf2d/source/sf2d_texture.c +++ b/libs/sf2dlib/libsf2d/source/sf2d_texture.c @@ -4,7 +4,11 @@ #include "sf2d.h" #include "sf2d_private.h" -#define TEX_MIN_SIZE 8 +#ifndef M_PI +#define M_PI (3.14159265358979323846) +#endif + +#define TEX_MIN_SIZE 32 static unsigned int nibbles_per_pixel(sf2d_texfmt format) { @@ -71,6 +75,10 @@ sf2d_texture *sf2d_create_texture(int width, int height, sf2d_texfmt pixel_forma texture->tiled = 0; texture->place = place; texture->pixel_format = pixel_format; + texture->params = GPU_TEXTURE_MAG_FILTER(GPU_NEAREST) + | GPU_TEXTURE_MIN_FILTER(GPU_NEAREST) + | GPU_TEXTURE_WRAP_S(GPU_CLAMP_TO_BORDER) + | GPU_TEXTURE_WRAP_T(GPU_CLAMP_TO_BORDER); texture->width = width; texture->height = height; texture->pow2_w = pow2_w; @@ -79,7 +87,7 @@ sf2d_texture *sf2d_create_texture(int width, int height, sf2d_texfmt pixel_forma texture->data = data; if (place == SF2D_PLACE_VRAM) { - GX_SetMemoryFill(NULL, texture->data, 0x00000000, (u32*)&((u8*)texture->data)[texture->data_size], GX_FILL_TRIGGER | GX_FILL_32BIT_DEPTH, + GX_MemoryFill(texture->data, 0x00000000, (u32*)&((u8*)texture->data)[texture->data_size], GX_FILL_TRIGGER | GX_FILL_32BIT_DEPTH, NULL, 0x00000000, NULL, 0); gspWaitForPSC0(); } else { @@ -89,6 +97,22 @@ sf2d_texture *sf2d_create_texture(int width, int height, sf2d_texfmt pixel_forma return texture; } +sf2d_rendertarget *sf2d_create_rendertarget(int width, int height) +{ + sf2d_texture *tx = sf2d_create_texture(width, height, TEXFMT_RGBA8, SF2D_PLACE_RAM); + sf2d_rendertarget *rt = malloc(sizeof(*rt)); + //memcpy(rt, tx, sizeof(*tx)); + rt->texture = *tx; + free(tx); + //tx = * rt->texture; + //rt->projection + + matrix_init_orthographic(rt->projection, 0.0f, width, height, 0.0f, 0.0f, 1.0f); + matrix_rotate_z(rt->projection, M_PI / 2.0f); + + return rt; +} + void sf2d_free_texture(sf2d_texture *texture) { if (texture) { @@ -101,21 +125,61 @@ void sf2d_free_texture(sf2d_texture *texture) } } +void sf2d_free_target(sf2d_rendertarget *target) +{ + sf2d_free_texture(&(target->texture)); + //free(target); // unnecessary since the texture is the start of the target struct +} + +void sf2d_clear_target(sf2d_rendertarget *target, u32 color) { + if (color == 0) { // if fully transparent, take a shortcut + memset(target->texture.data, 0, target->texture.width * target->texture.height * 4); + sf2d_texture_tile32(&(target->texture)); + return; + } + + color = ((color>>24)&0x000000FF) | ((color>>8)&0x0000FF00) | ((color<<8)&0x00FF0000) | ((color<<24)&0xFF000000); // reverse byte order + + int itarget = target->texture.width * target->texture.height; + for (int i = 0; i < itarget; i++) { memcpy(target->texture.data + i*4, &color, 4); } + + sf2d_texture_tile32(&(target->texture)); +} + +void sf2d_texture_tile32_hardware(sf2d_texture *texture, const void *data, int w, int h) +{ + if (texture->tiled) return; + const u32 flags = (GX_TRANSFER_FLIP_VERT(1) | GX_TRANSFER_OUT_TILED(1) | GX_TRANSFER_RAW_COPY(0) | + GX_TRANSFER_IN_FORMAT(GX_TRANSFER_FMT_RGBA8) | GX_TRANSFER_OUT_FORMAT(GX_TRANSFER_FMT_RGBA8) | + GX_TRANSFER_SCALING(GX_TRANSFER_SCALE_NO)); + + GSPGPU_FlushDataCache(data, (w*h)<<2); + GX_DisplayTransfer( + (u32*)data, + GX_BUFFER_DIM(w, h), + (u32*)texture->data, + GX_BUFFER_DIM(texture->pow2_w, texture->pow2_h), + flags + ); + gspWaitForPPF(); + GSPGPU_InvalidateDataCache(texture->data, texture->data_size); + texture->tiled = 1; +} + void sf2d_fill_texture_from_RGBA8(sf2d_texture *dst, const void *rgba8, int source_w, int source_h) { // TODO: add support for non-RGBA8 textures - u8 *tmp = linearAlloc(dst->pow2_w * dst->pow2_h * 4); + u8 *tmp = linearAlloc((dst->pow2_w * dst->pow2_h)<<2); int i, j; for (i = 0; i < source_h; i++) { for (j = 0; j < source_w; j++) { - ((u32 *)tmp)[i*dst->pow2_w + j] = ((u32 *)rgba8)[i*source_w + j]; + ((u32 *)tmp)[i*dst->pow2_w + j] = __builtin_bswap32(((u32 *)rgba8)[i*source_w + j]); } } - memcpy(dst->data, tmp, dst->pow2_w*dst->pow2_h*4); + sf2d_texture_tile32_hardware(dst, tmp, dst->pow2_w, dst->pow2_h); linearFree(tmp); - sf2d_texture_tile32(dst); } sf2d_texture *sf2d_create_texture_mem_RGBA8(const void *src_buffer, int src_w, int src_h, sf2d_texfmt pixel_format, sf2d_place place) @@ -142,10 +206,10 @@ void sf2d_bind_texture(const sf2d_texture *texture, GPU_TEXUNIT unit) GPU_SetTexture( unit, - (u32 *)osConvertVirtToPhys((u32)texture->data), + (u32 *)osConvertVirtToPhys(texture->data), texture->pow2_w, texture->pow2_h, - GPU_TEXTURE_MAG_FILTER(GPU_NEAREST) | GPU_TEXTURE_MIN_FILTER(GPU_NEAREST), + texture->params, texture->pixel_format ); } @@ -161,15 +225,15 @@ void sf2d_bind_texture_color(const sf2d_texture *texture, GPU_TEXUNIT unit, u32 GPU_TEVOPERANDS(0, 0, 0), GPU_TEVOPERANDS(0, 0, 0), GPU_MODULATE, GPU_MODULATE, - __builtin_bswap32(color) //RGBA8 -> ABGR8 + color ); GPU_SetTexture( unit, - (u32 *)osConvertVirtToPhys((u32)texture->data), + (u32 *)osConvertVirtToPhys(texture->data), texture->pow2_w, texture->pow2_h, - GPU_TEXTURE_MAG_FILTER(GPU_NEAREST) | GPU_TEXTURE_MIN_FILTER(GPU_NEAREST), + texture->params, texture->pixel_format ); } @@ -190,7 +254,7 @@ void sf2d_bind_texture_parameters(const sf2d_texture *texture, GPU_TEXUNIT unit, GPU_SetTexture( unit, - (u32 *)osConvertVirtToPhys((u32)texture->data), + (u32 *)osConvertVirtToPhys(texture->data), texture->pow2_w, texture->pow2_h, params, @@ -198,9 +262,19 @@ void sf2d_bind_texture_parameters(const sf2d_texture *texture, GPU_TEXUNIT unit, ); } +void sf2d_texture_set_params(sf2d_texture *texture, u32 params) +{ + texture->params = params; +} + +int sf2d_texture_get_params(const sf2d_texture *texture) +{ + return texture->params; +} + static inline void sf2d_draw_texture_generic(const sf2d_texture *texture, int x, int y) { - sf2d_vertex_pos_tex *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_tex)); + sf2d_vertex_pos_tex *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_tex), 8); if (!vertices) return; int w = texture->width; @@ -221,7 +295,7 @@ static inline void sf2d_draw_texture_generic(const sf2d_texture *texture, int x, GPU_SetAttributeBuffers( 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), + (u32*)osConvertVirtToPhys(vertices), GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 2, GPU_FLOAT), 0xFFFC, //0b1100 0x10, @@ -248,7 +322,7 @@ void sf2d_draw_texture_blend(const sf2d_texture *texture, int x, int y, u32 colo static inline void sf2d_draw_texture_rotate_hotspot_generic(const sf2d_texture *texture, int x, int y, float rad, float center_x, float center_y) { - sf2d_vertex_pos_tex *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_tex)); + sf2d_vertex_pos_tex *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_tex), 8); if (!vertices) return; const float w = texture->width; @@ -290,7 +364,7 @@ static inline void sf2d_draw_texture_rotate_hotspot_generic(const sf2d_texture * GPU_SetAttributeBuffers( 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), + (u32*)osConvertVirtToPhys(vertices), GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 2, GPU_FLOAT), 0xFFFC, //0b1100 0x10, @@ -330,9 +404,78 @@ void sf2d_draw_texture_rotate_blend(const sf2d_texture *texture, int x, int y, f color); } +static inline void sf2d_draw_texture_rotate_scale_hotspot_generic(const sf2d_texture *texture, int x, int y, float rad, float scale_x, float scale_y, float center_x, float center_y) +{ + sf2d_vertex_pos_tex *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_tex), 8); + if (!vertices) return; + + const float w = texture->width; + const float h = texture->height; + + vertices[0].position.x = -center_x * scale_x; + vertices[0].position.y = -center_y * scale_y; + vertices[0].position.z = SF2D_DEFAULT_DEPTH; + + vertices[1].position.x = (w - center_x) * scale_x; + vertices[1].position.y = -center_y * scale_y; + vertices[1].position.z = SF2D_DEFAULT_DEPTH; + + vertices[2].position.x = -center_x * scale_x; + vertices[2].position.y = (h - center_y) * scale_y; + vertices[2].position.z = SF2D_DEFAULT_DEPTH; + + vertices[3].position.x = (w - center_x) * scale_x; + vertices[3].position.y = h - center_y * scale_y; + vertices[3].position.z = SF2D_DEFAULT_DEPTH; + + float u = w/(float)texture->pow2_w; + float v = h/(float)texture->pow2_h; + + vertices[0].texcoord = (sf2d_vector_2f){0.0f, 0.0f}; + vertices[1].texcoord = (sf2d_vector_2f){u, 0.0f}; + vertices[2].texcoord = (sf2d_vector_2f){0.0f, v}; + vertices[3].texcoord = (sf2d_vector_2f){u, v}; + + const float c = cosf(rad); + const float s = sinf(rad); + int i; + for (i = 0; i < 4; ++i) { // Rotate and translate + float _x = vertices[i].position.x; + float _y = vertices[i].position.y; + vertices[i].position.x = _x*c - _y*s + x; + vertices[i].position.y = _x*s + _y*c + y; + } + + GPU_SetAttributeBuffers( + 2, // number of attributes + (u32*)osConvertVirtToPhys(vertices), + GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 2, GPU_FLOAT), + 0xFFFC, //0b1100 + 0x10, + 1, //number of buffers + (u32[]){0x0}, // buffer offsets (placeholders) + (u64[]){0x10}, // attribute permutations for each buffer + (u8[]){2} // number of attributes for each buffer + ); + + GPU_DrawArray(GPU_TRIANGLE_STRIP, 0, 4); +} + +void sf2d_draw_texture_rotate_scale_hotspot(const sf2d_texture *texture, int x, int y, float rad, float scale_x, float scale_y, float center_x, float center_y) +{ + sf2d_bind_texture(texture, GPU_TEXUNIT0); + sf2d_draw_texture_rotate_scale_hotspot_generic(texture, x, y, rad, scale_x, scale_y, center_x, center_y); +} + +void sf2d_draw_texture_rotate_scale_hotspot_blend(const sf2d_texture *texture, int x, int y, float rad, float scale_x, float scale_y, float center_x, float center_y, u32 color) +{ + sf2d_bind_texture_color(texture, GPU_TEXUNIT0, color); + sf2d_draw_texture_rotate_scale_hotspot_generic(texture, x, y, rad, scale_x, scale_y, center_x, center_y); +} + static inline void sf2d_draw_texture_part_generic(const sf2d_texture *texture, int x, int y, int tex_x, int tex_y, int tex_w, int tex_h) { - sf2d_vertex_pos_tex *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_tex)); + sf2d_vertex_pos_tex *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_tex), 8); if (!vertices) return; vertices[0].position = (sf2d_vector_3f){(float)x, (float)y, SF2D_DEFAULT_DEPTH}; @@ -352,7 +495,7 @@ static inline void sf2d_draw_texture_part_generic(const sf2d_texture *texture, i GPU_SetAttributeBuffers( 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), + (u32*)osConvertVirtToPhys(vertices), GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 2, GPU_FLOAT), 0xFFFC, //0b1100 0x10, @@ -379,7 +522,7 @@ void sf2d_draw_texture_part_blend(const sf2d_texture *texture, int x, int y, int static inline void sf2d_draw_texture_scale_generic(const sf2d_texture *texture, int x, int y, float x_scale, float y_scale) { - sf2d_vertex_pos_tex *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_tex)); + sf2d_vertex_pos_tex *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_tex), 8); if (!vertices) return; int ws = texture->width * x_scale; @@ -400,7 +543,7 @@ static inline void sf2d_draw_texture_scale_generic(const sf2d_texture *texture, GPU_SetAttributeBuffers( 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), + (u32*)osConvertVirtToPhys(vertices), GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 2, GPU_FLOAT), 0xFFFC, //0b1100 0x10, @@ -427,7 +570,7 @@ void sf2d_draw_texture_scale_blend(const sf2d_texture *texture, int x, int y, fl static inline void sf2d_draw_texture_part_scale_generic(const sf2d_texture *texture, float x, float y, float tex_x, float tex_y, float tex_w, float tex_h, float x_scale, float y_scale) { - sf2d_vertex_pos_tex *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_tex)); + sf2d_vertex_pos_tex *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_tex), 8); if (!vertices) return; float u0 = tex_x/(float)texture->pow2_w; @@ -450,7 +593,7 @@ static inline void sf2d_draw_texture_part_scale_generic(const sf2d_texture *text GPU_SetAttributeBuffers( 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), + (u32*)osConvertVirtToPhys(vertices), GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 2, GPU_FLOAT), 0xFFFC, //0b1100 0x10, @@ -475,18 +618,18 @@ void sf2d_draw_texture_part_scale_blend(const sf2d_texture *texture, float x, fl sf2d_draw_texture_part_scale_generic(texture, x, y, tex_x, tex_y, tex_w, tex_h, x_scale, y_scale); } -static inline void sf2d_draw_texture_part_rotate_scale_generic(const sf2d_texture *texture, int x, int y, float rad, int tex_x, int tex_y, int tex_w, int tex_h, float x_scale, float y_scale) +static inline void sf2d_draw_texture_part_rotate_scale_hotspot_generic(const sf2d_texture *texture, int x, int y, float rad, int tex_x, int tex_y, int tex_w, int tex_h, float x_scale, float y_scale, float center_x, float center_y) { - sf2d_vertex_pos_tex *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_tex)); + sf2d_vertex_pos_tex *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_tex), 8); if (!vertices) return; - int w2 = (tex_w * x_scale)/2.0f; - int h2 = (tex_h * y_scale)/2.0f; + int w = tex_w; + int h = tex_h; - vertices[0].position = (sf2d_vector_3f){(float)-w2, (float)-h2, SF2D_DEFAULT_DEPTH}; - vertices[1].position = (sf2d_vector_3f){(float) w2, (float)-h2, SF2D_DEFAULT_DEPTH}; - vertices[2].position = (sf2d_vector_3f){(float)-w2, (float) h2, SF2D_DEFAULT_DEPTH}; - vertices[3].position = (sf2d_vector_3f){(float) w2, (float) h2, SF2D_DEFAULT_DEPTH}; + vertices[0].position = (sf2d_vector_3f){(float)-center_x * x_scale, (float)-center_y * y_scale, SF2D_DEFAULT_DEPTH}; + vertices[1].position = (sf2d_vector_3f){(float) (w - center_x) * x_scale, (float)-center_y * y_scale, SF2D_DEFAULT_DEPTH}; + vertices[2].position = (sf2d_vector_3f){(float)-center_x * x_scale, (float) (h - center_y) * y_scale, SF2D_DEFAULT_DEPTH}; + vertices[3].position = (sf2d_vector_3f){(float) (w - center_x) * x_scale, (float) h - center_y * y_scale, SF2D_DEFAULT_DEPTH}; float u0 = tex_x/(float)texture->pow2_w; float v0 = tex_y/(float)texture->pow2_h; @@ -510,7 +653,7 @@ static inline void sf2d_draw_texture_part_rotate_scale_generic(const sf2d_textur GPU_SetAttributeBuffers( 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), + (u32*)osConvertVirtToPhys(vertices), GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 2, GPU_FLOAT), 0xFFFC, //0b1100 0x10, @@ -526,18 +669,24 @@ static inline void sf2d_draw_texture_part_rotate_scale_generic(const sf2d_textur void sf2d_draw_texture_part_rotate_scale(const sf2d_texture *texture, int x, int y, float rad, int tex_x, int tex_y, int tex_w, int tex_h, float x_scale, float y_scale) { sf2d_bind_texture(texture, GPU_TEXUNIT0); - sf2d_draw_texture_part_rotate_scale_generic(texture, x, y, rad, tex_x, tex_y, tex_w, tex_h, x_scale, y_scale); + sf2d_draw_texture_part_rotate_scale_hotspot_generic(texture, x, y, rad, tex_x, tex_y, tex_w, tex_h, x_scale, y_scale, tex_w/2.0f, tex_h/2.0f); } void sf2d_draw_texture_part_rotate_scale_blend(const sf2d_texture *texture, int x, int y, float rad, int tex_x, int tex_y, int tex_w, int tex_h, float x_scale, float y_scale, u32 color) { sf2d_bind_texture_color(texture, GPU_TEXUNIT0, color); - sf2d_draw_texture_part_rotate_scale_generic(texture, x, y, rad, tex_x, tex_y, tex_w, tex_h, x_scale, y_scale); + sf2d_draw_texture_part_rotate_scale_hotspot_generic(texture, x, y, rad, tex_x, tex_y, tex_w, tex_h, x_scale, y_scale, tex_w/2.0f, tex_h/2.0f); +} + +void sf2d_draw_texture_part_rotate_scale_hotspot_blend(const sf2d_texture *texture, int x, int y, float rad, int tex_x, int tex_y, int tex_w, int tex_h, float x_scale, float y_scale, float center_x, float center_y, u32 color) +{ + sf2d_bind_texture_color(texture, GPU_TEXUNIT0, color); + sf2d_draw_texture_part_rotate_scale_hotspot_generic(texture, x, y, rad, tex_x, tex_y, tex_w, tex_h, x_scale, y_scale, center_x, center_y); } static inline void sf2d_draw_texture_depth_generic(const sf2d_texture *texture, int x, int y, signed short z) { - sf2d_vertex_pos_tex *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_tex)); + sf2d_vertex_pos_tex *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_tex), 8); if (!vertices) return; int w = texture->width; @@ -559,7 +708,7 @@ static inline void sf2d_draw_texture_depth_generic(const sf2d_texture *texture, GPU_SetAttributeBuffers( 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), + (u32*)osConvertVirtToPhys(vertices), GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 2, GPU_FLOAT), 0xFFFC, //0b1100 0x10, @@ -587,7 +736,7 @@ void sf2d_draw_texture_depth_blend(const sf2d_texture *texture, int x, int y, si void sf2d_draw_quad_uv(const sf2d_texture *texture, float left, float top, float right, float bottom, float u0, float v0, float u1, float v1, unsigned int params) { - sf2d_vertex_pos_tex *vertices = sf2d_pool_malloc(4 * sizeof(sf2d_vertex_pos_tex)); + sf2d_vertex_pos_tex *vertices = sf2d_pool_memalign(4 * sizeof(sf2d_vertex_pos_tex), 8); if (!vertices) return; vertices[0].position = (sf2d_vector_3f){left, top, SF2D_DEFAULT_DEPTH}; @@ -604,7 +753,7 @@ void sf2d_draw_quad_uv(const sf2d_texture *texture, float left, float top, float GPU_SetAttributeBuffers( 2, // number of attributes - (u32*)osConvertVirtToPhys((u32)vertices), + (u32*)osConvertVirtToPhys(vertices), GPU_ATTRIBFMT(0, 3, GPU_FLOAT) | GPU_ATTRIBFMT(1, 2, GPU_FLOAT), 0xFFFC, //0b1100 0x10, @@ -641,9 +790,9 @@ void sf2d_set_pixel(sf2d_texture *texture, int x, int y, u32 new_color) if (texture->tiled) { u32 coarse_y = y & ~7; u32 offset = get_morton_offset(x, y, 4) + coarse_y * texture->pow2_w * 4; - *(u32 *)(texture->data + offset) = __builtin_bswap32(new_color); + *(u32 *)(texture->data + offset) = new_color; } else { - ((u32 *)texture->data)[x + y * texture->pow2_w] = __builtin_bswap32(new_color); + ((u32 *)texture->data)[x + y * texture->pow2_w] = new_color; } } @@ -653,9 +802,9 @@ u32 sf2d_get_pixel(sf2d_texture *texture, int x, int y) if (texture->tiled) { u32 coarse_y = y & ~7; u32 offset = get_morton_offset(x, y, 4) + coarse_y * texture->pow2_w * 4; - return __builtin_bswap32(*(u32 *)(texture->data + offset)); + return *(u32 *)(texture->data + offset); } else { - return __builtin_bswap32(((u32 *)texture->data)[x + y * texture->pow2_w]); + return ((u32 *)texture->data)[x + y * texture->pow2_w]; } } @@ -675,7 +824,7 @@ void sf2d_texture_tile32(sf2d_texture *texture) u32 dst_offset = get_morton_offset(i, j, 4) + coarse_y * texture->pow2_w * 4; u32 v = ((u32 *)texture->data)[i + (texture->pow2_h - 1 - j)*texture->pow2_w]; - *(u32 *)(tmp + dst_offset) = __builtin_bswap32(v); + *(u32 *)(tmp + dst_offset) = __builtin_bswap32(v); /* RGBA8 -> ABGR8 */ } } diff --git a/libs/sf2dlib/sample/Makefile b/libs/sf2dlib/sample/Makefile index 840f32b..27ae68b 100644 --- a/libs/sf2dlib/sample/Makefile +++ b/libs/sf2dlib/sample/Makefile @@ -153,7 +153,7 @@ run: $(BUILD) @citra $(TARGET).3dsx #--------------------------------------------------------------------------------- copy_cia: $(TARGET).cia - @cp $(TARGET).cia /mnt/GATEWAYNAND + @cp $(TARGET).cia /mnt/3DS sync #--------------------------------------------------------------------------------- diff --git a/libs/sf2dlib/sample/source/main.c b/libs/sf2dlib/sample/source/main.c index fb96559..820888b 100644 --- a/libs/sf2dlib/sample/source/main.c +++ b/libs/sf2dlib/sample/source/main.c @@ -20,6 +20,8 @@ extern const struct { unsigned char pixel_data[]; } dice_img; +#define CONFIG_3D_SLIDERSTATE (*(float *)0x1FF81080) + int main() { // Set the random seed based on the time @@ -27,11 +29,13 @@ int main() sf2d_init(); sf2d_set_clear_color(RGBA8(0x40, 0x40, 0x40, 0xFF)); + sf2d_set_3D(1); sf2d_texture *tex1 = sf2d_create_texture_mem_RGBA8(dice_img.pixel_data, dice_img.width, dice_img.height, TEXFMT_RGBA8, SF2D_PLACE_RAM); sf2d_texture *tex2 = sf2d_create_texture_mem_RGBA8(citra_img.pixel_data, citra_img.width, citra_img.height, TEXFMT_RGBA8, SF2D_PLACE_RAM); + float offset3d = 0.0f; float rad = 0.0f; u16 touch_x = 320/2; u16 touch_y = 240/2; @@ -55,7 +59,23 @@ int main() sf2d_set_clear_color(RGBA8(rand()%255, rand()%255, rand()%255, 255)); } + offset3d = CONFIG_3D_SLIDERSTATE * 30.0f; + sf2d_start_frame(GFX_TOP, GFX_LEFT); + sf2d_draw_fill_circle(offset3d + 60, 100, 35, RGBA8(0x00, 0xFF, 0x00, 0xFF)); + sf2d_draw_fill_circle(offset3d + 180, 120, 55, RGBA8(0xFF, 0xFF, 0x00, 0xFF)); + + sf2d_draw_rectangle_rotate(offset3d + 260, 20, 40, 40, RGBA8(0xFF, 0xFF, 0x00, 0xFF), -2.0f*rad); + sf2d_draw_rectangle(offset3d + 20, 60, 40, 40, RGBA8(0xFF, 0x00, 0x00, 0xFF)); + sf2d_draw_rectangle(offset3d + 5, 5, 30, 30, RGBA8(0x00, 0xFF, 0xFF, 0xFF)); + sf2d_draw_texture_rotate(tex1, offset3d + 400/2 + circle.dx, 240/2 - circle.dy, rad); + sf2d_end_frame(); + + sf2d_start_frame(GFX_TOP, GFX_RIGHT); + + sf2d_draw_fill_circle(60, 100, 35, RGBA8(0x00, 0xFF, 0x00, 0xFF)); + sf2d_draw_fill_circle(180, 120, 55, RGBA8(0xFF, 0xFF, 0x00, 0xFF)); + sf2d_draw_rectangle_rotate(260, 20, 40, 40, RGBA8(0xFF, 0xFF, 0x00, 0xFF), -2.0f*rad); sf2d_draw_rectangle(20, 60, 40, 40, RGBA8(0xFF, 0x00, 0x00, 0xFF)); sf2d_draw_rectangle(5, 5, 30, 30, RGBA8(0x00, 0xFF, 0xFF, 0xFF)); diff --git a/libs/sftdlib/libsftd/include/sftd.h b/libs/sftdlib/libsftd/include/sftd.h index 9e3facc..8702a04 100644 --- a/libs/sftdlib/libsftd/include/sftd.h +++ b/libs/sftdlib/libsftd/include/sftd.h @@ -110,9 +110,19 @@ void sftd_draw_wtextf(sftd_font *font, int x, int y, unsigned int color, unsigne * @param font the font used to calculate the width * @param size the font size * @param text a pointer to the text that will be used to calculate the length + * @return the width in pixels */ int sftd_get_text_width(sftd_font *font, unsigned int size, const char *text); +/** + * @brief Returns the width of the given wide text in pixels + * @param font the font used to calculate the width + * @param size the font size + * @param text a pointer to the wide text that will be used to calculate the length + * @return the width in pixels + */ +int sftd_get_wtext_width(sftd_font *font, unsigned int size, const wchar_t *text); + /** * @brief Draws text using a font. The text will wrap after the pixels specified in lineWidth. * @param font the font to use @@ -149,9 +159,6 @@ void sftd_calc_bounding_box(int *boundingWidth, int *boundingHeight, sftd_font * */ void sftd_draw_textf_wrap(sftd_font *font, int x, int y, unsigned int color, unsigned int size, unsigned int lineWidth, const char *text, ...); -// (ctruLua addition) Based on sftd_draw_wtext, returns the width of the text drawn. -int sftd_width_wtext(sftd_font *font, unsigned int size, const wchar_t *text); - #ifdef __cplusplus } #endif diff --git a/libs/sftdlib/libsftd/source/sftd.c b/libs/sftdlib/libsftd/source/sftd.c index f8f2b4f..6dca62f 100644 --- a/libs/sftdlib/libsftd/source/sftd.c +++ b/libs/sftdlib/libsftd/source/sftd.c @@ -13,7 +13,6 @@ static int sftd_initialized = 0; static FT_Library ftlibrary; -static FTC_Manager ftcmanager; typedef enum { SFTD_LOAD_FROM_FILE, @@ -228,6 +227,13 @@ void sftd_draw_text(sftd_font *font, int x, int y, unsigned int color, unsigned FT_ULong flags = FT_LOAD_RENDER | FT_LOAD_TARGET_NORMAL; while (*text) { + if(*text == '\n') { + pen_x = x; + pen_y += size; + text++; + continue; + } + glyph_index = FTC_CMapCache_Lookup(font->cmapcache, (FTC_FaceID)font, charmap_index, *text); if (use_kerning && previous && glyph_index) { @@ -305,6 +311,13 @@ void sftd_draw_wtext(sftd_font *font, int x, int y, unsigned int color, unsigned FT_ULong flags = FT_LOAD_RENDER | FT_LOAD_TARGET_NORMAL; while (*text) { + if(*text == '\n') { + pen_x = x; + pen_y += size; + text++; + continue; + } + glyph_index = FTC_CMapCache_Lookup(font->cmapcache, (FTC_FaceID)font, charmap_index, *text); if (use_kerning && previous && glyph_index) { @@ -418,6 +431,66 @@ int sftd_get_text_width(sftd_font *font, unsigned int size, const char *text) return pen_x; } +int sftd_get_wtext_width(sftd_font *font, unsigned int size, const wchar_t *text) +{ + FTC_FaceID face_id = (FTC_FaceID)font; + FT_Face face; + FTC_Manager_LookupFace(font->ftcmanager, face_id, &face); + + FT_Int charmap_index; + charmap_index = FT_Get_Charmap_Index(face->charmap); + + FT_Glyph glyph; + FT_Bool use_kerning = FT_HAS_KERNING(face); + FT_UInt glyph_index, previous = 0; + int pen_x = 0; + int pen_y = size; + + FTC_ScalerRec scaler; + scaler.face_id = face_id; + scaler.width = size; + scaler.height = size; + scaler.pixel = 1; + + FT_ULong flags = FT_LOAD_RENDER | FT_LOAD_TARGET_NORMAL; + + while (*text) { + glyph_index = FTC_CMapCache_Lookup(font->cmapcache, (FTC_FaceID)font, charmap_index, *text); + + if (use_kerning && previous && glyph_index) { + FT_Vector delta; + FT_Get_Kerning(face, previous, glyph_index, FT_KERNING_DEFAULT, &delta); + pen_x += delta.x >> 6; + } + + if (!texture_atlas_exists(font->tex_atlas, glyph_index)) { + FTC_ImageCache_LookupScaler(font->imagecache, &scaler, flags, glyph_index, &glyph, NULL); + + if (!atlas_add_glyph(font->tex_atlas, glyph_index, (FT_BitmapGlyph)glyph, size)) { + continue; + } + } + + bp2d_rectangle rect; + int bitmap_left, bitmap_top; + int advance_x, advance_y; + int glyph_size; + + texture_atlas_get(font->tex_atlas, glyph_index, + &rect, &bitmap_left, &bitmap_top, + &advance_x, &advance_y, &glyph_size); + + const float draw_scale = size/(float)glyph_size; + + pen_x += (advance_x >> 16) * draw_scale; + pen_y += (advance_y >> 16) * draw_scale; + + previous = glyph_index; + text++; + } + return pen_x; +} + void sftd_draw_text_wrap(sftd_font *font, int x, int y, unsigned int color, unsigned int size, unsigned int lineWidth, const char *text) { FTC_FaceID face_id = (FTC_FaceID)font; @@ -611,63 +684,3 @@ void sftd_draw_textf_wrap(sftd_font *font, int x, int y, unsigned int color, uns sftd_draw_text_wrap(font, x, y, color, size, lineWidth, buffer); va_end(args); } - -// (ctruLua addition) Based on sftd_draw_wtext, returns the width of the text drawn. -int sftd_width_wtext(sftd_font *font, unsigned int size, const wchar_t *text) -{ - FTC_FaceID face_id = (FTC_FaceID)font; - FT_Face face; - FTC_Manager_LookupFace(ftcmanager, face_id, &face); - - FT_Int charmap_index; - charmap_index = FT_Get_Charmap_Index(face->charmap); - - FT_Glyph glyph; - FT_Bool use_kerning = FT_HAS_KERNING(face); - FT_UInt glyph_index, previous = 0; - int pen_x = 0; - - FTC_ScalerRec scaler; - scaler.face_id = face_id; - scaler.width = size; - scaler.height = size; - scaler.pixel = 1; - - FT_ULong flags = FT_LOAD_RENDER | FT_LOAD_TARGET_NORMAL; - - while (*text) { - glyph_index = FTC_CMapCache_Lookup(font->cmapcache, (FTC_FaceID)font, charmap_index, *text); - - if (use_kerning && previous && glyph_index) { - FT_Vector delta; - FT_Get_Kerning(face, previous, glyph_index, FT_KERNING_DEFAULT, &delta); - pen_x += delta.x >> 6; - } - - if (!texture_atlas_exists(font->tex_atlas, glyph_index)) { - FTC_ImageCache_LookupScaler(font->imagecache, &scaler, flags, glyph_index, &glyph, NULL); - - if (!atlas_add_glyph(font->tex_atlas, glyph_index, (FT_BitmapGlyph)glyph, size)) { - continue; - } - } - - bp2d_rectangle rect; - int bitmap_left, bitmap_top; - int advance_x, advance_y; - int glyph_size; - - texture_atlas_get(font->tex_atlas, glyph_index, - &rect, &bitmap_left, &bitmap_top, - &advance_x, &advance_y, &glyph_size); - - const float draw_scale = size/(float)glyph_size; - - pen_x += (advance_x >> 16) * draw_scale; - - previous = glyph_index; - text++; - } - - return pen_x; -} diff --git a/libs/sftdlib/libsftd/source/texture_atlas.c b/libs/sftdlib/libsftd/source/texture_atlas.c index c877c59..f8e76bc 100644 --- a/libs/sftdlib/libsftd/source/texture_atlas.c +++ b/libs/sftdlib/libsftd/source/texture_atlas.c @@ -15,6 +15,7 @@ texture_atlas *texture_atlas_create(int width, int height, sf2d_texfmt format, s rect.h = height; atlas->tex = sf2d_create_texture(width, height, format, place); + sf2d_texture_set_params(atlas->tex, GPU_TEXTURE_MAG_FILTER(GPU_LINEAR) | GPU_TEXTURE_MIN_FILTER(GPU_LINEAR)); sf2d_texture_tile32(atlas->tex); atlas->bp_root = bp2d_create(&rect); @@ -58,11 +59,12 @@ int texture_atlas_insert(texture_atlas *atlas, unsigned int character, const voi int i, j; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { - sf2d_set_pixel(atlas->tex, pos.x + j, pos.y + i, *(unsigned int *)(image + (j + i*width)*4)); + sf2d_set_pixel(atlas->tex, pos.x + j, pos.y + i, + __builtin_bswap32(*(unsigned int *)(image + (j + i*width)*4))); } } - GSPGPU_FlushDataCache(NULL, atlas->tex->data, atlas->tex->data_size); + GSPGPU_FlushDataCache(atlas->tex->data, atlas->tex->data_size); return 1; } diff --git a/libs/stb/include/stb_image.h b/libs/stb/include/stb_image.h new file mode 100644 index 0000000..7522b99 --- /dev/null +++ b/libs/stb/include/stb_image.h @@ -0,0 +1,6615 @@ +/* stb_image - v2.10 - public domain image loader - http://nothings.org/stb_image.h + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + // i.e. it should look like this: + #include ... + #include ... + #include ... + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) + PNG 1/2/4/8-bit-per-channel (16 bpc not supported) + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels, 8/16 bit-per-channel) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + PNM (PPM and PGM binary only) + + Animated GIF still needs a proper API, but here's one way to do it: + http://gist.github.com/urraka/685d9a6340b26b830d49 + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) + + Full documentation under "DOCUMENTATION" below. + + + Revision 2.00 release notes: + + - Progressive JPEG is now supported. + + - PPM and PGM binary formats are now supported, thanks to Ken Miller. + + - x86 platforms now make use of SSE2 SIMD instructions for + JPEG decoding, and ARM platforms can use NEON SIMD if requested. + This work was done by Fabian "ryg" Giesen. SSE2 is used by + default, but NEON must be enabled explicitly; see docs. + + With other JPEG optimizations included in this version, we see + 2x speedup on a JPEG on an x86 machine, and a 1.5x speedup + on a JPEG on an ARM machine, relative to previous versions of this + library. The same results will not obtain for all JPGs and for all + x86/ARM machines. (Note that progressive JPEGs are significantly + slower to decode than regular JPEGs.) This doesn't mean that this + is the fastest JPEG decoder in the land; rather, it brings it + closer to parity with standard libraries. If you want the fastest + decode, look elsewhere. (See "Philosophy" section of docs below.) + + See final bullet items below for more info on SIMD. + + - Added STBI_MALLOC, STBI_REALLOC, and STBI_FREE macros for replacing + the memory allocator. Unlike other STBI libraries, these macros don't + support a context parameter, so if you need to pass a context in to + the allocator, you'll have to store it in a global or a thread-local + variable. + + - Split existing STBI_NO_HDR flag into two flags, STBI_NO_HDR and + STBI_NO_LINEAR. + STBI_NO_HDR: suppress implementation of .hdr reader format + STBI_NO_LINEAR: suppress high-dynamic-range light-linear float API + + - You can suppress implementation of any of the decoders to reduce + your code footprint by #defining one or more of the following + symbols before creating the implementation. + + STBI_NO_JPEG + STBI_NO_PNG + STBI_NO_BMP + STBI_NO_PSD + STBI_NO_TGA + STBI_NO_GIF + STBI_NO_HDR + STBI_NO_PIC + STBI_NO_PNM (.ppm and .pgm) + + - You can request *only* certain decoders and suppress all other ones + (this will be more forward-compatible, as addition of new decoders + doesn't require you to disable them explicitly): + + STBI_ONLY_JPEG + STBI_ONLY_PNG + STBI_ONLY_BMP + STBI_ONLY_PSD + STBI_ONLY_TGA + STBI_ONLY_GIF + STBI_ONLY_HDR + STBI_ONLY_PIC + STBI_ONLY_PNM (.ppm and .pgm) + + Note that you can define multiples of these, and you will get all + of them ("only x" and "only y" is interpreted to mean "only x&y"). + + - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still + want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB + + - Compilation of all SIMD code can be suppressed with + #define STBI_NO_SIMD + It should not be necessary to disable SIMD unless you have issues + compiling (e.g. using an x86 compiler which doesn't support SSE + intrinsics or that doesn't support the method used to detect + SSE2 support at run-time), and even those can be reported as + bugs so I can refine the built-in compile-time checking to be + smarter. + + - The old STBI_SIMD system which allowed installing a user-defined + IDCT etc. has been removed. If you need this, don't upgrade. My + assumption is that almost nobody was doing this, and those who + were will find the built-in SIMD more satisfactory anyway. + + - RGB values computed for JPEG images are slightly different from + previous versions of stb_image. (This is due to using less + integer precision in SIMD.) The C code has been adjusted so + that the same RGB values will be computed regardless of whether + SIMD support is available, so your app should always produce + consistent results. But these results are slightly different from + previous versions. (Specifically, about 3% of available YCbCr values + will compute different RGB results from pre-1.49 versions by +-1; + most of the deviating values are one smaller in the G channel.) + + - If you must produce consistent results with previous versions of + stb_image, #define STBI_JPEG_OLD and you will get the same results + you used to; however, you will not get the SIMD speedups for + the YCbCr-to-RGB conversion step (although you should still see + significant JPEG speedup from the other changes). + + Please note that STBI_JPEG_OLD is a temporary feature; it will be + removed in future versions of the library. It is only intended for + near-term back-compatibility use. + + + Latest revision history: + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) partial animated GIF support + limited 16-bit PSD support + minor bugs, code cleanup, and compiler warnings + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) additional corruption checking + stbi_set_flip_vertically_on_load + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPEG, including x86 SSE2 & ARM NEON SIMD + progressive JPEG + PGM/PPM support + STBI_MALLOC,STBI_REALLOC,STBI_FREE + STBI_NO_*, STBI_ONLY_* + GIF bugfix + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support (both grayscale and paletted) + optimize PNG + fix bug in interlaced PNG with user-specified channel count + + See end of file for full revision history. + + + ============================ Contributors ========================= + + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + urraka@github (animated gif) Junggon Kim (PNM comments) + Daniel Gibson (16-bit TGA) + + Optimizations & bugfixes + Fabian "ryg" Giesen + Arseny Kapoulkine + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Martin Golini Jerry Jansson Joseph Thomson + Dave Moore Roy Eltham Hayaki Saito Phil Jordan + Won Chun Luke Graham Johan Duparc Nathan Reed + the Horde3D community Thomas Ruf Ronny Chevalier Nick Verigakis + Janez Zemva John Bartholomew Michal Cichon svdijk@github + Jonathan Blow Ken Hamada Tero Hanninen Baldur Karlsson + Laurent Gomila Cort Stratton Sergio Gonzalez romigrou@github + Aruelien Pocheville Thibault Reuille Cass Everitt + Ryamond Barbiero Paul Du Bois Engin Manap + Blazej Dariusz Roszkowski + Michaelangel007@github + + +LICENSE + +This software is in the public domain. Where that dedication is not +recognized, you are granted a perpetual, irrevocable license to copy, +distribute, and modify this file as you see fit. + +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 16-bit-per-channel PNG +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - no 1-bit BMP +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data) +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *comp -- outputs # of image components in image file +// int req_comp -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise. +// If req_comp is non-zero, *comp has the number of components that _would_ +// have been output otherwise. E.g. if you set req_comp to 4, you will always +// get RGBA output, but you can check *comp to see if it's trivially opaque +// because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *comp will be unchanged. The function stbi_failure_reason() +// can be queried for an extremely brief, end-user unfriendly explanation +// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid +// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy to use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries do not emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// make more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// The output of the JPEG decoder is slightly different from versions where +// SIMD support was introduced (that is, for versions before 1.49). The +// difference is only +-1 in the 8-bit RGB channels, and only on a small +// fraction of pixels. You can force the pre-1.49 behavior by defining +// STBI_JPEG_OLD, but this will disable some of the SIMD decoding path +// and hence cost some performance. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image now supports loading HDR images in general, and currently +// the Radiance .HDR file format, although the support is provided +// generically. You can still load any file through the existing interface; +// if you attempt to load an HDR file, it will be automatically remapped to +// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// By default we convert iphone-formatted PNGs back to RGB, even though +// they are internally encoded differently. You can disable this conversion +// by by calling stbi_convert_iphone_png_to_rgb(0), in which case +// you will always just get the native iphone "format" through (which +// is BGR stored in RGB). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// + + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for req_comp + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +typedef unsigned char stbi_uc; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// PRIMARY API - works on images of any type +// + +// +// load image by filename, open file, or memory buffer +// + +typedef struct +{ + int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void *user); // returns nonzero if we are at end of file/data +} stbi_io_callbacks; + +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp); +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *comp, int req_comp); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *comp, int req_comp); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); +// for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp); + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp); + + #ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); + #endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + +// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename); +STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + +// get a VERY brief reason for failure +// NOT THREADSAFE +STBIDEF const char *stbi_failure_reason (void); + +// free the loaded image -- this is just free() +STBIDEF void stbi_image_free (void *retval_from_stbi_load); + +// get image dimensions & components without fully decoding +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); + +#endif + + + +// for image formats that explicitly notate that they have premultiplied alpha, +// we just return the colors as stored in the file. set this flag to force +// unpremultiplication. results are undefined if the unpremultiply overflow. +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + +// indicate whether we should process iphone images back to canonical format, +// or just pass them through "as-is" +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + +// flip the image vertically, so the first pixel in the output array is the bottom left +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + +// ZLIB client - used by PNG, available for other purposes + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); +STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + +STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) + #ifndef STBI_ONLY_JPEG + #define STBI_NO_JPEG + #endif + #ifndef STBI_ONLY_PNG + #define STBI_NO_PNG + #endif + #ifndef STBI_ONLY_BMP + #define STBI_NO_BMP + #endif + #ifndef STBI_ONLY_PSD + #define STBI_NO_PSD + #endif + #ifndef STBI_ONLY_TGA + #define STBI_NO_TGA + #endif + #ifndef STBI_ONLY_GIF + #define STBI_NO_GIF + #endif + #ifndef STBI_ONLY_HDR + #define STBI_NO_HDR + #endif + #ifndef STBI_ONLY_PIC + #define STBI_NO_PIC + #endif + #ifndef STBI_ONLY_PNM + #define STBI_NO_PNM + #endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#endif + + +#ifdef _MSC_VER +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL + #define stbi_lrot(x,y) _lrotl(x,y) +#else + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// NOTE: not clear do we actually need this for the 64-bit path? +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// (but compiling with -msse2 allows the compiler to use SSE2 everywhere; +// this is just broken and gcc are jerks for not fixing it properly +// http://www.virtualdub.org/blog/pivot/entry.php?id=363 ) +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && defined(STBI__X86_TARGET) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info,1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax,1 + cpuid + mov res,edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +static int stbi__sse2_available() +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +static int stbi__sse2_available() +{ +#if defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 408 // GCC 4.8 or later + // GCC 4.8+ has a nice way to do this + return __builtin_cpu_supports("sse2"); +#else + // portable way to do this, preferably without using GCC inline ASM? + // just bail for now. + return 0; +#endif +} +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +// assume GCC or Clang on ARM targets +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int) fread(data,1,size,(FILE*) user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + fseek((FILE*) user, n, SEEK_CUR); +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*) user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context *s); +static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context *s); +static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context *s); +static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context *s); +static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s); +static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context *s); +static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context *s); +static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context *s); +static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +// this is not threadsafe +static const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} + +static void *stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS + #define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) + #define stbi__err(x,y) stbi__err(y) +#else + #define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load = flag_true_if_should_flip; +} + +static unsigned char *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp); + #endif + #ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp); + #endif + #ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp); + #endif + #ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp); + #endif + #ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp); + #endif + #ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp); + #endif + #ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp); + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } + #endif + + #ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s,x,y,comp,req_comp); + #endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static unsigned char *stbi__load_flip(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result = stbi__load_main(s, x, y, comp, req_comp); + + if (stbi__vertically_flip_on_load && result != NULL) { + int w = *x, h = *y; + int depth = req_comp ? req_comp : *comp; + int row,col,z; + stbi_uc temp; + + // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once + for (row = 0; row < (h>>1); row++) { + for (col = 0; col < w; col++) { + for (z = 0; z < depth; z++) { + temp = result[(row * w + col) * depth + z]; + result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z]; + result[((h - row - 1) * w + col) * depth + z] = temp; + } + } + } + } + + return result; +} + +#ifndef STBI_NO_HDR +static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int w = *x, h = *y; + int depth = req_comp ? req_comp : *comp; + int row,col,z; + float temp; + + // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once + for (row = 0; row < (h>>1); row++) { + for (col = 0; col < w; col++) { + for (z = 0; z < depth; z++) { + temp = result[(row * w + col) * depth + z]; + result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z]; + result[((h - row - 1) * w + col) * depth + z] = temp; + } + } + } + } +} +#endif + +#ifndef STBI_NO_STDIO + +static FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_flip(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} +#endif //!STBI_NO_STDIO + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_flip(&s,x,y,comp,req_comp); +} + +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__load_flip(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp); + if (hdr_data) + stbi__float_postprocess(hdr_data,x,y,comp,req_comp); + return hdr_data; + } + #endif + data = stbi__load_flip(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s,f); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; + #endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result=0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_file(&s,f); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(f); + return 0; + #endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; + #endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load=0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start+1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} + +static void stbi__skip(stbi__context *s, int n) +{ + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} + +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); + res = (count == (n-blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer+n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; +} + +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} + +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + return z + (stbi__get16le(s) << 16); +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + + +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +} + +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *) stbi__malloc(req_comp * x * y); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + unsigned char *src = data + j * x * img_n ; + unsigned char *dest = good + j * x * req_comp; + + #define COMBO(a,b) ((a)*8+(b)) + #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (COMBO(img_n, req_comp)) { + CASE(1,2) dest[0]=src[0], dest[1]=255; break; + CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break; + CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break; + CASE(2,1) dest[0]=src[0]; break; + CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break; + CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break; + CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break; + CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break; + CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break; + CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break; + CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break; + CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break; + default: STBI_ASSERT(0); + } + #undef CASE + } + + STBI_FREE(data); + return good; +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i,k,n; + float *output = (float *) stbi__malloc(x * y * comp * sizeof(float)); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f; + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i,k,n; + stbi_uc *output = (stbi_uc *) stbi__malloc(x * y * comp); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp+k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi_uc dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + +// sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + +// definition of jpeg image component + struct + { + int id; + int h,v; + int tq; + int hd,ha; + int dc_pred; + + int x,y,w2,h2; + stbi_uc *data; + void *raw_data, *raw_coeff; + stbi_uc *linebuf; + short *coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + + int scan_n, order[4]; + int restart_interval, todo; + +// kernels + void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); + stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i,j,k=0,code; + // build size list for each symbol (from JPEG spec) + for (i=0; i < 16; ++i) + for (j=0; j < count[i]; ++j) + h->size[k++] = (stbi_uc) (i+1); + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for(j=1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16) (code++); + if (code-1 >= (1 << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16-j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i=0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS-s); + int m = 1 << (FAST_BITS-s); + for (j=0; j < m; ++j) { + h->fast[c+j] = (stbi_uc) i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) +{ + int i; + for (i=0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (-1 << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16) ((k << 8) + (run << 4) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + if (c != 0) { + j->marker = (unsigned char) c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c,k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k=FAST_BITS+1 ; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + + sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB + k = stbi_lrot(j->code_buffer, n); + STBI_ASSERT(n >= 0 && n < (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & ~sgn); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static stbi_uc stbi__jpeg_dezigzag[64+15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi_uc *dequant) +{ + int diff,dc,k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data,0,64*sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short) (dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * dequant[zig]); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) +{ + int diff,dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data,0,64*sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + diff = t ? stbi__extend_receive(j, t) : 0; + + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short) (dc << j->succ_low); + } else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short) (1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) << shift); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) << shift); + } + } + } while (k <= j->spec_end); + } else { + // refinement scan for these AC coefficients + + short bit = (short) (1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short *p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } else { + k = j->spec_start; + do { + int r,s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short *p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } else { + if (r == 0) { + *p = (short) s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int) x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc) x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) << 12) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) +{ + int i,val[64],*v=val; + stbi_uc *o; + short *d = data; + + // columns + for (i=0; i < 8; ++i,++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 + && d[40]==0 && d[48]==0 && d[56]==0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0] << 2; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } else { + STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[ 0] = (x0+t3) >> 10; + v[56] = (x0-t3) >> 10; + v[ 8] = (x1+t2) >> 10; + v[48] = (x1-t2) >> 10; + v[16] = (x2+t1) >> 10; + v[40] = (x2-t1) >> 10; + v[24] = (x3+t0) >> 10; + v[32] = (x3-t0) >> 10; + } + } + + for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128<<17); + x1 += 65536 + (128<<17); + x2 += 65536 + (128<<17); + x3 += 65536 + (128<<17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0+t3) >> 17); + o[7] = stbi__clamp((x0-t3) >> 17); + o[1] = stbi__clamp((x1+t2) >> 17); + o[6] = stbi__clamp((x1-t2) >> 17); + o[2] = stbi__clamp((x2+t1) >> 17); + o[5] = stbi__clamp((x2-t1) >> 17); + o[3] = stbi__clamp((x3+t0) >> 17); + o[4] = stbi__clamp((x3-t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y + #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + + // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) + // out(1) = c1[even]*x + c1[odd]*y + #define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) + #define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add + #define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub + #define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack + #define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) + #define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) + #define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + + #define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); + + // load + row0 = _mm_load_si128((const __m128i *) (data + 0*8)); + row1 = _mm_load_si128((const __m128i *) (data + 1*8)); + row2 = _mm_load_si128((const __m128i *) (data + 2*8)); + row3 = _mm_load_si128((const __m128i *) (data + 3*8)); + row4 = _mm_load_si128((const __m128i *) (data + 4*8)); + row5 = _mm_load_si128((const __m128i *) (data + 5*8)); + row6 = _mm_load_si128((const __m128i *) (data + 6*8)); + row7 = _mm_load_si128((const __m128i *) (data + 7*8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i *) out, p0); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p2); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p1); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p3); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + +// wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + +// wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + +// butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0*8); + row1 = vld1q_s16(data + 1*8); + row2 = vld1q_s16(data + 2*8); + row3 = vld1q_s16(data + 3*8); + row4 = vld1q_s16(data + 4*8); + row5 = vld1q_s16(data + 5*8); + row6 = vld1q_s16(data + 6*8); + row7 = vld1q_s16(data + 7*8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { +// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. +// whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i,j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + STBI_SIMD_ALIGN(short, data[64]); + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x)*8; + int y2 = (j*z->img_comp[n].v + y)*8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } else { + if (z->scan_n == 1) { + int i,j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x); + int y2 = (j*z->img_comp[n].v + y); + short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short *data, stbi_uc *dequant) +{ + int i; + for (i=0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg *z) +{ + if (z->progressive) { + // dequantize and idct the data + int i,j,n; + for (n=0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker","Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s)-2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4; + int t = q & 15,i; + if (p != 0) return stbi__err("bad DQT type","Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + for (i=0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8(z->s); + L -= 65; + } + return L==0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s)-2; + while (L > 0) { + stbi_uc *v; + int sizes[16],i,n=0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); + for (i=0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i=0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L==0; + } + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + stbi__skip(z->s, stbi__get16be(z->s)-2); + return 1; + } + return 0; +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); + if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); + for (i=0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } else { + if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf,p,i,q, h_max=1,v_max=1,c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + c = stbi__get8(s); + if (c != 3 && c != 1) return stbi__err("bad component count","Corrupt JPEG"); // JFIF requires + s->img_n = c; + for (i=0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + + for (i=0; i < s->img_n; ++i) { + z->img_comp[i].id = stbi__get8(s); + if (z->img_comp[i].id != i+1) // JFIF requires + if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files! + return stbi__err("bad component ID","Corrupt JPEG"); + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + + for (i=0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + + for (i=0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].raw_data = stbi__malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15); + + if (z->img_comp[i].raw_data == NULL) { + for(--i; i >= 0; --i) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + } + return stbi__err("outofmem", "Out of memory"); + } + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + z->img_comp[i].linebuf = NULL; + if (z->progressive) { + z->img_comp[i].coeff_w = (z->img_comp[i].w2 + 7) >> 3; + z->img_comp[i].coeff_h = (z->img_comp[i].h2 + 7) >> 3; + z->img_comp[i].raw_coeff = STBI_MALLOC(z->img_comp[i].coeff_w * z->img_comp[i].coeff_h * 64 * sizeof(short) + 15); + z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); + } else { + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z,m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg *j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none ) { + // handle 0s at the end of image data from IP Kamera 9060 + while (!stbi__at_eof(j->s)) { + int x = stbi__get8(j->s); + if (x == 255) { + j->marker = stbi__get8(j->s); + break; + } else if (x != 0) { + return stbi__err("junk before marker", "Corrupt JPEG"); + } + } + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + } else { + if (!stbi__process_marker(j, m)) return 0; + } + m = stbi__get_marker(j); + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i=0; i < w; ++i) + out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0]*3 + input[1] + 2); + for (i=1; i < w-1; ++i) { + int n = 3*input[i]+2; + out[i*2+0] = stbi__div4(n+input[i-1]); + out[i*2+1] = stbi__div4(n+input[i+1]); + } + out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); + out[i*2+1] = input[w-1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i,t0,t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + out[0] = stbi__div4(t1+2); + for (i=1; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i=0,t0,t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w-1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i *) (out + i*2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i*2, o); +#endif + + // "previous" value for next iter + t1 = 3*in_near[i+7] + in_far[i+7]; + } + + t0 = t1; + t1 = 3*in_near[i] + in_far[i]; + out[i*2] = stbi__div16(3*t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i,j; + STBI_NOTUSED(in_far); + for (i=0; i < w; ++i) + for (j=0; j < hs; ++j) + out[i*hs+j] = in_near[i]; + return out; +} + +#ifdef STBI_JPEG_OLD +// this is the same YCbCr-to-RGB calculation that stb_image has used +// historically before the algorithm changes in 1.49 +#define float2fixed(x) ((int) ((x) * 65536 + 0.5)) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 16) + 32768; // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr*float2fixed(1.40200f); + g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f); + b = y_fixed + cb*float2fixed(1.77200f); + r >>= 16; + g >>= 16; + b >>= 16; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#else +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* float2fixed(1.40200f); + g = y_fixed + (cr*-float2fixed(0.71414f)) + ((cb*-float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); + __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); + __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); + __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); + __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i+7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i *) (out + 0), o0); + _mm_storeu_si128((__m128i *) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); + int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); + int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); + int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); + + for (; i+7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8*4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* float2fixed(1.40200f); + g = y_fixed + cr*-float2fixed(0.71414f) + ((cb*-float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg *j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + #ifndef STBI_JPEG_OLD + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + #endif + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + #ifndef STBI_JPEG_OLD + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + #endif + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + int i; + for (i=0; i < j->s->img_n; ++i) { + if (j->img_comp[i].raw_data) { + STBI_FREE(j->img_comp[i].raw_data); + j->img_comp[i].raw_data = NULL; + j->img_comp[i].data = NULL; + } + if (j->img_comp[i].raw_coeff) { + STBI_FREE(j->img_comp[i].raw_coeff); + j->img_comp[i].raw_coeff = 0; + j->img_comp[i].coeff = 0; + } + if (j->img_comp[i].linebuf) { + STBI_FREE(j->img_comp[i].linebuf); + j->img_comp[i].linebuf = NULL; + } + } +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0,*line1; + int hs,vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n; + + if (z->s->img_n == 3 && n < 3) + decode_n = 1; + else + decode_n = z->s->img_n; + + // resample and color-convert + { + int k; + unsigned int i,j; + stbi_uc *output; + stbi_uc *coutput[4]; + + stbi__resample res_comp[4]; + + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs-1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *) stbi__malloc(n * z->s->img_x * z->s->img_y + 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j=0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } else + for (i=0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255; + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n; // report original components, not output + return output; + } +} + +static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__jpeg j; + j.s = s; + stbi__setup_jpeg(&j); + return load_jpeg_image(&j, x,y,comp,req_comp); +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg j; + j.s = s; + stbi__setup_jpeg(&j); + r = stbi__decode_jpeg_header(&j, STBI__SCAN_type); + stbi__rewind(s); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind( j->s ); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__jpeg j; + j.s = s; + return stbi__jpeg_info_raw(&j, x, y, comp); +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[288]; + stbi__uint16 value[288]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16-bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num) +{ + int i,k=0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i=0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i=1; i < 16; ++i) + if (sizes[i] > (1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i=1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16) code; + z->firstsymbol[i] = (stbi__uint16) k; + code = (code + sizes[i]); + if (sizes[i]) + if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); + z->maxcode[i] = code << (16-i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i=0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); + z->size [c] = (stbi_uc ) s; + z->value[c] = (stbi__uint16) i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s],s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + if (z->zbuffer >= z->zbuffer_end) return 0; + return *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + STBI_ASSERT(z->code_buffer < (1U << z->num_bits)); + z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s,k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s=STBI__ZFAST_BITS+1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s == 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; + STBI_ASSERT(z->size[b] == s); + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s; + if (a->num_bits < 16) stbi__fill_bits(a); + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +{ + char *q; + int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (int) (z->zout - z->zout_start); + limit = old_limit = (int) (z->zout_end - z->zout_start); + while (cur + n > limit) + limit *= 2; + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static int stbi__zlength_extra[31]= +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + +static int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + char *zout = a->zout; + for(;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char) z; + } else { + stbi_uc *p; + int len,dist; + if (z == 256) { + a->zout = zout; + return 1; + } + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); + if (zout + len > a->zout_end) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc *) (zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286+32+137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i,n; + + int hlit = stbi__zreceive(a,5) + 257; + int hdist = stbi__zreceive(a,5) + 1; + int hclen = stbi__zreceive(a,4) + 4; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i=0; i < hclen; ++i) { + int s = stbi__zreceive(a,3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < hlit + hdist) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc) c; + else if (c == 16) { + c = stbi__zreceive(a,2)+3; + memset(lencodes+n, lencodes[n-1], c); + n += c; + } else if (c == 17) { + c = stbi__zreceive(a,3)+3; + memset(lencodes+n, 0, c); + n += c; + } else { + STBI_ASSERT(c == 18); + c = stbi__zreceive(a,7)+11; + memset(lencodes+n, 0, c); + n += c; + } + } + if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncomperssed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len,nlen,k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + STBI_ASSERT(a->num_bits == 0); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +// @TODO: should statically initialize these for optimal thread safety +static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32]; +static void stbi__init_zdefaults(void) +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + do { + final = stbi__zreceive(a,1); + type = stbi__zreceive(a,2); + if (type == 0) { + if (!stbi__parse_uncomperssed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zdefault_distance[31]) stbi__init_zdefaults(); + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer+len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int) (a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i=0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; +} stbi__png; + + +enum { + STBI__F_none=0, + STBI__F_sub=1, + STBI__F_up=2, + STBI__F_avg=3, + STBI__F_paeth=4, + // synthetic filters used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static int stbi__paeth(int a, int b, int c) +{ + int p = a + b - c; + int pa = abs(p-a); + int pb = abs(p-b); + int pc = abs(p-c); + if (pa <= pb && pa <= pc) return a; + if (pb <= pc) return b; + return c; +} + +static stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + stbi__context *s = a->s; + stbi__uint32 i,j,stride = x*out_n; + stbi__uint32 img_len, img_width_bytes; + int k; + int img_n = s->img_n; // copy it into a local for later + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); + a->out = (stbi_uc *) stbi__malloc(x * y * out_n); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + img_len = (img_width_bytes + 1) * y; + if (s->img_x == x && s->img_y == y) { + if (raw_len != img_len) return stbi__err("not enough pixels","Corrupt PNG"); + } else { // interlaced: + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + } + + for (j=0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *prior = cur - stride; + int filter = *raw++; + int filter_bytes = img_n; + int width = x; + if (filter > 4) + return stbi__err("invalid filter","Corrupt PNG"); + + if (depth < 8) { + STBI_ASSERT(img_width_bytes <= x); + cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place + filter_bytes = 1; + width = img_width_bytes; + } + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // handle first byte explicitly + for (k=0; k < filter_bytes; ++k) { + switch (filter) { + case STBI__F_none : cur[k] = raw[k]; break; + case STBI__F_sub : cur[k] = raw[k]; break; + case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; + case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; + case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; + case STBI__F_avg_first : cur[k] = raw[k]; break; + case STBI__F_paeth_first: cur[k] = raw[k]; break; + } + } + + if (depth == 8) { + if (img_n != out_n) + cur[img_n] = 255; // first pixel + raw += img_n; + cur += out_n; + prior += out_n; + } else { + raw += 1; + cur += 1; + prior += 1; + } + + // this is a little gross, so that we don't switch per-pixel or per-component + if (depth < 8 || img_n == out_n) { + int nk = (width - 1)*img_n; + #define CASE(f) \ + case f: \ + for (k=0; k < nk; ++k) + switch (filter) { + // "none" filter turns into a memcpy here; make that explicit. + case STBI__F_none: memcpy(cur, raw, nk); break; + CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); break; + CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; + CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); break; + CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); break; + CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); break; + CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); break; + } + #undef CASE + raw += nk; + } else { + STBI_ASSERT(img_n+1 == out_n); + #define CASE(f) \ + case f: \ + for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \ + for (k=0; k < img_n; ++k) + switch (filter) { + CASE(STBI__F_none) cur[k] = raw[k]; break; + CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-out_n]); break; + CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; + CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-out_n])>>1)); break; + CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-out_n],prior[k],prior[k-out_n])); break; + CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-out_n] >> 1)); break; + CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-out_n],0,0)); break; + } + #undef CASE + } + } + + // we make a separate pass to expand bits to pixels; for performance, + // this could run two scanlines behind the above code, so it won't + // intefere with filtering but will still be in the cache. + if (depth < 8) { + for (j=0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; + // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit + // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + + // note that the final byte might overshoot and write more data than desired. + // we can allocate enough data that this never writes out of memory, but it + // could also overwrite the next scanline. can it overwrite non-empty data + // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. + // so we need to explicitly clamp the final ones + + if (depth == 4) { + for (k=x*img_n; k >= 2; k-=2, ++in) { + *cur++ = scale * ((*in >> 4) ); + *cur++ = scale * ((*in ) & 0x0f); + } + if (k > 0) *cur++ = scale * ((*in >> 4) ); + } else if (depth == 2) { + for (k=x*img_n; k >= 4; k-=4, ++in) { + *cur++ = scale * ((*in >> 6) ); + *cur++ = scale * ((*in >> 4) & 0x03); + *cur++ = scale * ((*in >> 2) & 0x03); + *cur++ = scale * ((*in ) & 0x03); + } + if (k > 0) *cur++ = scale * ((*in >> 6) ); + if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); + if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); + } else if (depth == 1) { + for (k=x*img_n; k >= 8; k-=8, ++in) { + *cur++ = scale * ((*in >> 7) ); + *cur++ = scale * ((*in >> 6) & 0x01); + *cur++ = scale * ((*in >> 5) & 0x01); + *cur++ = scale * ((*in >> 4) & 0x01); + *cur++ = scale * ((*in >> 3) & 0x01); + *cur++ = scale * ((*in >> 2) & 0x01); + *cur++ = scale * ((*in >> 1) & 0x01); + *cur++ = scale * ((*in ) & 0x01); + } + if (k > 0) *cur++ = scale * ((*in >> 7) ); + if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); + if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); + if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); + if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); + if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); + if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); + } + if (img_n != out_n) { + int q; + // insert alpha = 255 + cur = a->out + stride*j; + if (img_n == 1) { + for (q=x-1; q >= 0; --q) { + cur[q*2+1] = 255; + cur[q*2+0] = cur[q]; + } + } else { + STBI_ASSERT(img_n == 3); + for (q=x-1; q >= 0; --q) { + cur[q*4+3] = 255; + cur[q*4+2] = cur[q*3+2]; + cur[q*4+1] = cur[q*3+1]; + cur[q*4+0] = cur[q*3+0]; + } + } + } + } + } + + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *) stbi__malloc(a->s->img_x * a->s->img_y * out_n); + for (p=0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i,j,x,y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j=0; j < y; ++j) { + for (i=0; i < x; ++i) { + int out_y = j*yspc[p]+yorig[p]; + int out_x = i*xspc[p]+xorig[p]; + memcpy(final + out_y*a->s->img_x*out_n + out_x*out_n, + a->out + (j*x+i)*out_n, out_n); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i=0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i=0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *) stbi__malloc(pixel_count * pal_img_n); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p += 3; + } + } else { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p[3] = palette[n+3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load = 0; +static int stbi__de_iphone_flag = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag = flag_true_if_should_convert; +} + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i=0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + p[0] = p[2] * 255 / a; + p[1] = p[1] * 255 / a; + p[2] = t * 255 / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d)) + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n=0; + stbi_uc has_trans=0, tc[3]; + stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; + int first=1,k,interlace=0, color=0, depth=0, is_iphone=0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C','g','B','I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I','H','D','R'): { + int comp,filter; + if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); + s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); + s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); + depth = stbi__get8(s); if (depth != 1 && depth != 2 && depth != 4 && depth != 8) return stbi__err("1/2/4/8-bit only","PNG not supported: 1/2/4/8-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); + filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + if (scan == STBI__SCAN_header) return 1; + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + // if SCAN_header, have to scan to see if we have a tRNS + } + break; + } + + case STBI__PNG_TYPE('P','L','T','E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); + for (i=0; i < pal_len; ++i) { + palette[i*4+0] = stbi__get8(s); + palette[i*4+1] = stbi__get8(s); + palette[i*4+2] = stbi__get8(s); + palette[i*4+3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t','R','N','S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); + pal_img_n = 4; + for (i=0; i < c.length; ++i) + palette[i*4+3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); + if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); + has_trans = 1; + for (k=0; k < s->img_n; ++k) + tc[k] = (stbi_uc) (stbi__get16be(s) & 255) * stbi__depth_scale_table[depth]; // non 8-bit images will be larger + } + break; + } + + case STBI__PNG_TYPE('I','D','A','T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); + if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I','E','N','D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n+1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, depth, color, interlace)) return 0; + if (has_trans) + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } + STBI_FREE(z->expanded); z->expanded = NULL; + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { + #ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); + #endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp) +{ + unsigned char *result=NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_out_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x,y,comp,req_comp); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind( p->s ); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n=0; + if (z == 0) return -1; + if (z >= 0x10000) n += 16, z >>= 16; + if (z >= 0x00100) n += 8, z >>= 8; + if (z >= 0x00010) n += 4, z >>= 4; + if (z >= 0x00004) n += 2, z >>= 2; + if (z >= 0x00002) n += 1, z >>= 1; + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +static int stbi__shiftsigned(int v, int shift, int bits) +{ + int result; + int z=0; + + if (shift < 0) v <<= -shift; + else v >>= shift; + result = v; + + z = bits; + while (z < 8) { + result += v >> z; + z += bits; + } + return result; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; +} stbi__bmp_data; + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (info->bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit"); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + info->mr = info->mg = info->mb = 0; + if (compress == 0) { + if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } + } else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + stbi__get32le(s); // discard color space + for (i=0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void *) 1; +} + + +static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - 14 - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - 14 - info.hsz) >> 2; + } + + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + out = (stbi_uc *) stbi__malloc(target * s->img_x * s->img_y); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z=0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i=0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - 14 - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width)&3; + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } else { + int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; + int z = 0; + int easy=0; + stbi__skip(s, info.offset - 14 - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; + else /* bpp = 32 and pad = 0 */ width=0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + } + for (j=0; j < (int) s->img_y; ++j) { + if (easy) { + for (i=0; i < (int) s->img_x; ++i) { + unsigned char a; + out[z+2] = stbi__get8(s); + out[z+1] = stbi__get8(s); + out[z+0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } else { + int bpp = info.bpp; + for (i=0; i < (int) s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); + int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j=0; j < (int) s->img_y>>1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; + for (i=0; i < (int) s->img_x*target; ++i) { + t = p1[i], p1[i] = p2[i], p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if(is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // else: fall-through + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fall-through + case 32: return bits_per_pixel/8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if( tga_w < 1 ) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if( tga_h < 1 ) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (r * 255)/31; + out[1] = (g * 255)/31; + out[2] = (b * 255)/31; + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16=0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4]; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + + // do a tiny bit of precessing + if ( tga_image_type >= 8 ) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + tga_data = (unsigned char*)stbi__malloc( (size_t)tga_width * tga_height * tga_comp ); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset ); + + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { + for (i=0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height -i - 1 : i; + stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if ( tga_indexed) + { + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start ); + // load the palette + tga_palette = (unsigned char*)stbi__malloc( tga_palette_len * tga_comp ); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i=0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if ( tga_is_RLE ) + { + if ( RLE_count == 0 ) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if ( !RLE_repeating ) + { + read_next_pixel = 1; + } + } else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if ( read_next_pixel ) + { + // load however much data we did have + if ( tga_indexed ) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx+j]; + } + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp+j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if ( tga_inverted ) + { + for (j = 0; j*2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if ( tga_palette != NULL ) + { + STBI_FREE( tga_palette ); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i=0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + int pixelCount; + int channelCount, compression; + int channel, i, count, len; + int bitdepth; + int w,h; + stbi_uc *out; + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6 ); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s,stbi__get32be(s) ); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s) ); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s) ); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Create the destination image. + out = (stbi_uc *) stbi__malloc(4 * w*h); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2 ); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out+channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } else { + // Read the RLE data. + count = 0; + while (count < pixelCount) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len ^= 0x0FF; + len += 2; + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + } + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out + channel; + if (channel >= channelCount) { + // Fill this channel with default data. + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } else { + // Read the data. + if (bitdepth == 16) { + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + + if (req_comp && req_comp != 4) { + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context *s,const char *str) +{ + int i; + for (i=0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) + return 0; + + for(i=0;i<84;++i) + stbi__get8(s); + + if (!stbi__pic_is4(s,"PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size,type,channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask=0x80, i; + + for (i=0; i<4; ++i, mask>>=1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); + dest[i]=stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) +{ + int mask=0x80,i; + + for (i=0;i<4; ++i, mask>>=1) + if (channel&mask) + dest[i]=src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) +{ + int act_comp=0,num_packets=0,y,chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return stbi__errpuc("bad format","too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for(y=0; ytype) { + default: + return stbi__errpuc("bad format","packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for(x=0;xchannel,dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left=width, i; + + while (left>0) { + stbi_uc count,value[4]; + + count=stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); + + if (count > left) + count = (stbi_uc) left; + + if (!stbi__readval(s,packet->channel,value)) return 0; + + for(i=0; ichannel,dest,value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left=width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count==128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file","scanline overrun"); + + if (!stbi__readval(s,packet->channel,value)) + return 0; + + for(i=0;ichannel,dest,value); + } else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file","scanline overrun"); + + for(i=0;ichannel,dest)) + return 0; + } + left-=count; + } + break; + } + } + } + } + + return result; +} + +static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp) +{ + stbi_uc *result; + int i, x,y; + + for (i=0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); + if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *) stbi__malloc(x*y*4); + memset(result, 0xff, x*y*4); + + if (!stbi__pic_load_core(s,x,y,comp, result)) { + STBI_FREE(result); + result=0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result=stbi__convert_format(result,4,req_comp,x,y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w,h; + stbi_uc *out, *old_out; // output buffer (always 4 components) + int flags, bgindex, ratio, transparent, eflags, delay; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[4096]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i=0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif g; + if (!stbi__gif_header(s, &g, comp, 1)) { + stbi__rewind( s ); + return 0; + } + if (x) *x = g.w; + if (y) *y = g.h; + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + p = &g->out[g->cur_x + g->cur_y]; + c = &g->color_table[g->codes[code].suffix * 4]; + + if (c[3] >= 128) { + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc) init_code; + g->codes[init_code].suffix = (stbi_uc) init_code; + } + + // support no starting clear code + avail = clear+2; + oldcode = -1; + + len = 0; + for(;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32) stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s,len); + return g->out; + } else if (code <= avail) { + if (first) return stbi__errpuc("no clear code", "Corrupt GIF"); + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF"); + p->prefix = (stbi__int16) oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16) code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +static void stbi__fill_gif_background(stbi__gif *g, int x0, int y0, int x1, int y1) +{ + int x, y; + stbi_uc *c = g->pal[g->bgindex]; + for (y = y0; y < y1; y += 4 * g->w) { + for (x = x0; x < x1; x += 4) { + stbi_uc *p = &g->out[y + x]; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = 0; + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp) +{ + int i; + stbi_uc *prev_out = 0; + + if (g->out == 0 && !stbi__gif_header(s, g, comp,0)) + return 0; // stbi__g_failure_reason set by stbi__gif_header + + prev_out = g->out; + g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h); + if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); + + switch ((g->eflags & 0x1C) >> 2) { + case 0: // unspecified (also always used on 1st frame) + stbi__fill_gif_background(g, 0, 0, 4 * g->w, 4 * g->w * g->h); + break; + case 1: // do not dispose + if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); + g->old_out = prev_out; + break; + case 2: // dispose to background + if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); + stbi__fill_gif_background(g, g->start_x, g->start_y, g->max_x, g->max_y); + break; + case 3: // dispose to previous + if (g->old_out) { + for (i = g->start_y; i < g->max_y; i += 4 * g->w) + memcpy(&g->out[i + g->start_x], &g->old_out[i + g->start_x], g->max_x - g->start_x); + } + break; + } + + for (;;) { + switch (stbi__get8(s)) { + case 0x2C: /* Image Descriptor */ + { + int prev_trans = -1; + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *) g->lpal; + } else if (g->flags & 0x80) { + if (g->transparent >= 0 && (g->eflags & 0x01)) { + prev_trans = g->pal[g->transparent][3]; + g->pal[g->transparent][3] = 0; + } + g->color_table = (stbi_uc *) g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (o == NULL) return NULL; + + if (prev_trans != -1) + g->pal[g->transparent][3] = (stbi_uc) prev_trans; + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + if (stbi__get8(s) == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = stbi__get16le(s); + g->transparent = stbi__get8(s); + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) + stbi__skip(s, len); + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *) s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } + + STBI_NOTUSED(req_comp); +} + +static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + + u = stbi__gif_load_next(s, &g, comp, req_comp); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } + else if (g.out) + STBI_FREE(g.out); + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s,x,y,comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s) +{ + const char *signature = "#?RADIANCE\n"; + int i; + for (i=0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s); + stbi__rewind(s); + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len=0; + char c = '\0'; + + c = (char) stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN-1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char) stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if ( input[3] != 0 ) { + float f1; + // Exponent + f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1,c2, z; + + + // Check identifier + if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int) strtol(token, NULL, 10); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + // Read data + hdr_data = (float *) stbi__malloc(height * width * req_comp * sizeof(float)); + + // Load image data + // image data is stored as some number of sca + if ( width < 8 || width >= 32768) { + // Read flat data + for (j=0; j < height; ++j) { + for (i=0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc) c1; + rgbe[1] = (stbi_uc) c2; + rgbe[2] = (stbi_uc) len; + rgbe[3] = (stbi_uc) stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) scanline = (stbi_uc *) stbi__malloc(width * 4); + + for (k = 0; k < 4; ++k) { + i = 0; + while (i < width) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i=0; i < width; ++i) + stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); + } + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind( s ); + return 0; + } + + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind( s ); + return 0; + } + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *y = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *x = (int) strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + stbi__rewind( s ); + if (p == NULL) + return 0; + *x = s->img_x; + *y = s->img_y; + *comp = info.ma ? 4 : 3; + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + if (stbi__get16be(s) != 8) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp=0,num_packets=0,chained; + stbi__pic_packet packets[10]; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind( s); + return 0; + } + if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind( s ); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind( s ); + return 0; + } + if (packet->size != 8) { + stbi__rewind( s ); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) +// Does not support 16-bit-per-channel + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context *s) +{ + char p, t; + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind( s ); + return 0; + } + return 1; +} + +static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi_uc *out; + if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) + return 0; + *x = s->img_x; + *y = s->img_y; + *comp = s->img_n; + + out = (stbi_uc *) stbi__malloc(s->img_n * s->img_x * s->img_y); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + stbi__getn(s, out, s->img_n * s->img_x * s->img_y); + + if (req_comp && req_comp != s->img_n) { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context *s, char *c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value*10 + (*c - '0'); + *c = (char) stbi__get8(s); + } + + return value; +} + +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) +{ + int maxv; + char c, p, t; + + stbi__rewind( s ); + + // Get identifier + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind( s ); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char) stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + + if (maxv > 255) + return stbi__err("max value > 255", "PPM image not 8-bit"); + else + return 1; +} +#endif + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ + #ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; + #endif + + // test tga last because it's a crappy test! + #ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; + #endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s,x,y,comp); + fseek(f,pos,SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__info_main(&s,x,y,comp); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) fix compiler warnings + partial animated GIF support + limited 16-bpc PSD support + #ifdef unused functions + bug with < 92 byte PIC,PNM,HDR,TGA + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) extra corruption checking (mmozeiko) + stbi_set_flip_vertically_on_load (nguillemot) + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) + progressive JPEG (stb) + PGM/PPM support (Ken Miller) + STBI_MALLOC,STBI_REALLOC,STBI_FREE + GIF bugfix -- seemingly never worked + STBI_NO_*, STBI_ONLY_* + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) + optimize PNG (ryg) + fix bug in interlaced PNG with user-specified channel count (stb) + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 (2008-08-02) + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 (2006-11-19) + first released version +*/ + diff --git a/libs/stb/include/stb_image_write.h b/libs/stb/include/stb_image_write.h new file mode 100644 index 0000000..1bb99e1 --- /dev/null +++ b/libs/stb/include/stb_image_write.h @@ -0,0 +1,1045 @@ +/* stb_image_write - v1.01 - public domain - http://nothings.org/stb/stb_image_write.h + writes out PNG/BMP/TGA images to C stdio - Sean Barrett 2010-2015 + no warranty implied; use at your own risk + + Before #including, + + #define STB_IMAGE_WRITE_IMPLEMENTATION + + in the file that you want to have the implementation. + + Will probably not work correctly with strict-aliasing optimizations. + +ABOUT: + + This header file is a library for writing images to C stdio. It could be + adapted to write to memory or a general streaming interface; let me know. + + The PNG output is not optimal; it is 20-50% larger than the file + written by a decent optimizing implementation. This library is designed + for source code compactness and simplicity, not optimal image file size + or run-time performance. + +BUILDING: + + You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. + You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace + malloc,realloc,free. + You can define STBIW_MEMMOVE() to replace memmove() + +USAGE: + + There are four functions, one for each image file format: + + int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); + int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); + int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); + int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); + + There are also four equivalent functions that use an arbitrary write function. You are + expected to open/close your file-equivalent before and after calling these: + + int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); + int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); + int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); + int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); + + where the callback is: + void stbi_write_func(void *context, void *data, int size); + + You can define STBI_WRITE_NO_STDIO to disable the file variant of these + functions, so the library will not use stdio.h at all. However, this will + also disable HDR writing, because it requires stdio for formatted output. + + Each function returns 0 on failure and non-0 on success. + + The functions create an image file defined by the parameters. The image + is a rectangle of pixels stored from left-to-right, top-to-bottom. + Each pixel contains 'comp' channels of data stored interleaved with 8-bits + per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is + monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. + The *data pointer points to the first byte of the top-left-most pixel. + For PNG, "stride_in_bytes" is the distance in bytes from the first byte of + a row of pixels to the first byte of the next row of pixels. + + PNG creates output files with the same number of components as the input. + The BMP format expands Y to RGB in the file format and does not + output alpha. + + PNG supports writing rectangles of data even when the bytes storing rows of + data are not consecutive in memory (e.g. sub-rectangles of a larger image), + by supplying the stride between the beginning of adjacent rows. The other + formats do not. (Thus you cannot write a native-format BMP through the BMP + writer, both because it is in BGR order and because it may have padding + at the end of the line.) + + HDR expects linear float data. Since the format is always 32-bit rgb(e) + data, alpha (if provided) is discarded, and for monochrome data it is + replicated across all three channels. + + TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed + data, set the global variable 'stbi_write_tga_with_rle' to 0. + +CREDITS: + + PNG/BMP/TGA + Sean Barrett + HDR + Baldur Karlsson + TGA monochrome: + Jean-Sebastien Guay + misc enhancements: + Tim Kelsey + TGA RLE + Alan Hickman + initial file IO callback implementation + Emmanuel Julien + bugfixes: + github:Chribba + Guillaume Chereau + github:jry2 + github:romigrou + Sergio Gonzalez + Jonas Karlsson + Filip Wasil + +LICENSE + +This software is in the public domain. Where that dedication is not +recognized, you are granted a perpetual, irrevocable license to copy, +distribute, and modify this file as you see fit. + +*/ + +#ifndef INCLUDE_STB_IMAGE_WRITE_H +#define INCLUDE_STB_IMAGE_WRITE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef STB_IMAGE_WRITE_STATIC +#define STBIWDEF static +#else +#define STBIWDEF extern +extern int stbi_write_tga_with_rle; +#endif + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); +STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); +#endif + +typedef void stbi_write_func(void *context, void *data, int size); + +STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); +STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); + +#ifdef __cplusplus +} +#endif + +#endif//INCLUDE_STB_IMAGE_WRITE_H + +#ifdef STB_IMAGE_WRITE_IMPLEMENTATION + +#ifdef _WIN32 + #ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #endif + #ifndef _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_NONSTDC_NO_DEPRECATE + #endif +#endif + +#ifndef STBI_WRITE_NO_STDIO +#include +#endif // STBI_WRITE_NO_STDIO + +#include +#include +#include +#include + +#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) +// ok +#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." +#endif + +#ifndef STBIW_MALLOC +#define STBIW_MALLOC(sz) malloc(sz) +#define STBIW_REALLOC(p,newsz) realloc(p,newsz) +#define STBIW_FREE(p) free(p) +#endif + +#ifndef STBIW_REALLOC_SIZED +#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) +#endif + + +#ifndef STBIW_MEMMOVE +#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) +#endif + + +#ifndef STBIW_ASSERT +#include +#define STBIW_ASSERT(x) assert(x) +#endif + +#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) + +typedef struct +{ + stbi_write_func *func; + void *context; +} stbi__write_context; + +// initialize a callback-based context +static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) +{ + s->func = c; + s->context = context; +} + +#ifndef STBI_WRITE_NO_STDIO + +static void stbi__stdio_write(void *context, void *data, int size) +{ + fwrite(data,1,size,(FILE*) context); +} + +static int stbi__start_write_file(stbi__write_context *s, const char *filename) +{ + FILE *f = fopen(filename, "wb"); + stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); + return f != NULL; +} + +static void stbi__end_write_file(stbi__write_context *s) +{ + fclose((FILE *)s->context); +} + +#endif // !STBI_WRITE_NO_STDIO + +typedef unsigned int stbiw_uint32; +typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; + +#ifdef STB_IMAGE_WRITE_STATIC +static int stbi_write_tga_with_rle = 1; +#else +int stbi_write_tga_with_rle = 1; +#endif + +static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) +{ + while (*fmt) { + switch (*fmt++) { + case ' ': break; + case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); + s->func(s->context,&x,1); + break; } + case '2': { int x = va_arg(v,int); + unsigned char b[2]; + b[0] = STBIW_UCHAR(x); + b[1] = STBIW_UCHAR(x>>8); + s->func(s->context,b,2); + break; } + case '4': { stbiw_uint32 x = va_arg(v,int); + unsigned char b[4]; + b[0]=STBIW_UCHAR(x); + b[1]=STBIW_UCHAR(x>>8); + b[2]=STBIW_UCHAR(x>>16); + b[3]=STBIW_UCHAR(x>>24); + s->func(s->context,b,4); + break; } + default: + STBIW_ASSERT(0); + return; + } + } +} + +static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) +{ + va_list v; + va_start(v, fmt); + stbiw__writefv(s, fmt, v); + va_end(v); +} + +static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) +{ + unsigned char arr[3]; + arr[0] = a, arr[1] = b, arr[2] = c; + s->func(s->context, arr, 3); +} + +static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) +{ + unsigned char bg[3] = { 255, 0, 255}, px[3]; + int k; + + if (write_alpha < 0) + s->func(s->context, &d[comp - 1], 1); + + switch (comp) { + case 1: + s->func(s->context,d,1); + break; + case 2: + if (expand_mono) + stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp + else + s->func(s->context, d, 1); // monochrome TGA + break; + case 4: + if (!write_alpha) { + // composite against pink background + for (k = 0; k < 3; ++k) + px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; + stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); + break; + } + /* FALLTHROUGH */ + case 3: + stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); + break; + } + if (write_alpha > 0) + s->func(s->context, &d[comp - 1], 1); +} + +static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) +{ + stbiw_uint32 zero = 0; + int i,j, j_end; + + if (y <= 0) + return; + + if (vdir < 0) + j_end = -1, j = y-1; + else + j_end = y, j = 0; + + for (; j != j_end; j += vdir) { + for (i=0; i < x; ++i) { + unsigned char *d = (unsigned char *) data + (j*x+i)*comp; + stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); + } + s->func(s->context, &zero, scanline_pad); + } +} + +static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) +{ + if (y < 0 || x < 0) { + return 0; + } else { + va_list v; + va_start(v, fmt); + stbiw__writefv(s, fmt, v); + va_end(v); + stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); + return 1; + } +} + +static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) +{ + int pad = (-x*3) & 3; + return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, + "11 4 22 4" "4 44 22 444444", + 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header + 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header +} + +STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_bmp_core(&s, x, y, comp, data); +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_bmp_core(&s, x, y, comp, data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif //!STBI_WRITE_NO_STDIO + +static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) +{ + int has_alpha = (comp == 2 || comp == 4); + int colorbytes = has_alpha ? comp-1 : comp; + int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 + + if (y < 0 || x < 0) + return 0; + + if (!stbi_write_tga_with_rle) { + return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, + "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); + } else { + int i,j,k; + + stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); + + for (j = y - 1; j >= 0; --j) { + unsigned char *row = (unsigned char *) data + j * x * comp; + int len; + + for (i = 0; i < x; i += len) { + unsigned char *begin = row + i * comp; + int diff = 1; + len = 1; + + if (i < x - 1) { + ++len; + diff = memcmp(begin, row + (i + 1) * comp, comp); + if (diff) { + const unsigned char *prev = begin; + for (k = i + 2; k < x && len < 128; ++k) { + if (memcmp(prev, row + k * comp, comp)) { + prev += comp; + ++len; + } else { + --len; + break; + } + } + } else { + for (k = i + 2; k < x && len < 128; ++k) { + if (!memcmp(begin, row + k * comp, comp)) { + ++len; + } else { + break; + } + } + } + } + + if (diff) { + unsigned char header = STBIW_UCHAR(len - 1); + s->func(s->context, &header, 1); + for (k = 0; k < len; ++k) { + stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); + } + } else { + unsigned char header = STBIW_UCHAR(len - 129); + s->func(s->context, &header, 1); + stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); + } + } + } + } + return 1; +} + +int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_tga_core(&s, x, y, comp, (void *) data); +} + +#ifndef STBI_WRITE_NO_STDIO +int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) +{ + stbi__write_context s; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR writer +// by Baldur Karlsson +#ifndef STBI_WRITE_NO_STDIO + +#define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) + +void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) +{ + int exponent; + float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); + + if (maxcomp < 1e-32f) { + rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; + } else { + float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; + + rgbe[0] = (unsigned char)(linear[0] * normalize); + rgbe[1] = (unsigned char)(linear[1] * normalize); + rgbe[2] = (unsigned char)(linear[2] * normalize); + rgbe[3] = (unsigned char)(exponent + 128); + } +} + +void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) +{ + unsigned char lengthbyte = STBIW_UCHAR(length+128); + STBIW_ASSERT(length+128 <= 255); + s->func(s->context, &lengthbyte, 1); + s->func(s->context, &databyte, 1); +} + +void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) +{ + unsigned char lengthbyte = STBIW_UCHAR(length); + STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code + s->func(s->context, &lengthbyte, 1); + s->func(s->context, data, length); +} + +void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) +{ + unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; + unsigned char rgbe[4]; + float linear[3]; + int x; + + scanlineheader[2] = (width&0xff00)>>8; + scanlineheader[3] = (width&0x00ff); + + /* skip RLE for images too small or large */ + if (width < 8 || width >= 32768) { + for (x=0; x < width; x++) { + switch (ncomp) { + case 4: /* fallthrough */ + case 3: linear[2] = scanline[x*ncomp + 2]; + linear[1] = scanline[x*ncomp + 1]; + linear[0] = scanline[x*ncomp + 0]; + break; + default: + linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; + break; + } + stbiw__linear_to_rgbe(rgbe, linear); + s->func(s->context, rgbe, 4); + } + } else { + int c,r; + /* encode into scratch buffer */ + for (x=0; x < width; x++) { + switch(ncomp) { + case 4: /* fallthrough */ + case 3: linear[2] = scanline[x*ncomp + 2]; + linear[1] = scanline[x*ncomp + 1]; + linear[0] = scanline[x*ncomp + 0]; + break; + default: + linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; + break; + } + stbiw__linear_to_rgbe(rgbe, linear); + scratch[x + width*0] = rgbe[0]; + scratch[x + width*1] = rgbe[1]; + scratch[x + width*2] = rgbe[2]; + scratch[x + width*3] = rgbe[3]; + } + + s->func(s->context, scanlineheader, 4); + + /* RLE each component separately */ + for (c=0; c < 4; c++) { + unsigned char *comp = &scratch[width*c]; + + x = 0; + while (x < width) { + // find first run + r = x; + while (r+2 < width) { + if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) + break; + ++r; + } + if (r+2 >= width) + r = width; + // dump up to first run + while (x < r) { + int len = r-x; + if (len > 128) len = 128; + stbiw__write_dump_data(s, len, &comp[x]); + x += len; + } + // if there's a run, output it + if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd + // find next byte after run + while (r < width && comp[r] == comp[x]) + ++r; + // output run up to r + while (x < r) { + int len = r-x; + if (len > 127) len = 127; + stbiw__write_run_data(s, len, comp[x]); + x += len; + } + } + } + } + } +} + +static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) +{ + if (y <= 0 || x <= 0 || data == NULL) + return 0; + else { + // Each component is stored separately. Allocate scratch space for full output scanline. + unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); + int i, len; + char buffer[128]; + char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; + s->func(s->context, header, sizeof(header)-1); + + len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); + s->func(s->context, buffer, len); + + for(i=0; i < y; i++) + stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*i*x); + STBIW_FREE(scratch); + return 1; + } +} + +int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) +{ + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_hdr_core(&s, x, y, comp, (float *) data); +} + +int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) +{ + stbi__write_context s; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif // STBI_WRITE_NO_STDIO + + +////////////////////////////////////////////////////////////////////////////// +// +// PNG writer +// + +// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() +#define stbiw__sbraw(a) ((int *) (a) - 2) +#define stbiw__sbm(a) stbiw__sbraw(a)[0] +#define stbiw__sbn(a) stbiw__sbraw(a)[1] + +#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) +#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) +#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) + +#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) +#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) +#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) + +static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) +{ + int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; + void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); + STBIW_ASSERT(p); + if (p) { + if (!*arr) ((int *) p)[1] = 0; + *arr = (void *) ((int *) p + 2); + stbiw__sbm(*arr) = m; + } + return *arr; +} + +static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) +{ + while (*bitcount >= 8) { + stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); + *bitbuffer >>= 8; + *bitcount -= 8; + } + return data; +} + +static int stbiw__zlib_bitrev(int code, int codebits) +{ + int res=0; + while (codebits--) { + res = (res << 1) | (code & 1); + code >>= 1; + } + return res; +} + +static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) +{ + int i; + for (i=0; i < limit && i < 258; ++i) + if (a[i] != b[i]) break; + return i; +} + +static unsigned int stbiw__zhash(unsigned char *data) +{ + stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); + hash ^= hash << 3; + hash += hash >> 5; + hash ^= hash << 4; + hash += hash >> 17; + hash ^= hash << 25; + hash += hash >> 6; + return hash; +} + +#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) +#define stbiw__zlib_add(code,codebits) \ + (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) +#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) +// default huffman tables +#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) +#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) +#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) +#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) +#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) +#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) + +#define stbiw__ZHASH 16384 + +unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) +{ + static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 }; + static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; + static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 }; + static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; + unsigned int bitbuf=0; + int i,j, bitcount=0; + unsigned char *out = NULL; + unsigned char **hash_table[stbiw__ZHASH]; // 64KB on the stack! + if (quality < 5) quality = 5; + + stbiw__sbpush(out, 0x78); // DEFLATE 32K window + stbiw__sbpush(out, 0x5e); // FLEVEL = 1 + stbiw__zlib_add(1,1); // BFINAL = 1 + stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman + + for (i=0; i < stbiw__ZHASH; ++i) + hash_table[i] = NULL; + + i=0; + while (i < data_len-3) { + // hash next 3 bytes of data to be compressed + int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; + unsigned char *bestloc = 0; + unsigned char **hlist = hash_table[h]; + int n = stbiw__sbcount(hlist); + for (j=0; j < n; ++j) { + if (hlist[j]-data > i-32768) { // if entry lies within window + int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); + if (d >= best) best=d,bestloc=hlist[j]; + } + } + // when hash table entry is too long, delete half the entries + if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { + STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); + stbiw__sbn(hash_table[h]) = quality; + } + stbiw__sbpush(hash_table[h],data+i); + + if (bestloc) { + // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal + h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); + hlist = hash_table[h]; + n = stbiw__sbcount(hlist); + for (j=0; j < n; ++j) { + if (hlist[j]-data > i-32767) { + int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); + if (e > best) { // if next match is better, bail on current match + bestloc = NULL; + break; + } + } + } + } + + if (bestloc) { + int d = (int) (data+i - bestloc); // distance back + STBIW_ASSERT(d <= 32767 && best <= 258); + for (j=0; best > lengthc[j+1]-1; ++j); + stbiw__zlib_huff(j+257); + if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); + for (j=0; d > distc[j+1]-1; ++j); + stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); + if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); + i += best; + } else { + stbiw__zlib_huffb(data[i]); + ++i; + } + } + // write out final bytes + for (;i < data_len; ++i) + stbiw__zlib_huffb(data[i]); + stbiw__zlib_huff(256); // end of block + // pad with 0 bits to byte boundary + while (bitcount) + stbiw__zlib_add(0,1); + + for (i=0; i < stbiw__ZHASH; ++i) + (void) stbiw__sbfree(hash_table[i]); + + { + // compute adler32 on input + unsigned int s1=1, s2=0; + int blocklen = (int) (data_len % 5552); + j=0; + while (j < data_len) { + for (i=0; i < blocklen; ++i) s1 += data[j+i], s2 += s1; + s1 %= 65521, s2 %= 65521; + j += blocklen; + blocklen = 5552; + } + stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(s2)); + stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(s1)); + } + *out_len = stbiw__sbn(out); + // make returned pointer freeable + STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); + return (unsigned char *) stbiw__sbraw(out); +} + +static unsigned int stbiw__crc32(unsigned char *buffer, int len) +{ + static unsigned int crc_table[256] = + { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + }; + + unsigned int crc = ~0u; + int i; + for (i=0; i < len; ++i) + crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; + return ~crc; +} + +#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) +#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); +#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) + +static void stbiw__wpcrc(unsigned char **data, int len) +{ + unsigned int crc = stbiw__crc32(*data - len - 4, len+4); + stbiw__wp32(*data, crc); +} + +static unsigned char stbiw__paeth(int a, int b, int c) +{ + int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); + if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); + if (pb <= pc) return STBIW_UCHAR(b); + return STBIW_UCHAR(c); +} + +unsigned char *stbi_write_png_to_mem(unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) +{ + int ctype[5] = { -1, 0, 4, 2, 6 }; + unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; + unsigned char *out,*o, *filt, *zlib; + signed char *line_buffer; + int i,j,k,p,zlen; + + if (stride_bytes == 0) + stride_bytes = x * n; + + filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; + line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } + for (j=0; j < y; ++j) { + static int mapping[] = { 0,1,2,3,4 }; + static int firstmap[] = { 0,1,0,5,6 }; + int *mymap = j ? mapping : firstmap; + int best = 0, bestval = 0x7fffffff; + for (p=0; p < 2; ++p) { + for (k= p?best:0; k < 5; ++k) { + int type = mymap[k],est=0; + unsigned char *z = pixels + stride_bytes*j; + for (i=0; i < n; ++i) + switch (type) { + case 0: line_buffer[i] = z[i]; break; + case 1: line_buffer[i] = z[i]; break; + case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break; + case 3: line_buffer[i] = z[i] - (z[i-stride_bytes]>>1); break; + case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-stride_bytes],0)); break; + case 5: line_buffer[i] = z[i]; break; + case 6: line_buffer[i] = z[i]; break; + } + for (i=n; i < x*n; ++i) { + switch (type) { + case 0: line_buffer[i] = z[i]; break; + case 1: line_buffer[i] = z[i] - z[i-n]; break; + case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break; + case 3: line_buffer[i] = z[i] - ((z[i-n] + z[i-stride_bytes])>>1); break; + case 4: line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-stride_bytes], z[i-stride_bytes-n]); break; + case 5: line_buffer[i] = z[i] - (z[i-n]>>1); break; + case 6: line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; + } + } + if (p) break; + for (i=0; i < x*n; ++i) + est += abs((signed char) line_buffer[i]); + if (est < bestval) { bestval = est; best = k; } + } + } + // when we get here, best contains the filter type, and line_buffer contains the data + filt[j*(x*n+1)] = (unsigned char) best; + STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); + } + STBIW_FREE(line_buffer); + zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, 8); // increase 8 to get smaller but use more memory + STBIW_FREE(filt); + if (!zlib) return 0; + + // each tag requires 12 bytes of overhead + out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); + if (!out) return 0; + *out_len = 8 + 12+13 + 12+zlen + 12; + + o=out; + STBIW_MEMMOVE(o,sig,8); o+= 8; + stbiw__wp32(o, 13); // header length + stbiw__wptag(o, "IHDR"); + stbiw__wp32(o, x); + stbiw__wp32(o, y); + *o++ = 8; + *o++ = STBIW_UCHAR(ctype[n]); + *o++ = 0; + *o++ = 0; + *o++ = 0; + stbiw__wpcrc(&o,13); + + stbiw__wp32(o, zlen); + stbiw__wptag(o, "IDAT"); + STBIW_MEMMOVE(o, zlib, zlen); + o += zlen; + STBIW_FREE(zlib); + stbiw__wpcrc(&o, zlen); + + stbiw__wp32(o,0); + stbiw__wptag(o, "IEND"); + stbiw__wpcrc(&o,0); + + STBIW_ASSERT(o == out + *out_len); + + return out; +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) +{ + FILE *f; + int len; + unsigned char *png = stbi_write_png_to_mem((unsigned char *) data, stride_bytes, x, y, comp, &len); + if (png == NULL) return 0; + f = fopen(filename, "wb"); + if (!f) { STBIW_FREE(png); return 0; } + fwrite(png, 1, len, f); + fclose(f); + STBIW_FREE(png); + return 1; +} +#endif + +STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) +{ + int len; + unsigned char *png = stbi_write_png_to_mem((unsigned char *) data, stride_bytes, x, y, comp, &len); + if (png == NULL) return 0; + func(context, png, len); + STBIW_FREE(png); + return 1; +} + +#endif // STB_IMAGE_WRITE_IMPLEMENTATION + +/* Revision history + 1.01 (2016-01-16) + STBIW_REALLOC_SIZED: support allocators with no realloc support + avoid race-condition in crc initialization + minor compile issues + 1.00 (2015-09-14) + installable file IO function + 0.99 (2015-09-13) + warning fixes; TGA rle support + 0.98 (2015-04-08) + added STBIW_MALLOC, STBIW_ASSERT etc + 0.97 (2015-01-18) + fixed HDR asserts, rewrote HDR rle logic + 0.96 (2015-01-17) + add HDR output + fix monochrome BMP + 0.95 (2014-08-17) + add monochrome TGA output + 0.94 (2014-05-31) + rename private functions to avoid conflicts with stb_image.h + 0.93 (2014-05-27) + warning fixes + 0.92 (2010-08-01) + casts to unsigned char to fix warnings + 0.91 (2010-07-17) + first public release + 0.90 first internal release +*/ + diff --git a/libs/tremor/CHANGELOG b/libs/tremor/CHANGELOG new file mode 100644 index 0000000..53f2335 --- /dev/null +++ b/libs/tremor/CHANGELOG @@ -0,0 +1,19 @@ +*** 20020517: 1.0.2 *** + + Playback bugfix to floor1; mode mistakenly used for sizing instead + of blockflag + +*** 20020515: 1.0.1 *** + + Added complete API documentation to source tarball. No code + changes. + +*** 20020412: 1.0.1 *** + + Fixed a clipping bug that affected ARM processors; negative + overflows were being properly clipped, but then clobbered to + positive by the positive overflow chec (asm_arm.h:CLIP_TO_15) + +*** 20020403: 1.0.0 *** + + Initial version \ No newline at end of file diff --git a/libs/tremor/COPYING b/libs/tremor/COPYING new file mode 100644 index 0000000..6111c6c --- /dev/null +++ b/libs/tremor/COPYING @@ -0,0 +1,28 @@ +Copyright (c) 2002, 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. diff --git a/libs/tremor/Makefile.am b/libs/tremor/Makefile.am new file mode 100644 index 0000000..0a4bb2c --- /dev/null +++ b/libs/tremor/Makefile.am @@ -0,0 +1,50 @@ +AUTOMAKE_OPTIONS = foreign + +INCLUDES = -I./ @OGG_CFLAGS@ + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = vorbisidec.pc + +lib_LTLIBRARIES = libvorbisidec.la + +libvorbisidec_la_SOURCES = mdct.c block.c window.c \ + synthesis.c info.c \ + floor1.c floor0.c vorbisfile.c \ + res012.c mapping0.c registry.c codebook.c \ + sharedbook.c \ + codebook.h misc.h mdct_lookup.h\ + os.h mdct.h block.h ivorbisfile.h lsp_lookup.h\ + registry.h window.h window_lookup.h\ + codec_internal.h backends.h \ + asm_arm.h ivorbiscodec.h +libvorbisidec_la_LDFLAGS = -version-info @V_LIB_CURRENT@:@V_LIB_REVISION@:@V_LIB_AGE@ +libvorbisidec_la_LIBADD = @OGG_LIBS@ + +EXTRA_PROGRAMS = ivorbisfile_example iseeking_example +CLEANFILES = $(EXTRA_PROGRAMS) $(lib_LTLIBRARIES) + +ivorbisfile_example_SOURCES = ivorbisfile_example.c +ivorbisfile_example_LDFLAGS = -static +ivorbisfile_example_LDADD = libvorbisidec.la @OGG_LIBS@ + +iseeking_example_SOURCES = iseeking_example.c +iseeking_example_LDFLAGS = -static +iseeking_example_LDADD = libvorbisidec.la @OGG_LIBS@ + +includedir = $(prefix)/include/tremor + +include_HEADERS = ivorbiscodec.h ivorbisfile.h config_types.h + +EXTRA_DIST = vorbisidec.pc.in \ + $(srcdir)/doc/*.html $(srcdir)/win32/VS*/libtremor/*.vcproj + +example: + -ln -fs . vorbis + $(MAKE) ivorbisfile_example + $(MAKE) iseeking_example + +debug: + $(MAKE) all CFLAGS="@DEBUG@" + +profile: + $(MAKE) all CFLAGS="@PROFILE@" diff --git a/libs/tremor/README b/libs/tremor/README new file mode 100644 index 0000000..1321175 --- /dev/null +++ b/libs/tremor/README @@ -0,0 +1,46 @@ +This README covers the Ogg Vorbis 'Tremor' integer playback codec +source as of date 2002 09 02, version 1.0.0. + + ****** + +The C source in this package will build on any ANSI C compiler and +function completely and properly on any platform. The included build +system assumes GNU build system and make tools (m4, automake, +autoconf, libtool and gmake). GCC is not required, although GCC is +the most tested compiler. To build using GNU tools, type in the +source directory: + +./autogen.sh +make + +Currently, the source implements playback in pure C on all platforms +except ARM, where a [currently] small amount of assembly (see +asm_arm.h) is used to implement 64 bit math operations and fast LSP +computation. If building on ARM without the benefit of GNU build +system tools, be sure that '_ARM_ASSEM_' is #defined by the build +system if this assembly is desired, else the resulting library will +use whatever 64 bit math builtins the compiler implements. + +No math library is required by this source. No floating point +operations are used at any point in either setup or decode. This +decoder library will properly decode any past, current or future +Vorbis I file or stream. + + ******** + +The build system produces a static and [when supported by the OS] +dynamic library named 'libvorbisidec'. This library exposes an API +nearly identical to the BSD reference library's 'libvorbisfile', +including all the features familiar to users of vorbisfile. This API +is similar enough that the proper header file to include is named +'ivorbisfile.h' [included in the source build directory]. Lower level +libvorbis-style headers and structures are in 'ivorbiscodec.h' +[included in the source build directory]. A simple example program, +ivorbisfile_example.c, can be built with 'make example'. + + ******** + +Detailed Tremor API Documentation begins at doc/index.html + +Monty +xiph.org diff --git a/libs/tremor/Version_script.in b/libs/tremor/Version_script.in new file mode 100644 index 0000000..7f22f2f --- /dev/null +++ b/libs/tremor/Version_script.in @@ -0,0 +1,62 @@ +# +# Export file for libvorbisidec +# +# Only the symbols listed in the global section will be callable from +# applications linking to libvorbisidec. +# + +@PACKAGE@.so.1 +{ + global: + ov_clear; + ov_open; + ov_open_callbacks; + ov_test; + ov_test_callbacks; + ov_test_open; + ov_bitrate; + ov_bitrate_instant; + ov_streams; + ov_seekable; + ov_serialnumber; + ov_raw_total; + ov_pcm_total; + ov_time_total; + ov_raw_seek; + ov_pcm_seek; + ov_pcm_seek_page; + ov_time_seek; + ov_time_seek_page; + ov_raw_tell; + ov_pcm_tell; + ov_time_tell; + ov_info; + ov_comment; + ov_read; + + vorbis_info_init; + vorbis_info_clear; + vorbis_info_blocksize; + vorbis_comment_init; + vorbis_comment_add; + vorbis_comment_add_tag; + vorbis_comment_query; + vorbis_comment_query_count; + vorbis_comment_clear; + vorbis_block_init; + vorbis_block_clear; + vorbis_dsp_clear; + vorbis_synthesis_idheader; + vorbis_synthesis_headerin; + vorbis_synthesis_init; + vorbis_synthesis_restart; + vorbis_synthesis; + vorbis_synthesis_trackonly; + vorbis_synthesis_blockin; + vorbis_synthesis_pcmout; + vorbis_synthesis_read; + vorbis_packet_blocksize; + + local: + *; +}; diff --git a/libs/tremor/asm_arm.h b/libs/tremor/asm_arm.h new file mode 100644 index 0000000..c3bda00 --- /dev/null +++ b/libs/tremor/asm_arm.h @@ -0,0 +1,245 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: arm7 and later wide math functions + + ********************************************************************/ + +#ifdef _ARM_ASSEM_ + +#if !defined(_V_WIDE_MATH) && !defined(_LOW_ACCURACY_) +#define _V_WIDE_MATH + +static inline ogg_int32_t MULT32(ogg_int32_t x, ogg_int32_t y) { + int lo,hi; + asm volatile("smull\t%0, %1, %2, %3" + : "=&r"(lo),"=&r"(hi) + : "%r"(x),"r"(y) + : "cc"); + return(hi); +} + +static inline ogg_int32_t MULT31(ogg_int32_t x, ogg_int32_t y) { + return MULT32(x,y)<<1; +} + +static inline ogg_int32_t MULT31_SHIFT15(ogg_int32_t x, ogg_int32_t y) { + int lo,hi; + asm volatile("smull %0, %1, %2, %3\n\t" + "movs %0, %0, lsr #15\n\t" + "adc %1, %0, %1, lsl #17\n\t" + : "=&r"(lo),"=&r"(hi) + : "%r"(x),"r"(y) + : "cc"); + return(hi); +} + +#define MB() asm volatile ("" : : : "memory") + +static inline void XPROD32(ogg_int32_t a, ogg_int32_t b, + ogg_int32_t t, ogg_int32_t v, + ogg_int32_t *x, ogg_int32_t *y) +{ + int x1, y1, l; + asm( "smull %0, %1, %4, %6\n\t" + "smlal %0, %1, %5, %7\n\t" + "rsb %3, %4, #0\n\t" + "smull %0, %2, %5, %6\n\t" + "smlal %0, %2, %3, %7" + : "=&r" (l), "=&r" (x1), "=&r" (y1), "=r" (a) + : "3" (a), "r" (b), "r" (t), "r" (v) + : "cc" ); + *x = x1; + MB(); + *y = y1; +} + +static inline void XPROD31(ogg_int32_t a, ogg_int32_t b, + ogg_int32_t t, ogg_int32_t v, + ogg_int32_t *x, ogg_int32_t *y) +{ + int x1, y1, l; + asm( "smull %0, %1, %4, %6\n\t" + "smlal %0, %1, %5, %7\n\t" + "rsb %3, %4, #0\n\t" + "smull %0, %2, %5, %6\n\t" + "smlal %0, %2, %3, %7" + : "=&r" (l), "=&r" (x1), "=&r" (y1), "=r" (a) + : "3" (a), "r" (b), "r" (t), "r" (v) + : "cc" ); + *x = x1 << 1; + MB(); + *y = y1 << 1; +} + +static inline void XNPROD31(ogg_int32_t a, ogg_int32_t b, + ogg_int32_t t, ogg_int32_t v, + ogg_int32_t *x, ogg_int32_t *y) +{ + int x1, y1, l; + asm( "rsb %2, %4, #0\n\t" + "smull %0, %1, %3, %5\n\t" + "smlal %0, %1, %2, %6\n\t" + "smull %0, %2, %4, %5\n\t" + "smlal %0, %2, %3, %6" + : "=&r" (l), "=&r" (x1), "=&r" (y1) + : "r" (a), "r" (b), "r" (t), "r" (v) + : "cc" ); + *x = x1 << 1; + MB(); + *y = y1 << 1; +} + +#endif + +#ifndef _V_CLIP_MATH +#define _V_CLIP_MATH + +static inline ogg_int32_t CLIP_TO_15(ogg_int32_t x) { + int tmp; + asm volatile("subs %1, %0, #32768\n\t" + "movpl %0, #0x7f00\n\t" + "orrpl %0, %0, #0xff\n" + "adds %1, %0, #32768\n\t" + "movmi %0, #0x8000" + : "+r"(x),"=r"(tmp) + : + : "cc"); + return(x); +} + +#endif + +#ifndef _V_LSP_MATH_ASM +#define _V_LSP_MATH_ASM + +static inline void lsp_loop_asm(ogg_uint32_t *qip,ogg_uint32_t *pip, + ogg_int32_t *qexpp, + ogg_int32_t *ilsp,ogg_int32_t wi, + ogg_int32_t m){ + + ogg_uint32_t qi=*qip,pi=*pip; + ogg_int32_t qexp=*qexpp; + + asm("mov r0,%3;" + "movs r1,%5,asr#1;" + "add r0,r0,r1,lsl#3;" + "beq 2f;\n" + "1:" + + "ldmdb r0!,{r1,r3};" + "subs r1,r1,%4;" //ilsp[j]-wi + "rsbmi r1,r1,#0;" //labs(ilsp[j]-wi) + "umull %0,r2,r1,%0;" //qi*=labs(ilsp[j]-wi) + + "subs r1,r3,%4;" //ilsp[j+1]-wi + "rsbmi r1,r1,#0;" //labs(ilsp[j+1]-wi) + "umull %1,r3,r1,%1;" //pi*=labs(ilsp[j+1]-wi) + + "cmn r2,r3;" // shift down 16? + "beq 0f;" + "add %2,%2,#16;" + "mov %0,%0,lsr #16;" + "orr %0,%0,r2,lsl #16;" + "mov %1,%1,lsr #16;" + "orr %1,%1,r3,lsl #16;" + "0:" + "cmp r0,%3;\n" + "bhi 1b;\n" + + "2:" + // odd filter assymetry + "ands r0,%5,#1;\n" + "beq 3f;\n" + "add r0,%3,%5,lsl#2;\n" + + "ldr r1,[r0,#-4];\n" + "mov r0,#0x4000;\n" + + "subs r1,r1,%4;\n" //ilsp[j]-wi + "rsbmi r1,r1,#0;\n" //labs(ilsp[j]-wi) + "umull %0,r2,r1,%0;\n" //qi*=labs(ilsp[j]-wi) + "umull %1,r3,r0,%1;\n" //pi*=labs(ilsp[j+1]-wi) + + "cmn r2,r3;\n" // shift down 16? + "beq 3f;\n" + "add %2,%2,#16;\n" + "mov %0,%0,lsr #16;\n" + "orr %0,%0,r2,lsl #16;\n" + "mov %1,%1,lsr #16;\n" + "orr %1,%1,r3,lsl #16;\n" + + //qi=(pi>>shift)*labs(ilsp[j]-wi); + //pi=(qi>>shift)*labs(ilsp[j+1]-wi); + //qexp+=shift; + + //} + + /* normalize to max 16 sig figs */ + "3:" + "mov r2,#0;" + "orr r1,%0,%1;" + "tst r1,#0xff000000;" + "addne r2,r2,#8;" + "movne r1,r1,lsr #8;" + "tst r1,#0x00f00000;" + "addne r2,r2,#4;" + "movne r1,r1,lsr #4;" + "tst r1,#0x000c0000;" + "addne r2,r2,#2;" + "movne r1,r1,lsr #2;" + "tst r1,#0x00020000;" + "addne r2,r2,#1;" + "movne r1,r1,lsr #1;" + "tst r1,#0x00010000;" + "addne r2,r2,#1;" + "mov %0,%0,lsr r2;" + "mov %1,%1,lsr r2;" + "add %2,%2,r2;" + + : "+r"(qi),"+r"(pi),"+r"(qexp) + : "r"(ilsp),"r"(wi),"r"(m) + : "r0","r1","r2","r3","cc"); + + *qip=qi; + *pip=pi; + *qexpp=qexp; +} + +static inline void lsp_norm_asm(ogg_uint32_t *qip,ogg_int32_t *qexpp){ + + ogg_uint32_t qi=*qip; + ogg_int32_t qexp=*qexpp; + + asm("tst %0,#0x0000ff00;" + "moveq %0,%0,lsl #8;" + "subeq %1,%1,#8;" + "tst %0,#0x0000f000;" + "moveq %0,%0,lsl #4;" + "subeq %1,%1,#4;" + "tst %0,#0x0000c000;" + "moveq %0,%0,lsl #2;" + "subeq %1,%1,#2;" + "tst %0,#0x00008000;" + "moveq %0,%0,lsl #1;" + "subeq %1,%1,#1;" + : "+r"(qi),"+r"(qexp) + : + : "cc"); + *qip=qi; + *qexpp=qexp; +} + +#endif +#endif + diff --git a/libs/tremor/autogen.sh b/libs/tremor/autogen.sh new file mode 100755 index 0000000..73c8fca --- /dev/null +++ b/libs/tremor/autogen.sh @@ -0,0 +1,120 @@ +#!/bin/sh +# Run this to set up the build system: configure, makefiles, etc. +# (based on the version in enlightenment's cvs) + +package="vorbisdec" + +olddir=`pwd` +srcdir=`dirname $0` +test -z "$srcdir" && srcdir=. + +cd "$srcdir" +DIE=0 + +echo "checking for autoconf... " +(autoconf --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "You must have autoconf installed to compile $package." + echo "Download the appropriate package for your distribution," + echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/" + DIE=1 +} + +VERSIONGREP="sed -e s/.*[^0-9\.]\([0-9]\.[0-9]\).*/\1/" +VERSIONMKINT="sed -e s/[^0-9]//" + +# do we need automake? +if test -r Makefile.am; then + AM_OPTIONS=`fgrep AUTOMAKE_OPTIONS Makefile.am` + AM_NEEDED=`echo $AM_OPTIONS | $VERSIONGREP` + if test x"$AM_NEEDED" = "x$AM_OPTIONS"; then + AM_NEEDED="" + fi + if test -z $AM_NEEDED; then + echo -n "checking for automake... " + AUTOMAKE=automake + ACLOCAL=aclocal + if ($AUTOMAKE --version < /dev/null > /dev/null 2>&1); then + echo "yes" + else + echo "no" + AUTOMAKE= + fi + else + echo -n "checking for automake $AM_NEEDED or later... " + for am in automake-$AM_NEEDED automake$AM_NEEDED automake; do + ($am --version < /dev/null > /dev/null 2>&1) || continue + ver=`$am --version < /dev/null | head -n 1 | $VERSIONGREP | $VERSIONMKINT` + verneeded=`echo $AM_NEEDED | $VERSIONMKINT` + if test $ver -ge $verneeded; then + AUTOMAKE=$am + echo $AUTOMAKE + break + fi + done + test -z $AUTOMAKE && echo "no" + echo -n "checking for aclocal $AM_NEEDED or later... " + for ac in aclocal-$AM_NEEDED aclocal$AM_NEEDED aclocal; do + ($ac --version < /dev/null > /dev/null 2>&1) || continue + ver=`$ac --version < /dev/null | head -n 1 | $VERSIONGREP | $VERSIONMKINT` + verneeded=`echo $AM_NEEDED | $VERSIONMKINT` + if test $ver -ge $verneeded; then + ACLOCAL=$ac + echo $ACLOCAL + break + fi + done + test -z $ACLOCAL && echo "no" + fi + test -z $AUTOMAKE || test -z $ACLOCAL && { + echo + echo "You must have automake installed to compile $package." + echo "Download the appropriate package for your distribution," + echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/" + exit 1 + } +fi + +echo -n "checking for libtool... " +for LIBTOOLIZE in libtoolize glibtoolize nope; do + ($LIBTOOLIZE --version) < /dev/null > /dev/null 2>&1 && break +done +if test x$LIBTOOLIZE = xnope; then + echo "nope." + LIBTOOLIZE=libtoolize +else + echo $LIBTOOLIZE +fi +($LIBTOOLIZE --version) < /dev/null > /dev/null 2>&1 || { + echo + echo "You must have libtool installed to compile $package." + echo "Download the appropriate package for your system," + echo "or get the source from one of the GNU ftp sites" + echo "listed in http://www.gnu.org/order/ftp.html" + DIE=1 +} + +if test "$DIE" -eq 1; then + exit 1 +fi + +if test -z "$*"; then + echo "I am going to run ./configure with no arguments - if you wish " + echo "to pass any to it, please specify them on the $0 command line." +fi + +echo "Generating configuration files for $package, please wait...." + +echo " $ACLOCAL $ACLOCAL_FLAGS" +$ACLOCAL $ACLOCAL_FLAGS || exit 1 +echo " $LIBTOOLIZE --automake" +$LIBTOOLIZE --automake || exit 1 +echo " autoheader" +autoheader || exit 1 +echo " $AUTOMAKE --add-missing $AUTOMAKE_FLAGS" +$AUTOMAKE --add-missing $AUTOMAKE_FLAGS || exit 1 +echo " autoconf" +autoconf || exit 1 + +cd $olddir +$srcdir/configure --enable-maintainer-mode "$@" && echo diff --git a/libs/tremor/backends.h b/libs/tremor/backends.h new file mode 100644 index 0000000..5202421 --- /dev/null +++ b/libs/tremor/backends.h @@ -0,0 +1,131 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: backend and mapping structures + + ********************************************************************/ + +/* this is exposed up here because we need it for static modes. + Lookups for each backend aren't exposed because there's no reason + to do so */ + +#ifndef _vorbis_backend_h_ +#define _vorbis_backend_h_ + +#include "codec_internal.h" + +/* this would all be simpler/shorter with templates, but.... */ +/* Transform backend generic *************************************/ + +/* only mdct right now. Flesh it out more if we ever transcend mdct + in the transform domain */ + +/* Floor backend generic *****************************************/ +typedef struct{ + vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *); + vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_mode *, + vorbis_info_floor *); + void (*free_info) (vorbis_info_floor *); + void (*free_look) (vorbis_look_floor *); + void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *); + int (*inverse2) (struct vorbis_block *,vorbis_look_floor *, + void *buffer,ogg_int32_t *); +} vorbis_func_floor; + +typedef struct{ + int order; + long rate; + long barkmap; + + int ampbits; + int ampdB; + + int numbooks; /* <= 16 */ + int books[16]; + +} vorbis_info_floor0; + +#define VIF_POSIT 63 +#define VIF_CLASS 16 +#define VIF_PARTS 31 +typedef struct{ + int partitions; /* 0 to 31 */ + int partitionclass[VIF_PARTS]; /* 0 to 15 */ + + int class_dim[VIF_CLASS]; /* 1 to 8 */ + int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1< +#include +#include +#include +#include "ivorbiscodec.h" +#include "codec_internal.h" + +#include "window.h" +#include "registry.h" +#include "misc.h" + +static int ilog(unsigned int v){ + int ret=0; + if(v)--v; + while(v){ + ret++; + v>>=1; + } + return(ret); +} + +/* pcm accumulator examples (not exhaustive): + + <-------------- lW ----------------> + <--------------- W ----------------> +: .....|..... _______________ | +: .''' | '''_--- | |\ | +:.....''' |_____--- '''......| | \_______| +:.................|__________________|_______|__|______| + |<------ Sl ------>| > Sr < |endW + |beginSl |endSl | |endSr + |beginW |endlW |beginSr + + + |< lW >| + <--------------- W ----------------> + | | .. ______________ | + | | ' `/ | ---_ | + |___.'___/`. | ---_____| + |_______|__|_______|_________________| + | >|Sl|< |<------ Sr ----->|endW + | | |endSl |beginSr |endSr + |beginW | |endlW + mult[0] |beginSl mult[n] + + <-------------- lW -----------------> + |<--W-->| +: .............. ___ | | +: .''' |`/ \ | | +:.....''' |/`....\|...| +:.........................|___|___|___| + |Sl |Sr |endW + | | |endSr + | |beginSr + | |endSl + |beginSl + |beginW +*/ + +/* block abstraction setup *********************************************/ + +#ifndef WORD_ALIGN +#define WORD_ALIGN 8 +#endif + +int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){ + memset(vb,0,sizeof(*vb)); + vb->vd=v; + vb->localalloc=0; + vb->localstore=NULL; + + return(0); +} + +void *_vorbis_block_alloc(vorbis_block *vb,long bytes){ + bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1); + if(bytes+vb->localtop>vb->localalloc){ + /* can't just _ogg_realloc... there are outstanding pointers */ + if(vb->localstore){ + struct alloc_chain *link=(struct alloc_chain *)_ogg_malloc(sizeof(*link)); + vb->totaluse+=vb->localtop; + link->next=vb->reap; + link->ptr=vb->localstore; + vb->reap=link; + } + /* highly conservative */ + vb->localalloc=bytes; + vb->localstore=_ogg_malloc(vb->localalloc); + vb->localtop=0; + } + { + void *ret=(void *)(((char *)vb->localstore)+vb->localtop); + vb->localtop+=bytes; + return ret; + } +} + +/* reap the chain, pull the ripcord */ +void _vorbis_block_ripcord(vorbis_block *vb){ + /* reap the chain */ + struct alloc_chain *reap=vb->reap; + while(reap){ + struct alloc_chain *next=reap->next; + _ogg_free(reap->ptr); + memset(reap,0,sizeof(*reap)); + _ogg_free(reap); + reap=next; + } + /* consolidate storage */ + if(vb->totaluse){ + vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc); + vb->localalloc+=vb->totaluse; + vb->totaluse=0; + } + + /* pull the ripcord */ + vb->localtop=0; + vb->reap=NULL; +} + +int vorbis_block_clear(vorbis_block *vb){ + _vorbis_block_ripcord(vb); + if(vb->localstore)_ogg_free(vb->localstore); + + memset(vb,0,sizeof(*vb)); + return(0); +} + +static int _vds_init(vorbis_dsp_state *v,vorbis_info *vi){ + int i; + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + private_state *b=NULL; + + if(ci==NULL) return 1; + + memset(v,0,sizeof(*v)); + b=(private_state *)(v->backend_state=_ogg_calloc(1,sizeof(*b))); + + v->vi=vi; + b->modebits=ilog(ci->modes); + + /* Vorbis I uses only window type 0 */ + b->window[0]=_vorbis_window(0,ci->blocksizes[0]/2); + b->window[1]=_vorbis_window(0,ci->blocksizes[1]/2); + + /* finish the codebooks */ + if(!ci->fullbooks){ + ci->fullbooks=(codebook *)_ogg_calloc(ci->books,sizeof(*ci->fullbooks)); + for(i=0;ibooks;i++){ + if(ci->book_param[i]==NULL) + goto abort_books; + if(vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i])) + goto abort_books; + /* decode codebooks are now standalone after init */ + vorbis_staticbook_destroy(ci->book_param[i]); + ci->book_param[i]=NULL; + } + } + + v->pcm_storage=ci->blocksizes[1]; + v->pcm=(ogg_int32_t **)_ogg_malloc(vi->channels*sizeof(*v->pcm)); + v->pcmret=(ogg_int32_t **)_ogg_malloc(vi->channels*sizeof(*v->pcmret)); + for(i=0;ichannels;i++) + v->pcm[i]=(ogg_int32_t *)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i])); + + /* all 1 (large block) or 0 (small block) */ + /* explicitly set for the sake of clarity */ + v->lW=0; /* previous window size */ + v->W=0; /* current window size */ + + /* initialize all the mapping/backend lookups */ + b->mode=(vorbis_look_mapping **)_ogg_calloc(ci->modes,sizeof(*b->mode)); + for(i=0;imodes;i++){ + int mapnum=ci->mode_param[i]->mapping; + int maptype=ci->map_type[mapnum]; + b->mode[i]=_mapping_P[maptype]->look(v,ci->mode_param[i], + ci->map_param[mapnum]); + } + return 0; +abort_books: + for(i=0;ibooks;i++){ + if(ci->book_param[i]!=NULL){ + vorbis_staticbook_destroy(ci->book_param[i]); + ci->book_param[i]=NULL; + } + } + vorbis_dsp_clear(v); + return -1; +} + +int vorbis_synthesis_restart(vorbis_dsp_state *v){ + vorbis_info *vi=v->vi; + codec_setup_info *ci; + + if(!v->backend_state)return -1; + if(!vi)return -1; + ci=vi->codec_setup; + if(!ci)return -1; + + v->centerW=ci->blocksizes[1]/2; + v->pcm_current=v->centerW; + + v->pcm_returned=-1; + v->granulepos=-1; + v->sequence=-1; + ((private_state *)(v->backend_state))->sample_count=-1; + + return(0); +} + +int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){ + if(_vds_init(v,vi))return 1; + vorbis_synthesis_restart(v); + + return 0; +} + +void vorbis_dsp_clear(vorbis_dsp_state *v){ + int i; + if(v){ + vorbis_info *vi=v->vi; + codec_setup_info *ci=(codec_setup_info *)(vi?vi->codec_setup:NULL); + private_state *b=(private_state *)v->backend_state; + + if(v->pcm){ + for(i=0;ichannels;i++) + if(v->pcm[i])_ogg_free(v->pcm[i]); + _ogg_free(v->pcm); + if(v->pcmret)_ogg_free(v->pcmret); + } + + /* free mode lookups; these are actually vorbis_look_mapping structs */ + if(ci){ + for(i=0;imodes;i++){ + int mapnum=ci->mode_param[i]->mapping; + int maptype=ci->map_type[mapnum]; + if(b && b->mode)_mapping_P[maptype]->free_look(b->mode[i]); + } + } + + if(b){ + if(b->mode)_ogg_free(b->mode); + _ogg_free(b); + } + + memset(v,0,sizeof(*v)); + } +} + +/* Unlike in analysis, the window is only partially applied for each + block. The time domain envelope is not yet handled at the point of + calling (as it relies on the previous block). */ + +int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){ + vorbis_info *vi=v->vi; + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + private_state *b=v->backend_state; + int i,j; + + if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL); + + v->lW=v->W; + v->W=vb->W; + v->nW=-1; + + if((v->sequence==-1)|| + (v->sequence+1 != vb->sequence)){ + v->granulepos=-1; /* out of sequence; lose count */ + b->sample_count=-1; + } + + v->sequence=vb->sequence; + + if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly + was called on block */ + int n=ci->blocksizes[v->W]/2; + int n0=ci->blocksizes[0]/2; + int n1=ci->blocksizes[1]/2; + + int thisCenter; + int prevCenter; + + if(v->centerW){ + thisCenter=n1; + prevCenter=0; + }else{ + thisCenter=0; + prevCenter=n1; + } + + /* v->pcm is now used like a two-stage double buffer. We don't want + to have to constantly shift *or* adjust memory usage. Don't + accept a new block until the old is shifted out */ + + /* overlap/add PCM */ + + for(j=0;jchannels;j++){ + /* the overlap/add section */ + if(v->lW){ + if(v->W){ + /* large/large */ + ogg_int32_t *pcm=v->pcm[j]+prevCenter; + ogg_int32_t *p=vb->pcm[j]; + for(i=0;ipcm[j]+prevCenter+n1/2-n0/2; + ogg_int32_t *p=vb->pcm[j]; + for(i=0;iW){ + /* small/large */ + ogg_int32_t *pcm=v->pcm[j]+prevCenter; + ogg_int32_t *p=vb->pcm[j]+n1/2-n0/2; + for(i=0;ipcm[j]+prevCenter; + ogg_int32_t *p=vb->pcm[j]; + for(i=0;ipcm[j]+thisCenter; + ogg_int32_t *p=vb->pcm[j]+n; + for(i=0;icenterW) + v->centerW=0; + else + v->centerW=n1; + + /* deal with initial packet state; we do this using the explicit + pcm_returned==-1 flag otherwise we're sensitive to first block + being short or long */ + + if(v->pcm_returned==-1){ + v->pcm_returned=thisCenter; + v->pcm_current=thisCenter; + }else{ + v->pcm_returned=prevCenter; + v->pcm_current=prevCenter+ + ci->blocksizes[v->lW]/4+ + ci->blocksizes[v->W]/4; + } + + } + + /* track the frame number... This is for convenience, but also + making sure our last packet doesn't end with added padding. If + the last packet is partial, the number of samples we'll have to + return will be past the vb->granulepos. + + This is not foolproof! It will be confused if we begin + decoding at the last page after a seek or hole. In that case, + we don't have a starting point to judge where the last frame + is. For this reason, vorbisfile will always try to make sure + it reads the last two marked pages in proper sequence */ + + if(b->sample_count==-1){ + b->sample_count=0; + }else{ + b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4; + } + + if(v->granulepos==-1){ + if(vb->granulepos!=-1){ /* only set if we have a position to set to */ + + v->granulepos=vb->granulepos; + + /* is this a short page? */ + if(b->sample_count>v->granulepos){ + /* corner case; if this is both the first and last audio page, + then spec says the end is cut, not beginning */ + long extra=b->sample_count-vb->granulepos; + + /* we use ogg_int64_t for granule positions because a + uint64 isn't universally available. Unfortunately, + that means granposes can be 'negative' and result in + extra being negative */ + if(extra<0) + extra=0; + + if(vb->eofflag){ + /* trim the end */ + /* no preceeding granulepos; assume we started at zero (we'd + have to in a short single-page stream) */ + /* granulepos could be -1 due to a seek, but that would result + in a long coun`t, not short count */ + + /* Guard against corrupt/malicious frames that set EOP and + a backdated granpos; don't rewind more samples than we + actually have */ + if(extra > v->pcm_current - v->pcm_returned) + extra = v->pcm_current - v->pcm_returned; + + v->pcm_current-=extra; + }else{ + /* trim the beginning */ + v->pcm_returned+=extra; + if(v->pcm_returned>v->pcm_current) + v->pcm_returned=v->pcm_current; + } + + } + + } + }else{ + v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4; + if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){ + + if(v->granulepos>vb->granulepos){ + long extra=v->granulepos-vb->granulepos; + + if(extra) + if(vb->eofflag){ + /* partial last frame. Strip the extra samples off */ + + /* Guard against corrupt/malicious frames that set EOP and + a backdated granpos; don't rewind more samples than we + actually have */ + if(extra > v->pcm_current - v->pcm_returned) + extra = v->pcm_current - v->pcm_returned; + + /* we use ogg_int64_t for granule positions because a + uint64 isn't universally available. Unfortunately, + that means granposes can be 'negative' and result in + extra being negative */ + if(extra<0) + extra=0; + + v->pcm_current-=extra; + + } /* else {Shouldn't happen *unless* the bitstream is out of + spec. Either way, believe the bitstream } */ + } /* else {Shouldn't happen *unless* the bitstream is out of + spec. Either way, believe the bitstream } */ + v->granulepos=vb->granulepos; + } + } + + /* Update, cleanup */ + + if(vb->eofflag)v->eofflag=1; + return(0); +} + +/* pcm==NULL indicates we just want the pending samples, no more */ +int vorbis_synthesis_pcmout(vorbis_dsp_state *v,ogg_int32_t ***pcm){ + vorbis_info *vi=v->vi; + if(v->pcm_returned>-1 && v->pcm_returnedpcm_current){ + if(pcm){ + int i; + for(i=0;ichannels;i++) + v->pcmret[i]=v->pcm[i]+v->pcm_returned; + *pcm=v->pcmret; + } + return(v->pcm_current-v->pcm_returned); + } + return(0); +} + +int vorbis_synthesis_read(vorbis_dsp_state *v,int bytes){ + if(bytes && v->pcm_returned+bytes>v->pcm_current)return(OV_EINVAL); + v->pcm_returned+=bytes; + return(0); +} + diff --git a/libs/tremor/block.h b/libs/tremor/block.h new file mode 100644 index 0000000..5e19354 --- /dev/null +++ b/libs/tremor/block.h @@ -0,0 +1,24 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2008 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: shared block functions + + ********************************************************************/ + +#ifndef _V_BLOCK_ +#define _V_BLOCK_ + +extern void _vorbis_block_ripcord(vorbis_block *vb); +extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes); + +#endif diff --git a/libs/tremor/codebook.c b/libs/tremor/codebook.c new file mode 100644 index 0000000..f8b7983 --- /dev/null +++ b/libs/tremor/codebook.c @@ -0,0 +1,391 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: basic codebook pack/unpack/code/decode operations + + ********************************************************************/ + +#include +#include +#include +#include +#include "ivorbiscodec.h" +#include "codebook.h" +#include "misc.h" + +/* unpacks a codebook from the packet buffer into the codebook struct, + readies the codebook auxiliary structures for decode *************/ +static_codebook *vorbis_staticbook_unpack(oggpack_buffer *opb){ + long i,j; + static_codebook *s=_ogg_calloc(1,sizeof(*s)); + + /* make sure alignment is correct */ + if(oggpack_read(opb,24)!=0x564342)goto _eofout; + + /* first the basic parameters */ + s->dim=oggpack_read(opb,16); + s->entries=oggpack_read(opb,24); + if(s->entries==-1)goto _eofout; + + if(_ilog(s->dim)+_ilog(s->entries)>24)goto _eofout; + + /* codeword ordering.... length ordered or unordered? */ + switch((int)oggpack_read(opb,1)){ + case 0:{ + long unused; + /* allocated but unused entries? */ + unused=oggpack_read(opb,1); + if((s->entries*(unused?1:5)+7)>>3>opb->storage-oggpack_bytes(opb)) + goto _eofout; + /* unordered */ + s->lengthlist=(long *)_ogg_malloc(sizeof(*s->lengthlist)*s->entries); + + /* allocated but unused entries? */ + if(unused){ + /* yes, unused entries */ + + for(i=0;ientries;i++){ + if(oggpack_read(opb,1)){ + long num=oggpack_read(opb,5); + if(num==-1)goto _eofout; + s->lengthlist[i]=num+1; + }else + s->lengthlist[i]=0; + } + }else{ + /* all entries used; no tagging */ + for(i=0;ientries;i++){ + long num=oggpack_read(opb,5); + if(num==-1)goto _eofout; + s->lengthlist[i]=num+1; + } + } + + break; + } + case 1: + /* ordered */ + { + long length=oggpack_read(opb,5)+1; + if(length==0)goto _eofout; + s->lengthlist=(long *)_ogg_malloc(sizeof(*s->lengthlist)*s->entries); + + for(i=0;ientries;){ + long num=oggpack_read(opb,_ilog(s->entries-i)); + if(num==-1)goto _eofout; + if(length>32 || num>s->entries-i || + (num>0 && (num-1)>>(length>>1)>>((length+1)>>1))>0){ + goto _errout; + } + for(j=0;jlengthlist[i]=length; + length++; + } + } + break; + default: + /* EOF */ + goto _eofout; + } + + /* Do we have a mapping to unpack? */ + switch((s->maptype=oggpack_read(opb,4))){ + case 0: + /* no mapping */ + break; + case 1: case 2: + /* implicitly populated value mapping */ + /* explicitly populated value mapping */ + + s->q_min=oggpack_read(opb,32); + s->q_delta=oggpack_read(opb,32); + s->q_quant=oggpack_read(opb,4)+1; + s->q_sequencep=oggpack_read(opb,1); + if(s->q_sequencep==-1)goto _eofout; + + { + int quantvals=0; + switch(s->maptype){ + case 1: + quantvals=(s->dim==0?0:_book_maptype1_quantvals(s)); + break; + case 2: + quantvals=s->entries*s->dim; + break; + } + + /* quantized values */ + if((quantvals*s->q_quant+7)>>3>opb->storage-oggpack_bytes(opb)) + goto _eofout; + s->quantlist=(long *)_ogg_malloc(sizeof(*s->quantlist)*quantvals); + for(i=0;iquantlist[i]=oggpack_read(opb,s->q_quant); + + if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout; + } + break; + default: + goto _errout; + } + + /* all set */ + return(s); + + _errout: + _eofout: + vorbis_staticbook_destroy(s); + return(NULL); +} + +/* the 'eliminate the decode tree' optimization actually requires the + codewords to be MSb first, not LSb. This is an annoying inelegancy + (and one of the first places where carefully thought out design + turned out to be wrong; Vorbis II and future Ogg codecs should go + to an MSb bitpacker), but not actually the huge hit it appears to + be. The first-stage decode table catches most words so that + bitreverse is not in the main execution path. */ + +static ogg_uint32_t bitreverse(ogg_uint32_t x){ + x= ((x>>16)&0x0000ffff) | ((x<<16)&0xffff0000); + x= ((x>> 8)&0x00ff00ff) | ((x<< 8)&0xff00ff00); + x= ((x>> 4)&0x0f0f0f0f) | ((x<< 4)&0xf0f0f0f0); + x= ((x>> 2)&0x33333333) | ((x<< 2)&0xcccccccc); + return((x>> 1)&0x55555555) | ((x<< 1)&0xaaaaaaaa); +} + +STIN long decode_packed_entry_number(codebook *book, + oggpack_buffer *b){ + int read=book->dec_maxlength; + long lo,hi; + long lok = oggpack_look(b,book->dec_firsttablen); + + if (lok >= 0) { + long entry = book->dec_firsttable[lok]; + if(entry&0x80000000UL){ + lo=(entry>>15)&0x7fff; + hi=book->used_entries-(entry&0x7fff); + }else{ + oggpack_adv(b, book->dec_codelengths[entry-1]); + return(entry-1); + } + }else{ + lo=0; + hi=book->used_entries; + } + + lok = oggpack_look(b, read); + + while(lok<0 && read>1) + lok = oggpack_look(b, --read); + + if(lok<0){ + oggpack_adv(b,1); /* force eop */ + return -1; + } + + /* bisect search for the codeword in the ordered list */ + { + ogg_uint32_t testword=bitreverse((ogg_uint32_t)lok); + + while(hi-lo>1){ + long p=(hi-lo)>>1; + long test=book->codelist[lo+p]>testword; + lo+=p&(test-1); + hi-=p&(-test); + } + + if(book->dec_codelengths[lo]<=read){ + oggpack_adv(b, book->dec_codelengths[lo]); + return(lo); + } + } + + oggpack_adv(b, read+1); + return(-1); +} + +/* Decode side is specced and easier, because we don't need to find + matches using different criteria; we simply read and map. There are + two things we need to do 'depending': + + We may need to support interleave. We don't really, but it's + convenient to do it here rather than rebuild the vector later. + + Cascades may be additive or multiplicitive; this is not inherent in + the codebook, but set in the code using the codebook. Like + interleaving, it's easiest to do it here. + addmul==0 -> declarative (set the value) + addmul==1 -> additive + addmul==2 -> multiplicitive */ + +/* returns the [original, not compacted] entry number or -1 on eof *********/ +long vorbis_book_decode(codebook *book, oggpack_buffer *b){ + if(book->used_entries>0){ + long packed_entry=decode_packed_entry_number(book,b); + if(packed_entry>=0) + return(book->dec_index[packed_entry]); + } + + /* if there's no dec_index, the codebook unpacking isn't collapsed */ + return(-1); +} + +/* returns 0 on OK or -1 on eof *************************************/ +/* decode vector / dim granularity gaurding is done in the upper layer */ +long vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a, + oggpack_buffer *b,int n,int point){ + if(book->used_entries>0){ + int step=n/book->dim; + long *entry = (long *)alloca(sizeof(*entry)*step); + ogg_int32_t **t = (ogg_int32_t **)alloca(sizeof(*t)*step); + int i,j,o; + int shift=point-book->binarypoint; + + if(shift>=0){ + for (i = 0; i < step; i++) { + entry[i]=decode_packed_entry_number(book,b); + if(entry[i]==-1)return(-1); + t[i] = book->valuelist+entry[i]*book->dim; + } + for(i=0,o=0;idim;i++,o+=step) + for (j=0;j>shift; + }else{ + for (i = 0; i < step; i++) { + entry[i]=decode_packed_entry_number(book,b); + if(entry[i]==-1)return(-1); + t[i] = book->valuelist+entry[i]*book->dim; + } + for(i=0,o=0;idim;i++,o+=step) + for (j=0;jused_entries>0){ + int i,j,entry; + ogg_int32_t *t; + int shift=point-book->binarypoint; + + if(shift>=0){ + for(i=0;ivaluelist+entry*book->dim; + for (j=0;jdim;) + a[i++]+=t[j++]>>shift; + } + }else{ + for(i=0;ivaluelist+entry*book->dim; + for (j=0;jdim;) + a[i++]+=t[j++]<<-shift; + } + } + } + return(0); +} + +/* unlike the others, we guard against n not being an integer number + of internally rather than in the upper layer (called only by + floor0) */ +long vorbis_book_decodev_set(codebook *book,ogg_int32_t *a, + oggpack_buffer *b,int n,int point){ + if(book->used_entries>0){ + int i,j,entry; + ogg_int32_t *t; + int shift=point-book->binarypoint; + + if(shift>=0){ + + for(i=0;ivaluelist+entry*book->dim; + for (j=0;idim;){ + a[i++]=t[j++]>>shift; + } + } + }else{ + + for(i=0;ivaluelist+entry*book->dim; + for (j=0;idim;){ + a[i++]=t[j++]<<-shift; + } + } + } + }else{ + + int i,j; + for(i=0;iused_entries>0){ + long i,j,entry; + int chptr=0; + int shift=point-book->binarypoint; + + if(shift>=0){ + + for(i=offset;ivaluelist+entry*book->dim; + for (j=0;jdim;j++){ + a[chptr++][i]+=t[j]>>shift; + if(chptr==ch){ + chptr=0; + i++; + } + } + } + } + }else{ + + for(i=offset;ivaluelist+entry*book->dim; + for (j=0;jdim;j++){ + a[chptr++][i]+=t[j]<<-shift; + if(chptr==ch){ + chptr=0; + i++; + } + } + } + } + } + } + return(0); +} diff --git a/libs/tremor/codebook.h b/libs/tremor/codebook.h new file mode 100644 index 0000000..bb13942 --- /dev/null +++ b/libs/tremor/codebook.h @@ -0,0 +1,101 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: basic shared codebook operations + + ********************************************************************/ + +#ifndef _V_CODEBOOK_H_ +#define _V_CODEBOOK_H_ + +#include + +/* This structure encapsulates huffman and VQ style encoding books; it + doesn't do anything specific to either. + + valuelist/quantlist are nonNULL (and q_* significant) only if + there's entry->value mapping to be done. + + If encode-side mapping must be done (and thus the entry needs to be + hunted), the auxiliary encode pointer will point to a decision + tree. This is true of both VQ and huffman, but is mostly useful + with VQ. + +*/ + +typedef struct static_codebook{ + long dim; /* codebook dimensions (elements per vector) */ + long entries; /* codebook entries */ + long *lengthlist; /* codeword lengths in bits */ + + /* mapping ***************************************************************/ + int maptype; /* 0=none + 1=implicitly populated values from map column + 2=listed arbitrary values */ + + /* The below does a linear, single monotonic sequence mapping. */ + long q_min; /* packed 32 bit float; quant value 0 maps to minval */ + long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */ + int q_quant; /* bits: 0 < quant <= 16 */ + int q_sequencep; /* bitflag */ + + long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map + map == 2: list of dim*entries quantized entry vals + */ +} static_codebook; + +typedef struct codebook{ + long dim; /* codebook dimensions (elements per vector) */ + long entries; /* codebook entries */ + long used_entries; /* populated codebook entries */ + + /* the below are ordered by bitreversed codeword and only used + entries are populated */ + int binarypoint; + ogg_int32_t *valuelist; /* list of dim*entries actual entry values */ + ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */ + + int *dec_index; + char *dec_codelengths; + ogg_uint32_t *dec_firsttable; + int dec_firsttablen; + int dec_maxlength; + + long q_min; /* packed 32 bit float; quant value 0 maps to minval */ + long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */ + +} codebook; + +extern void vorbis_staticbook_destroy(static_codebook *b); +extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source); + +extern void vorbis_book_clear(codebook *b); +extern long _book_maptype1_quantvals(const static_codebook *b); + +extern static_codebook *vorbis_staticbook_unpack(oggpack_buffer *b); + +extern long vorbis_book_decode(codebook *book, oggpack_buffer *b); +extern long vorbis_book_decodevs_add(codebook *book, ogg_int32_t *a, + oggpack_buffer *b,int n,int point); +extern long vorbis_book_decodev_set(codebook *book, ogg_int32_t *a, + oggpack_buffer *b,int n,int point); +extern long vorbis_book_decodev_add(codebook *book, ogg_int32_t *a, + oggpack_buffer *b,int n,int point); +extern long vorbis_book_decodevv_add(codebook *book, ogg_int32_t **a, + long off,int ch, + oggpack_buffer *b,int n,int point); + +extern int _ilog(unsigned int v); + + +#endif diff --git a/libs/tremor/codec_internal.h b/libs/tremor/codec_internal.h new file mode 100644 index 0000000..3ca7f54 --- /dev/null +++ b/libs/tremor/codec_internal.h @@ -0,0 +1,92 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: libvorbis codec headers + + ********************************************************************/ + +#ifndef _V_CODECI_H_ +#define _V_CODECI_H_ + +#include "codebook.h" + +typedef void vorbis_look_mapping; +typedef void vorbis_look_floor; +typedef void vorbis_look_residue; +typedef void vorbis_look_transform; + +/* mode ************************************************************/ +typedef struct { + int blockflag; + int windowtype; + int transformtype; + int mapping; +} vorbis_info_mode; + +typedef void vorbis_info_floor; +typedef void vorbis_info_residue; +typedef void vorbis_info_mapping; + +typedef struct private_state { + /* local lookup storage */ + const void *window[2]; + + /* backend lookups are tied to the mode, not the backend or naked mapping */ + int modebits; + vorbis_look_mapping **mode; + + ogg_int64_t sample_count; + +} private_state; + +/* codec_setup_info contains all the setup information specific to the + specific compression/decompression mode in progress (eg, + psychoacoustic settings, channel setup, options, codebook + etc). +*********************************************************************/ + +typedef struct codec_setup_info { + + /* Vorbis supports only short and long blocks, but allows the + encoder to choose the sizes */ + + long blocksizes[2]; + + /* modes are the primary means of supporting on-the-fly different + blocksizes, different channel mappings (LR or M/A), + different residue backends, etc. Each mode consists of a + blocksize flag and a mapping (along with the mapping setup */ + + int modes; + int maps; + int times; + int floors; + int residues; + int books; + + vorbis_info_mode *mode_param[64]; + int map_type[64]; + vorbis_info_mapping *map_param[64]; + int time_type[64]; + int floor_type[64]; + vorbis_info_floor *floor_param[64]; + int residue_type[64]; + vorbis_info_residue *residue_param[64]; + static_codebook *book_param[256]; + codebook *fullbooks; + + int passlimit[32]; /* iteration limit per couple/quant pass */ + int coupling_passes; +} codec_setup_info; + +#endif diff --git a/libs/tremor/config_types.h b/libs/tremor/config_types.h new file mode 100644 index 0000000..1fdcb27 --- /dev/null +++ b/libs/tremor/config_types.h @@ -0,0 +1,25 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: #ifdef jail to whip a few platforms into the UNIX ideal. + + ********************************************************************/ +#ifndef _OS_CVTYPES_H +#define _OS_CVTYPES_H + +typedef long long ogg_int64_t; +typedef int ogg_int32_t; +typedef unsigned int ogg_uint32_t; +typedef short ogg_int16_t; + +#endif diff --git a/libs/tremor/configure.in b/libs/tremor/configure.in new file mode 100644 index 0000000..e7f5690 --- /dev/null +++ b/libs/tremor/configure.in @@ -0,0 +1,146 @@ +dnl Process this file with autoconf to produce a configure script + +dnl ------------------------------------------------ +dnl Initialization and Versioning +dnl ------------------------------------------------ + +AC_INIT(mdct.c) + +AC_CANONICAL_HOST +AC_CANONICAL_TARGET + +AM_CONFIG_HEADER([config.h]) + +AM_INIT_AUTOMAKE(libvorbisidec,1.2.1) + +dnl AM_MAINTAINER_MODE only provides the option to configure to enable it +AM_MAINTAINER_MODE + +dnl Library versioning + +V_LIB_CURRENT=1 +V_LIB_REVISION=3 +V_LIB_AGE=0 +AC_SUBST(V_LIB_CURRENT) +AC_SUBST(V_LIB_REVISION) +AC_SUBST(V_LIB_AGE) + +dnl -------------------------------------------------- +dnl Check for programs +dnl -------------------------------------------------- + +dnl save $CFLAGS since AC_PROG_CC likes to insert "-g -O2" +dnl if $CFLAGS is blank +cflags_save="$CFLAGS" +AC_PROG_CC +AC_PROG_CPP +CFLAGS="$cflags_save" + +AM_PROG_LIBTOOL + +dnl -------------------------------------------------- +dnl Set build flags based on environment +dnl -------------------------------------------------- + +dnl Set some target options + +cflags_save="$CFLAGS" +ldflags_save="$LDFLAGS" +if test -z "$GCC"; then + case $host in + arm-*-*) + DEBUG="-g -D_ARM_ASSEM_" + CFLAGS="-O -D_ARM_ASSEM_" + PROFILE="-p -g -O -D_ARM_ASSEM_" ;; + *) + DEBUG="-g" + CFLAGS="-O" + PROFILE="-g -p" ;; + esac +else + + case $host in + arm-*-*) + DEBUG="-g -Wall -D__NO_MATH_INLINES -fsigned-char -D_ARM_ASSEM_" + CFLAGS="-O2 -D_ARM_ASSEM_ -fsigned-char" + PROFILE="-W -pg -g -O2 -D_ARM_ASSEM_ -fsigned-char -fno-inline-functions";; + + *) + DEBUG="-g -Wall -D__NO_MATH_INLINES -fsigned-char" + CFLAGS="-O2 -Wall -fsigned-char" + PROFILE="-Wall -pg -g -O2 -fsigned-char -fno-inline-functions";; + esac +fi +CFLAGS="$CFLAGS $cflags_save -D_REENTRANT" +LDFLAGS="$LDFLAGS $ldflags_save" + + +# Test whenever ld supports -version-script +AC_PROG_LD +AC_PROG_LD_GNU +if test "x$lt_cv_prog_gnu_ld" = "xyes"; then + SHLIB_VERSION_ARG="-Wl,--version-script=Version_script" + LDFLAGS="$LDFLAGS $SHLIB_VERSION_ARG" +fi + +dnl -------------------------------------------------- +dnl Options +dnl -------------------------------------------------- + +AC_ARG_ENABLE( + low-accuracy, + [ --enable-low-accuracy enable 32 bit only multiply operations], + CFLAGS="$CFLAGS -D_LOW_ACCURACY_" +) + +dnl -------------------------------------------------- +dnl Check for headers +dnl -------------------------------------------------- + +AC_CHECK_HEADER(memory.h,CFLAGS="$CFLAGS -DUSE_MEMORY_H",:) + +dnl -------------------------------------------------- +dnl Check for typedefs, structures, etc +dnl -------------------------------------------------- + +dnl none + +dnl -------------------------------------------------- +dnl Check for libraries +dnl -------------------------------------------------- + +PKG_PROG_PKG_CONFIG + +HAVE_OGG=no +if test "x$PKG_CONFIG" != "x" +then + PKG_CHECK_MODULES(OGG, ogg >= 1.0, HAVE_OGG=yes, HAVE_OGG=no) +fi +if test "x$HAVE_OGG" = "xno" +then + dnl fall back to the old school test + XIPH_PATH_OGG(, AC_MSG_ERROR(must have Ogg installed!)) + libs_save=$LIBS + LIBS="$OGG_LIBS" + AC_CHECK_FUNC(oggpack_writealign, , AC_MSG_ERROR(Ogg >= 1.0 required !)) + LIBS=$libs_save +fi + +dnl -------------------------------------------------- +dnl Check for library functions +dnl -------------------------------------------------- + +AC_FUNC_ALLOCA +AC_FUNC_MEMCMP + +dnl -------------------------------------------------- +dnl Do substitutions +dnl -------------------------------------------------- + +LIBS="$LIBS" + +AC_SUBST(LIBS) +AC_SUBST(DEBUG) +AC_SUBST(PROFILE) + +AC_OUTPUT(Makefile Version_script vorbisidec.pc) diff --git a/libs/tremor/debian/Makefile.am b/libs/tremor/debian/Makefile.am new file mode 100644 index 0000000..45a0f01 --- /dev/null +++ b/libs/tremor/debian/Makefile.am @@ -0,0 +1,6 @@ +## Process this file with automake to produce Makefile.in + +AUTOMAKE_OPTIONS = foreign + +EXTRA_DIST = changelog control copyright libvorbisidec1.install\ + libvorbisidec-dev.install rules diff --git a/libs/tremor/debian/changelog b/libs/tremor/debian/changelog new file mode 100644 index 0000000..0cb4935 --- /dev/null +++ b/libs/tremor/debian/changelog @@ -0,0 +1,9 @@ +libvorbisidec (1.2.0-1) unstable; urgency=low + + * Initial Release. + + -- Christopher L Cheney Wed, 09 Oct 2002 22:00:00 -0500 + +Local variables: +mode: debian-changelog +End: diff --git a/libs/tremor/debian/control b/libs/tremor/debian/control new file mode 100644 index 0000000..f286e91 --- /dev/null +++ b/libs/tremor/debian/control @@ -0,0 +1,22 @@ +Source: libvorbisidec +Section: libs +Priority: optional +Maintainer: Christopher L Cheney +Build-Depends: autotools-dev, debhelper (>> 4.0.18), devscripts, gawk +Standards-Version: 3.5.7.0 + +Package: libvorbisidec1 +Architecture: any +Section: libs +Depends: ${shlibs:Depends} +Description: Ogg Bitstream Library + Libogg is a library for manipulating ogg bitstreams. It handles + both making ogg bitstreams and getting packets from ogg bitstreams. + +Package: libvorbisidec-dev +Architecture: any +Section: devel +Depends: libvorbisidec1 (= ${Source-Version}), libc6-dev +Description: Ogg Bitstream Library Development + The libogg-dev package contains the header files and documentation + needed to develop applications with libogg. diff --git a/libs/tremor/debian/copyright b/libs/tremor/debian/copyright new file mode 100644 index 0000000..ef98ddd --- /dev/null +++ b/libs/tremor/debian/copyright @@ -0,0 +1,37 @@ +This package was debianized by Christopher L Cheney on +Wed, 09 Oct 2002 22:00:00 -0500. + +It was downloaded from cvs. + +Upstream Author(s): Monty + +Copyright: +Copyright (c) 2002, 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 REGENTS 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. + diff --git a/libs/tremor/debian/libvorbisidec-dev.install b/libs/tremor/debian/libvorbisidec-dev.install new file mode 100644 index 0000000..5c3ccf9 --- /dev/null +++ b/libs/tremor/debian/libvorbisidec-dev.install @@ -0,0 +1,8 @@ +debian/tmp/usr/include/tremor/config_types.h +debian/tmp/usr/include/tremor/ivorbiscodec.h +debian/tmp/usr/include/tremor/ivorbisfile.h +debian/tmp/usr/include/tremor/ogg.h +debian/tmp/usr/include/tremor/os_types.h +debian/tmp/usr/lib/libvorbisidec.a +debian/tmp/usr/lib/libvorbisidec.la +debian/tmp/usr/lib/libvorbisidec.so diff --git a/libs/tremor/debian/libvorbisidec1.install b/libs/tremor/debian/libvorbisidec1.install new file mode 100644 index 0000000..b824d1e --- /dev/null +++ b/libs/tremor/debian/libvorbisidec1.install @@ -0,0 +1 @@ +debian/tmp/usr/lib/libvorbisidec.so.* diff --git a/libs/tremor/debian/rules b/libs/tremor/debian/rules new file mode 100755 index 0000000..c684884 --- /dev/null +++ b/libs/tremor/debian/rules @@ -0,0 +1,151 @@ +#!/usr/bin/make -f +# Sample debian/rules that uses debhelper. +# GNU copyright 1997 to 1999 by Joey Hess. + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + +# This is the debhelper compatibility version to use. +export DH_COMPAT=4 + +# This has to be exported to make some magic below work. +export DH_OPTIONS + +# These are used for cross-compiling and for saving the configure script +# from having to guess our platform (since we know it already) +DEB_HOST_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE) +DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE) + +objdir = $(CURDIR)/obj-$(DEB_BUILD_GNU_TYPE) + +ifneq (,$(findstring debug,$(DEB_BUILD_OPTIONS))) + CFLAGS += -g +endif +ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS))) + INSTALL_PROGRAM += -s +endif + +configure: configure-stamp +configure-stamp: + dh_testdir + + # make build directory + mkdir $(objdir) + + # run configure with build tree $(objdir) + # change ../configure to ../autogen.sh for CVS build + cd $(objdir) && \ + ../configure --build=$(DEB_BUILD_GNU_TYPE) --host=$(DEB_HOST_GNU_TYPE) \ + --prefix=/usr + + touch configure-stamp + +build: build-stamp +build-stamp: configure-stamp + dh_testdir + + cd $(objdir) && \ + $(MAKE) + + touch build-stamp + +autotools: + OLDDATESUB=`./config.sub -t | tr -d -` ;\ + OLDDATEGUESS=`./config.guess -t | tr -d -` ;\ + NEWDATESUB=`/usr/share/misc/config.sub -t | tr -d -` ;\ + NEWDATEGUESS=`/usr/share/misc/config.guess -t | tr -d -` ;\ + if [ $$OLDDATESUB -lt $$NEWDATESUB -o \ + $$OLDDATEGUESS -lt $$NEWDATEGUESS ]; then \ + dch -a -p "GNU config automated update: config.sub\ + ($$OLDDATESUB to $$NEWDATESUB), config.guess\ + ($$OLDDATEGUESS to $$NEWDATEGUESS)" ;\ + cp -f /usr/share/misc/config.sub config.sub ;\ + cp -f /usr/share/misc/config.guess config.guess ;\ + echo WARNING: GNU config scripts updated from master copies 1>&2 ;\ + fi + +debian-clean: + dh_testdir + dh_testroot + + dh_clean + +clean: autotools + dh_testdir + dh_testroot + rm -f build-stamp configure-stamp + + # Remove build tree + rm -rf $(objdir) + + # if Makefile exists run distclean + if test -f Makefile; then \ + $(MAKE) distclean; \ + fi + + #if test -d CVS; then \ + $(MAKE) cvs-clean ;\ + fi + + dh_clean + +install: DH_OPTIONS= +install: build + dh_testdir + dh_testroot + dh_clean -k + dh_installdirs + + cd $(objdir) && \ + $(MAKE) install DESTDIR=$(CURDIR)/debian/tmp + + dh_install --list-missing + +# This single target is used to build all the packages, all at once, or +# one at a time. So keep in mind: any options passed to commands here will +# affect _all_ packages. Anything you want to only affect one package +# should be put in another target, such as the install target. +binary-common: + dh_testdir + dh_testroot +# dh_installxfonts + dh_installchangelogs + dh_installdocs + dh_installexamples +# dh_installmenu +# dh_installdebconf +# dh_installlogrotate +# dh_installemacsen +# dh_installpam +# dh_installmime +# dh_installinit +# dh_installcron +# dh_installinfo +# dh_undocumented + dh_installman + dh_strip + dh_link + dh_compress + dh_fixperms + dh_makeshlibs -V + dh_installdeb +# dh_perl + dh_shlibdeps + dh_gencontrol + dh_md5sums + dh_builddeb + +# Build architecture independant packages using the common target. +binary-indep: build install +# $(MAKE) -f debian/rules DH_OPTIONS=-i binary-common + +# Build architecture dependant packages using the common target. +binary-arch: build install + $(MAKE) -f debian/rules DH_OPTIONS=-a binary-common + +# Any other binary targets build just one binary package at a time. +binary-%: build install + $(MAKE) -f debian/rules binary-common DH_OPTIONS=-p$* + +binary: binary-indep binary-arch +.PHONY: build clean binary-indep binary-arch binary install configure diff --git a/libs/tremor/doc/OggVorbis_File.html b/libs/tremor/doc/OggVorbis_File.html new file mode 100644 index 0000000..9201d18 --- /dev/null +++ b/libs/tremor/doc/OggVorbis_File.html @@ -0,0 +1,132 @@ + + + +Tremor - datatype - OggVorbis_File + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

OggVorbis_File

+ +

declared in "ivorbisfile.h"

+ +

+The OggVorbis_File structure defines an Ogg Vorbis file. +

+ +This structure is used in all libvorbisidec routines. Before it can be used, +it must be initialized by ov_open() or ov_open_callbacks(). + +

+After use, the OggVorbis_File structure must be deallocated with a +call to ov_clear(). + +

+Once a file or data source is opened successfully by libvorbisidec +(using ov_open() or ov_open_callbacks()), it is owned by +libvorbisidec. The file should not be used by any other applications or +functions outside of the libvorbisidec API. The file must not be closed +directly by the application at any time after a successful open; +libvorbisidec expects to close the file within ov_clear(). +

+If the call to ov_open() or ov_open_callbacks() fails, +libvorbisidec does not assume ownership of the file and the +application is expected to close it if necessary. + +

+ + + + +
+
typedef struct {
+  void             *datasource; /* Pointer to a FILE *, etc. */
+  int              seekable;
+  ogg_int64_t      offset;
+  ogg_int64_t      end;
+  ogg_sync_state   oy; 
+
+  /* If the FILE handle isn't seekable (eg, a pipe), only the current
+     stream appears */
+  int              links;
+  ogg_int64_t      *offsets;
+  ogg_int64_t      *dataoffsets;
+  long             *serialnos;
+  ogg_int64_t      *pcmlengths;
+  vorbis_info      *vi;
+  vorbis_comment   *vc;
+
+  /* Decoding working state local storage */
+  ogg_int64_t      pcm_offset;
+  int              ready_state;
+  long             current_serialno;
+  int              current_link;
+
+  ogg_int64_t      bittrack;
+  ogg_int64_t      samptrack;
+
+  ogg_stream_state os; /* take physical pages, weld into a logical
+                          stream of packets */
+  vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
+  vorbis_block     vb; /* local working space for packet->PCM decode */
+
+  ov_callbacks callbacks;
+
+} OggVorbis_File;
+
+ +

Relevant Struct Members

+
+
datasource
+ +
Pointer to file or other ogg source. When using stdio based +file/stream access, this field contains a FILE pointer. When using +custom IO via callbacks, libvorbisidec treats this void pointer as a +black box only to be passed to the callback routines provided by the +application.
+ +
seekable
+
Read-only int indicating whether file is seekable. E.g., a physical file is seekable, a pipe isn't.
+
links
+
Read-only int indicating the number of logical bitstreams within the physical bitstream.
+
ov_callbacks
+
Collection of file manipulation routines to be used on this data source. When using stdio/FILE access via ov_open(), the callbacks will be filled in with stdio calls or wrappers to stdio calls.
+
+ +

Notes

+ +

Tremor requires a native 64 bit integer type to compile and +function; The GNU build system will locate and typedef +ogg_int64_t to the appropriate native type. If not using the +GNU build tools, you will need to define ogg_int64_t as a +64-bit type inside your system's project file/Makefile, etc. On win32, +for example, this should be defined as __int64. +

+ + +

+


+ + + + + + + + +

copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

+ + + + diff --git a/libs/tremor/doc/build.html b/libs/tremor/doc/build.html new file mode 100644 index 0000000..6f0f4ee --- /dev/null +++ b/libs/tremor/doc/build.html @@ -0,0 +1,111 @@ + + + +Tremor - Build + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

Tremor: Building libvorbisidec

+ +

+ +The C source in the Tremor package will build on any ANSI C compiler +and function completely and properly on any platform. The included +build system assumes GNU build system and make tools (m4, automake, +autoconf, libtool and gmake). GCC is not required, although GCC is +the most tested compiler. To build using GNU tools, type in the +source directory: + +

+


+./autogen.sh
+gmake
+
+

+or if GNU make is the standard make on the build system: +


+./autogen.sh
+make
+
+ +

+Currently, the source implements playback in pure C on all platforms +except ARM, where a [currently] small amount of assembly (see the file +asm_arm.h) is used to implement 64 bit math operations and +fast LSP computation. If building on ARM without the benefit of GNU +build system tools, be sure that _ARM_ASSEM_ is #defined by +the build system if this assembly is desired, else the resulting +library will use whatever 64 bit math builtins the compiler +implements. + +

+No math library is required by this source. No floating point +operations are used at any point in either setup or decode. This +decoder library will properly decode any past, current or future +Vorbis I file or stream. + +

+The GNU build system produces static and, when supported by the OS, +dynamic libraries named 'libvorbisidec'. This library exposes an API +nearly identical to the BSD reference library's 'libvorbisfile', +including all the features familiar to users of vorbisfile. This API +is similar enough that the proper header file to include is named +'ivorbisfile.h', included in the source build directory. +Lower level libvorbis-style headers and structures are +in 'ivorbiscodec.h', also included in the source build directory. A +simple example program, ivorbisfile_example.c, can be built with 'make +ivorbisfile_example'. +

+(We've summarized differences between the free, +reference vorbisfile library and Tremor's libvorbisidec in a separate +document.) + +

Notes

+ +

Tremor requires a native 64 bit integer type to compile and +function; The GNU build system will locate and typedef +ogg_int64_t to the appropriate native type. If not using the +GNU build tools, you will need to define ogg_int64_t as a +64-bit type inside your system's project file/Makefile, etc. On win32, +for example, this should be defined as __int64. +

+ +

+


+ + + + + + + + +

copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

+ + + + + + + + + + + + + + + + + + + + diff --git a/libs/tremor/doc/callbacks.html b/libs/tremor/doc/callbacks.html new file mode 100644 index 0000000..9a6d392 --- /dev/null +++ b/libs/tremor/doc/callbacks.html @@ -0,0 +1,113 @@ + + + +Tremor - Callbacks and non-stdio I/O + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

Callbacks and non-stdio I/O

+ +Although stdio is convenient and nearly universally implemented as per +ANSI C, it is not suited to all or even most potential uses of Vorbis. +For additional flexibility, embedded applications may provide their +own I/O functions for use with Tremor when stdio is unavailable or not +suitable. One common example is decoding a Vorbis stream from a +memory buffer.

+ +Use custom I/O functions by populating an ov_callbacks structure and calling ov_open_callbacks() or ov_test_callbacks() rather than the +typical ov_open() or ov_test(). Past the open call, use of +libvorbisidec is identical to using it with stdio. + +

Read function

+ +The read-like function provided in the read_func field is +used to fetch the requested amount of data. It expects the fetch +operation to function similar to file-access, that is, a multiple read +operations will retrieve contiguous sequential pieces of data, +advancing a position cursor after each read.

+ +The following behaviors are also expected:

+

    +
  • a return of '0' indicates end-of-data (if the by-thread errno is unset) +
  • short reads mean nothing special (short reads are not treated as error conditions) +
  • a return of zero with the by-thread errno set to nonzero indicates a read error +
+

+ +

Seek function

+ +The seek-like function provided in the seek_func field is +used to request non-sequential data access by libvorbisidec, moving +the access cursor to the requested position.

+ +libvorbisidec expects the following behavior: +

    +
  • The seek function must always return -1 (failure) if the given +data abstraction is not seekable. It may choose to always return -1 +if the application desires libvorbisidec to treat the Vorbis data +strictly as a stream (which makes for a less expensive open +operation).

    + +

  • If the seek function initially indicates seekability, it must +always succeed upon being given a valid seek request.

    + +

  • The seek function must implement all of SEEK_SET, SEEK_CUR and +SEEK_END. The implementation of SEEK_END should set the access cursor +one past the last byte of accessible data, as would stdio +fseek()

    +

+ +

Close function

+ +The close function should deallocate any access state used by the +passed in instance of the data access abstraction and invalidate the +instance handle. The close function is assumed to succeed.

+ +One common use of callbacks and the close function is to change the +behavior of libvorbisidec with respect to file closure for applications +that must fclose data files themselves. By passing +the normal stdio calls as callback functions, but passing a +close_func that does nothing, an application may call ov_clear() and then fclose() the +file originally passed to libvorbisidec. + +

Tell function

+ +The tell function is intended to mimic the +behavior of ftell() and must return the byte position of the +next data byte that would be read. If the data access cursor is at +the end of the 'file' (pointing to one past the last byte of data, as +it would be after calling fseek(file,SEEK_END,0)), the tell +function must return the data position (and thus the total file size), +not an error.

+ +The tell function need not be provided if the data IO abstraction is +not seekable.
+


+ + + + + + + + +

copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

+ + + + diff --git a/libs/tremor/doc/datastructures.html b/libs/tremor/doc/datastructures.html new file mode 100644 index 0000000..2b3da07 --- /dev/null +++ b/libs/tremor/doc/datastructures.html @@ -0,0 +1,61 @@ + + + +Tremor - Base Data Structures + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

Base Data Structures

+

There are several data structures used to hold file and bitstream information during libvorbisidec decoding. These structures are declared in "ivorbisfile.h" and "ivorbiscodec.h". +

+

When using libvorbisidec, it's not necessary to know about most of the contents of these data structures, but it may be helpful to understand what they contain. +

+ + + + + + + + + + + + + + + + + + + + + + +
datatypepurpose
OggVorbis_FileThis structure represents the basic file information. It contains + a pointer to the physical file or bitstream and various information about that bitstream.
vorbis_commentThis structure contains the file comments. It contains + a pointer to unlimited user comments, information about the number of comments, and a vendor description.
vorbis_infoThis structure contains encoder-related information about the bitstream. It includes encoder info, channel info, and bitrate limits.
ov_callbacksThis structure contains pointers to the application-specified file manipulation routines set for use by ov_open_callbacks(). See also the provided document on using application-provided callbacks instead of stdio.
+ +

+


+ + + + + + + + +

copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

+ + + + diff --git a/libs/tremor/doc/decoding.html b/libs/tremor/doc/decoding.html new file mode 100644 index 0000000..1f61b47 --- /dev/null +++ b/libs/tremor/doc/decoding.html @@ -0,0 +1,82 @@ + + + +Tremor - Decoding + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

Decoding

+ +

+All libivorbisdec decoding routines are declared in "ivorbisfile.h". +

+ +After initialization, decoding audio +is as simple as calling ov_read(). This +function works similarly to reading from a normal file using +read().

+ +However, a few differences are worth noting: + +

multiple stream links

+ +A Vorbis stream may consist of multiple sections (called links) that +encode differing numbers of channels or sample rates. It is vitally +important to pay attention to the link numbers returned by ov_read and handle audio changes that may +occur at link boundaries. Such multi-section files do exist in the +wild and are not merely a specification curiosity. + +

returned data amount

+ +ov_read does not attempt to completely fill +a large, passed in data buffer; it merely guarantees that the passed +back data does not overflow the passed in buffer size. Large buffers +may be filled by iteratively looping over calls to ov_read (incrementing the buffer pointer) +until the original buffer is filled. + +

file cursor position

+ +Vorbis files do not necessarily start at a sample number or time offset +of zero. Do not be surprised if a file begins at a positive offset of +several minutes or hours, such as would happen if a large stream (such +as a concert recording) is chopped into multiple seperate files. + +

+ + + + + + + + + +
functionpurpose
ov_readThis function makes up the main chunk of a decode loop. It takes an +OggVorbis_File structure, which must have been initialized by a previous +call to ov_open().
+ +

+


+ + + + + + + + +

copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

+ + + + diff --git a/libs/tremor/doc/diff.html b/libs/tremor/doc/diff.html new file mode 100644 index 0000000..ae0b908 --- /dev/null +++ b/libs/tremor/doc/diff.html @@ -0,0 +1,67 @@ + + + +Tremor - Vorbisfile Differences + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

Tremor / Vorbisfile API Differences

+ +

+ +The Tremor libvorbisidec library exposes an API intended to be as +similar as possible to the familiar 'vorbisfile' library included with +the open source Vorbis reference libraries distributed for free by +Xiph.org. Differences are summarized below.

+ +

OggVorbis_File structure

+ +The bittrack and samptrack fields in the OggVorbis_File structure are changed to +64 bit integers in Tremor, from doubles in vorbisfile. + +

Time-related seek and tell function calls

+ +The ov_time_total() and ov_time_tell() functions return milliseconds as +64 bit integers in Tremor. In vorbisfile, these functions returned +seconds as doubles.

+ +In Tremor, the ov_time_seek() and ov_time_seek_page() calls take +seeking positions in milliseconds as 64 bit integers, rather than in +seconds as doubles as in Vorbisfile.

+ +

Reading decoded data

+ +Tremor ov_read() always returns data as +signed 16 bit interleaved PCM in host byte order. As such, it does not +take arguments to request specific signedness, byte order or bit depth +as in Vorbisfile.

+ +Tremor does not implement ov_read_float().

+ + +

+


+ + + + + + + + +

copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

+ + + + diff --git a/libs/tremor/doc/example.html b/libs/tremor/doc/example.html new file mode 100644 index 0000000..2b9a1dd --- /dev/null +++ b/libs/tremor/doc/example.html @@ -0,0 +1,205 @@ + + + +Tremor - Example Code + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

Example Code

+ +

+The following is a run-through of the decoding example program supplied +with libvorbisidec, ivorbisfile_example.c. +This program takes a vorbis bitstream from stdin and writes raw pcm to stdout. + +

+First, relevant headers, including vorbis-specific "ivorbiscodec.h" and "ivorbisfile.h" have to be included. + +

+ + + + +
+

+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include "ivorbiscodec.h"
+#include "ivorbisfile.h"
+
+
+

+We also have to make a concession to Windows users here. If we are using windows for decoding, we must declare these libraries so that we can set stdin/stdout to binary. +

+ + + + +
+

+#ifdef _WIN32
+#include <io.h>
+#include <fcntl.h>
+#endif
+
+
+

+Next, a buffer for the pcm audio output is declared. + +

+ + + + +
+

+char pcmout[4096];
+
+
+ +

Inside main(), we declare our primary OggVorbis_File structure. We also declare a few other helpful variables to track out progress within the file. +Also, we make our final concession to Windows users by setting the stdin and stdout to binary mode. +

+ + + + +
+

+int main(int argc, char **argv){
+  OggVorbis_File vf;
+  int eof=0;
+  int current_section;
+
+#ifdef _WIN32
+  _setmode( _fileno( stdin ), _O_BINARY );
+  _setmode( _fileno( stdout ), _O_BINARY );
+#endif
+
+
+ +

ov_open() must be +called to initialize the OggVorbis_File structure with default values. +ov_open() also checks to ensure that we're reading Vorbis format and not something else. + +

+ + + + +
+

+  if(ov_open(stdin, &vf, NULL, 0) < 0) {
+      fprintf(stderr,"Input does not appear to be an Ogg bitstream.\n");
+      exit(1);
+  }
+
+
+
+ +

+We're going to pull the channel and bitrate info from the file using ov_info() and show them to the user. +We also want to pull out and show the user a comment attached to the file using ov_comment(). + +

+ + + + +
+

+  {
+    char **ptr=ov_comment(&vf,-1)->user_comments;
+    vorbis_info *vi=ov_info(&vf,-1);
+    while(*ptr){
+      fprintf(stderr,"%s\n",*ptr);
+      ++ptr;
+    }
+    fprintf(stderr,"\nBitstream is %d channel, %ldHz\n",vi->channels,vi->rate);
+    fprintf(stderr,"\nDecoded length: %ld samples\n",
+            (long)ov_pcm_total(&vf,-1));
+    fprintf(stderr,"Encoded by: %s\n\n",ov_comment(&vf,-1)->vendor);
+  }
+  
+
+
+ +

+Here's the read loop: + +

+ + + + +
+

+
+  while(!eof){
+    long ret=ov_read(&vf,pcmout,sizeof(pcmout),¤t_section);
+    if (ret == 0) {
+      /* EOF */
+      eof=1;
+    } else if (ret < 0) {
+      /* error in the stream.  Not a problem, just reporting it in
+	 case we (the app) cares.  In this case, we don't. */
+    } else {
+      /* we don't bother dealing with sample rate changes, etc, but
+	 you'll have to*/
+      fwrite(pcmout,1,ret,stdout);
+    }
+  }
+
+  
+
+
+ +

+The code is reading blocks of data using ov_read(). +Based on the value returned, we know if we're at the end of the file or have invalid data. If we have valid data, we write it to the pcm output. + +

+Now that we've finished playing, we can pack up and go home. It's important to call ov_clear() when we're finished. + +

+ + + + +
+

+
+  ov_clear(&vf);
+    
+  fprintf(stderr,"Done.\n");
+  return(0);
+}
+
+
+ +

+ +

+


+ + + + + + + + +

copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

+ + + + diff --git a/libs/tremor/doc/fileinfo.html b/libs/tremor/doc/fileinfo.html new file mode 100644 index 0000000..53dfd38 --- /dev/null +++ b/libs/tremor/doc/fileinfo.html @@ -0,0 +1,95 @@ + + + +Tremor - File Information + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

File Information

+

Libvorbisidec contains many functions to get information about bitstream attributes and decoding status. +

+All libvorbisidec file information routines are declared in "ivorbisfile.h". +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
functionpurpose
ov_bitrateReturns the average bitrate of the current logical bitstream.
ov_bitrate_instantReturns the exact bitrate since the last call of this function, or -1 if at the beginning of the bitream or no new information is available.
ov_streamsGives the number of logical bitstreams within the current physical bitstream.
ov_seekableIndicates whether the bitstream is seekable.
ov_serialnumberReturns the unique serial number of the specified logical bitstream.
ov_raw_totalReturns the total (compressed) bytes in a physical or logical seekable bitstream.
ov_pcm_totalReturns the total number of samples in a physical or logical seekable bitstream.
ov_time_totalReturns the total time length in seconds of a physical or logical seekable bitstream.
ov_raw_tellReturns the byte location of the next sample to be read, giving the approximate location in the stream that the decoding engine has reached.
ov_pcm_tellReturns the sample location of the next sample to be read, giving the approximate location in the stream that the decoding engine has reached.
ov_time_tellReturns the time location of the next sample to be read, giving the approximate location in the stream that the decoding engine has reached.
ov_infoReturns the vorbis_info struct for a specific bitstream section.
ov_commentReturns attached comments for the current bitstream.
+ +

+


+ + + + + + + + +

copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

+ + + + diff --git a/libs/tremor/doc/index.html b/libs/tremor/doc/index.html new file mode 100644 index 0000000..671f13f --- /dev/null +++ b/libs/tremor/doc/index.html @@ -0,0 +1,53 @@ + + + +Tremor - Documentation + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

Tremor Documentation

+ +

+ +The Tremor Vorbis I stream and file decoder provides an embeddable, +integer-only library [libvorbisidec] intended for decoding all current +and future Vorbis I compliant streams. The Tremor libvorbisidec +library exposes an API intended to be as similar as possible to the +familiar 'vorbisfile' library included with the open source Vorbis +reference libraries distributed for free by Xiph.org.

+ +Tremor can be used along with any ANSI compliant stdio implementation +for file/stream access, or use custom stream i/o routines provided by +the embedded environment. Both uses are described in detail in this +documentation. + +

+Building libvorbisidec
+API overview
+API reference
+Example code
+Tremor / vorbisfile API differences
+ +

+


+ + + + + + + + +

copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

+ + + + diff --git a/libs/tremor/doc/initialization.html b/libs/tremor/doc/initialization.html new file mode 100644 index 0000000..f9f6807 --- /dev/null +++ b/libs/tremor/doc/initialization.html @@ -0,0 +1,101 @@ + + + +Tremor - Setup/Teardown + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

Setup/Teardown

In order to decode audio using +libvorbisidec, a bitstream containing Vorbis audio must be properly +initialized before decoding and cleared when decoding is finished. +The simplest possible case is to use fopen() to open a Vorbis +file and then pass the FILE * to an ov_open() call. A successful return code from ov_open() indicates the file is ready for use. +Once the file is no longer needed, ov_clear() is used to close the file and +deallocate decoding resources. Do not call fclose() on the +file; libvorbisidec does this in the ov_clear() call. + +

+All libvorbisidec initialization and deallocation routines are declared in "ivorbisfile.h". +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
functionpurpose
ov_openInitializes the Ogg Vorbis bitstream with a pointer to a bitstream and default values. This must be called before other functions in the library may be + used.
ov_open_callbacksInitializes the Ogg Vorbis bitstream with a pointer to a bitstream, default values, and custom file/bitstream manipulation routines. Used instead of ov_open() when working with other than stdio based I/O.
ov_testPartially opens a file just far enough to determine if the file +is an Ogg Vorbis file or not. A successful return indicates that the +file appears to be an Ogg Vorbis file, but the OggVorbis_File struct is not yet fully +initialized for actual decoding. After a successful return, the file +may be closed using ov_clear() or fully +opened for decoding using ov_test_open().

This call is intended to +be used as a less expensive file open test than a full ov_open().

+Note that libvorbisidec owns the passed in file resource is it returns success; do not fclose() files owned by libvorbisidec.

ov_test_callbacksAs above but allowing application-define I/O callbacks.

+Note that libvorbisidec owns the passed in file resource is it returns success; do not fclose() files owned by libvorbisidec.

ov_test_open +Finish opening a file after a successful call to ov_test() or ov_test_callbacks().
ov_clear Closes the + bitstream and cleans up loose ends. Must be called when + finished with the bitstream. After return, the OggVorbis_File struct is + invalid and may not be used before being initialized again + before begin reinitialized. + +
+ +

+


+ + + + + + + + +

copyright © 2002 Xiph.org

Ogg Vorbis

Tremor documentation

Tremor version 1.0 - 20020403

+ + + + diff --git a/libs/tremor/doc/ov_bitrate.html b/libs/tremor/doc/ov_bitrate.html new file mode 100644 index 0000000..65ebfc3 --- /dev/null +++ b/libs/tremor/doc/ov_bitrate.html @@ -0,0 +1,72 @@ + + + +Tremor - function - ov_bitrate + + + + + + + + + +

Tremor documentation

Tremor version 1.0 - 20020403

+ +

ov_bitrate

+ +

declared in "ivorbisfile.h";

+ +

This function returns the average bitrate for the specified logical bitstream. This may be different from the ov_info->nominal_bitrate value, as it is based on the actual average for this bitstream if the file is seekable. +

Nonseekable files will return the nominal bitrate setting or the average of the upper and lower bounds, if any of these values are set. +

+ +

+ + + + +
+

+long ov_bitrate(OggVorbis_File *vf,int i);
+
+
+ +

Parameters

+
+
vf
+
A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
+
i
+
Link to the desired logical bitstream. For nonseekable files, this argument is ignored. To retrieve the bitrate for the entire bitstream, this parameter should be set to -1.
+
+ + +

Return Values

+
+
  • OV_EINVAL indicates that an invalid argument value was submitted or that the stream represented by vf is not open.
  • +
  • OV_FALSE means the call returned a 'false' status, which in this case most likely indicates that the file is nonseekable and the upper, lower, and nominal bitrates were unset. +
  • n indicates the bitrate for the given logical bitstream or the entire + physical bitstream. If the file is open for random (seekable) access, it will + find the *actual* average bitrate. If the file is streaming (nonseekable), it + returns the nominal bitrate (if set) or else the average of the + upper/lower bounds (if set).
  • +
    +

    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_bitrate_instant.html b/libs/tremor/doc/ov_bitrate_instant.html new file mode 100644 index 0000000..874671f --- /dev/null +++ b/libs/tremor/doc/ov_bitrate_instant.html @@ -0,0 +1,65 @@ + + + +Tremor - function - ov_bitrate + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_bitrate_instant

    + +

    declared in "ivorbisfile.h";

    + +

    Used to find the most recent bitrate played back within the file. Will return 0 if the bitrate has not changed or it is the beginning of the file. + +

    + + + + +
    +
    
    +long ov_bitrate_instant(OggVorbis_File *vf);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions. +
    + + +

    Return Values

    +
    +
  • 0 indicates the beginning of the file or unchanged bitrate info.
  • +
  • n indicates the actual bitrate since the last call.
  • +
  • OV_FALSE indicates that playback is not in progress, and thus there is no instantaneous bitrate information to report.
  • +
  • OV_EINVAL indicates that the stream represented by vf is not open.
  • +
    +

    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_callbacks.html b/libs/tremor/doc/ov_callbacks.html new file mode 100644 index 0000000..776352d --- /dev/null +++ b/libs/tremor/doc/ov_callbacks.html @@ -0,0 +1,78 @@ + + + +Tremor - datatype - ov_callbacks + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_callbacks

    + +

    declared in "ivorbiscodec.h"

    + +

    +The ov_callbacks structure contains file manipulation function prototypes necessary for opening, closing, seeking, and location. + +

    +The ov_callbacks structure does not need to be user-defined if you are +working with stdio-based file manipulation; the ov_open() call provides default callbacks for +stdio. ov_callbacks are defined and passed to ov_open_callbacks() when +implementing non-stdio based stream manipulation (such as playback +from a memory buffer). +

    + + + + + +
    +
    typedef struct {
    +  size_t (*read_func)  (void *ptr, size_t size, size_t nmemb, void *datasource);
    +  int    (*seek_func)  (void *datasource, ogg_int64_t offset, int whence);
    +  int    (*close_func) (void *datasource);
    +  long   (*tell_func)  (void *datasource);
    +} ov_callbacks;
    +
    + +

    Relevant Struct Members

    +
    +
    read_func
    +
    Pointer to custom data reading function.
    +
    seek_func
    +
    Pointer to custom data seeking function. If the data source is not seekable (or the application wants the data source to be treated as unseekable at all times), the provided seek callback should always return -1 (failure).
    +
    close_func
    +
    Pointer to custom data source closure function.
    +
    tell_func
    +
    Pointer to custom data location function.
    +
    + +

    + +See the callbacks and non-stdio I/O document for more +detailed information on required behavior of the various callback +functions.

    + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_clear.html b/libs/tremor/doc/ov_clear.html new file mode 100644 index 0000000..7c51bb7 --- /dev/null +++ b/libs/tremor/doc/ov_clear.html @@ -0,0 +1,64 @@ + + + +Tremor - function - ov_clear + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_clear

    + +

    declared in "ivorbisfile.h";

    + +

    After a bitstream has been opened using ov_open()/ov_open_callbacks() and decoding is complete, the application must call ov_clear() to clear +the decoder's buffers and close the file.

    + +ov_clear() must also be called after a successful call to ov_test() or ov_test_callbacks().

    + +

    + + + + +
    +
    
    +int ov_clear(OggVorbis_File *vf);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions. After ov_clear has been called, the structure is deallocated and can no longer be used.
    +
    + + +

    Return Values

    +
    +
  • 0 for success
  • +
    + + +

    +
    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_comment.html b/libs/tremor/doc/ov_comment.html new file mode 100644 index 0000000..5d9cc0b --- /dev/null +++ b/libs/tremor/doc/ov_comment.html @@ -0,0 +1,66 @@ + + + +Tremor - function - ov_bitrate + + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_comment

    + +

    declared in "ivorbisfile.h";

    + +

    Returns a pointer to the vorbis_comment struct for the specified bitstream. For nonseekable streams, returns the struct for the current bitstream. +

    + +

    + + + + +
    +
    
    +vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    i
    +
    Link to the desired logical bitstream. For nonseekable files, this argument is ignored. To retrieve the vorbis_comment struct for the current bitstream, this parameter should be set to -1.
    +
    + + +

    Return Values

    +
    +
  • Returns the vorbis_comment struct for the specified bitstream.
  • +
  • NULL if the specified bitstream does not exist or the file has been initialized improperly.
  • +
    +

    + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_info.html b/libs/tremor/doc/ov_info.html new file mode 100644 index 0000000..d783bf3 --- /dev/null +++ b/libs/tremor/doc/ov_info.html @@ -0,0 +1,64 @@ + + + +Tremor - function - ov_info + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_info

    + +

    declared in "ivorbisfile.h";

    + +

    Returns the vorbis_info struct for the specified bitstream. For nonseekable files, always returns the current vorbis_info struct. + +

    + + + + +
    +
    
    +vorbis_info *ov_info(OggVorbis_File *vf,int link);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    i
    +
    Link to the desired logical bitstream. For nonseekable files, this argument is ignored. To retrieve the vorbis_info struct for the current bitstream, this parameter should be set to -1.
    +
    + + +

    Return Values

    +
    +
  • Returns the vorbis_info struct for the specified bitstream. Returns vorbis_info for current bitstream if the file is nonseekable or i=-1.
  • +
  • NULL if the specified bitstream does not exist or the file has been initialized improperly.
  • +
    +

    + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_open.html b/libs/tremor/doc/ov_open.html new file mode 100644 index 0000000..654cae8 --- /dev/null +++ b/libs/tremor/doc/ov_open.html @@ -0,0 +1,115 @@ + + + +Tremor - function - ov_open + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_open

    + +

    declared in "ivorbisfile.h";

    + +

    This is the main function used to open and initialize an OggVorbis_File +structure. It sets up all the related decoding structure. +

    The first argument must be a file pointer to an already opened file +or pipe (it need not be seekable--though this obviously restricts what +can be done with the bitstream). vf should be a pointer to the +OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions. Once this has been called, the same OggVorbis_File +struct should be passed to all the libvorbisidec functions. +

    Also, you should be aware that ov_open(), once successful, takes complete possession of the file resource. After you have opened a file using ov_open(), you MUST close it using ov_clear(), not fclose() or any other function. +

    +It is often useful to call ov_open() +simply to determine whether a given file is a vorbis bitstream. If the +ov_open() +call fails, then the file is not recognizable as such. +When you use ov_open() +for +this, you should fclose() the file pointer if, and only if, the +ov_open() +call fails. If it succeeds, you must call ov_clear() to clear +the decoder's buffers and close the file for you.

    + +(Note that ov_test() provides a less expensive way to test a file for Vorbisness.)

    + +

    + + + + +
    +
    
    +int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
    +
    +
    + +

    Parameters

    +
    +
    f
    +
    File pointer to an already opened file +or pipe (it need not be seekable--though this obviously restricts what +can be done with the bitstream).
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions. Once this has been called, the same OggVorbis_File +struct should be passed to all the libvorbisidec functions.
    +
    initial
    +
    Typically set to NULL. This parameter is useful if some data has already been +read from the file and the stream is not seekable. It is used in conjunction with ibytes. In this case, initial +should be a pointer to a buffer containing the data read.
    +
    ibytes
    +
    Typically set to 0. This parameter is useful if some data has already been +read from the file and the stream is not seekable. In this case, ibytes +should contain the length (in bytes) of the buffer. Used together with initial
    +
    + + +

    Return Values

    +
    +
  • 0 indicates success
  • + +
  • less than zero for failure:
  • +
      +
    • OV_EREAD - A read from media returned an error.
    • +
    • OV_ENOTVORBIS - Bitstream is not Vorbis data.
    • +
    • OV_EVERSION - Vorbis version mismatch.
    • +
    • OV_EBADHEADER - Invalid Vorbis bitstream header.
    • +
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.
    • +
    +
    +

    + +

    Notes

    +

    If your decoder is threaded, it is recommended that you NOT call +ov_open() +in the main control thread--instead, call ov_open() IN your decode/playback +thread. This is important because ov_open() may be a fairly time-consuming +call, given that the full structure of the file is determined at this point, +which may require reading large parts of the file under certain circumstances +(determining all the logical bitstreams in one physical bitstream, for +example). See Thread Safety for other information on using libvorbisidec with threads. + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_open_callbacks.html b/libs/tremor/doc/ov_open_callbacks.html new file mode 100644 index 0000000..64a2a92 --- /dev/null +++ b/libs/tremor/doc/ov_open_callbacks.html @@ -0,0 +1,110 @@ + + + +Tremor - function - ov_open_callbacks + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_open_callbacks

    + +

    declared in "ivorbisfile.h";

    + +

    This is an alternative function used to open and initialize an OggVorbis_File +structure when using a data source other than a file. It allows you to specify custom file manipulation routines and sets up all the related decoding structure. +

    Once this has been called, the same OggVorbis_File +struct should be passed to all the libvorbisidec functions. +

    +It is often useful to call ov_open_callbacks() +simply to determine whether a given file is a vorbis bitstream. If the +ov_open_callbacks() +call fails, then the file is not recognizable as such. When you use ov_open_callbacks() +for +this, you should fclose() the file pointer if, and only if, the +ov_open_callbacks() +call fails. If it succeeds, you must call ov_clear() to clear +the decoder's buffers and close the file for you.

    + +See also Callbacks and Non-stdio I/O for information on designing and specifying the required callback functions.

    + +

    + + + + +
    +
    
    +int ov_open_callbacks(void *datasource, OggVorbis_File *vf, char *initial, long ibytes, ov_callbacks callbacks);
    +
    +
    + +

    Parameters

    +
    +
    f
    +
    File pointer to an already opened file +or pipe (it need not be seekable--though this obviously restricts what +can be done with the bitstream).
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions. Once this has been called, the same OggVorbis_File +struct should be passed to all the libvorbisidec functions.
    +
    initial
    +
    Typically set to NULL. This parameter is useful if some data has already been +read from the file and the stream is not seekable. It is used in conjunction with ibytes. In this case, initial +should be a pointer to a buffer containing the data read.
    +
    ibytes
    +
    Typically set to 0. This parameter is useful if some data has already been +read from the file and the stream is not seekable. In this case, ibytes +should contain the length (in bytes) of the buffer. Used together with initial.
    +
    callbacks
    +
    Pointer to a completed ov_callbacks struct which indicates desired custom file manipulation routines.
    +
    + + +

    Return Values

    +
    +
  • 0 for success
  • +
  • less than zero for failure:
  • +
      +
    • OV_EREAD - A read from media returned an error.
    • +
    • OV_ENOTVORBIS - Bitstream is not Vorbis data.
    • +
    • OV_EVERSION - Vorbis version mismatch.
    • +
    • OV_EBADHEADER - Invalid Vorbis bitstream header.
    • +
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.
    • +
    +
    +

    + +

    Notes

    +

    If your decoder is threaded, it is recommended that you NOT call +ov_open_callbacks() +in the main control thread--instead, call ov_open_callbacks() IN your decode/playback +thread. This is important because ov_open_callbacks() may be a fairly time-consuming +call, given that the full structure of the file is determined at this point, +which may require reading large parts of the file under certain circumstances +(determining all the logical bitstreams in one physical bitstream, for +example). +See Thread Safety for other information on using libvorbisidec with threads. + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_pcm_seek.html b/libs/tremor/doc/ov_pcm_seek.html new file mode 100644 index 0000000..cf0351e --- /dev/null +++ b/libs/tremor/doc/ov_pcm_seek.html @@ -0,0 +1,81 @@ + + + +Tremor - function - ov_pcm_seek + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_pcm_seek

    + +

    declared in "ivorbisfile.h";

    + +

    Seeks to the offset specified (in pcm samples) within the physical bitstream. This function only works for seekable streams. +

    This also updates everything needed within the +decoder, so you can immediately call ov_read() and get data from +the newly seeked to position. +

    + +

    + + + + +
    +
    
    +int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    pos
    +
    Position in pcm samples to seek to in the bitstream.
    +
    + + +

    Return Values

    +
    +
  • 0 for success
  • + +
  • +nonzero indicates failure, described by several error codes:
  • +
      +
    • OV_ENOSEEK - Bitstream is not seekable. +
    • +
    • OV_EINVAL - Invalid argument value. +
    • +
    • OV_EREAD - A read from media returned an error. +
    • +
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack + corruption. +
    • +
    • OV_EBADLINK - Invalid stream section supplied to libvorbisidec, or the requested link is corrupt. +
    • +
    + +

    +
    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_pcm_seek_page.html b/libs/tremor/doc/ov_pcm_seek_page.html new file mode 100644 index 0000000..44468a8 --- /dev/null +++ b/libs/tremor/doc/ov_pcm_seek_page.html @@ -0,0 +1,83 @@ + + + +Tremor - function - ov_pcm_seek_page + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_pcm_seek_page

    + +

    declared in "ivorbisfile.h";

    + +

    Seeks to the closest page preceding the specified location (in pcm samples) within the physical bitstream. This function only works for seekable streams. +

    This function is faster than ov_pcm_seek because the function can begin decoding at a page boundary rather than seeking through any remaining samples before the specified location. However, it is less accurate. +

    This also updates everything needed within the +decoder, so you can immediately call ov_read() and get data from +the newly seeked to position. +

    + +

    + + + + +
    +
    
    +int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    pos
    +
    Position in pcm samples to seek to in the bitstream.
    +
    + + +

    Return Values

    +
    +
  • +0 for success
  • + +
  • +nonzero indicates failure, described by several error codes:
  • +
      +
    • OV_ENOSEEK - Bitstream is not seekable. +
    • +
    • OV_EINVAL - Invalid argument value. +
    • +
    • OV_EREAD - A read from media returned an error. +
    • +
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack + corruption. +
    • +
    • OV_EBADLINK - Invalid stream section supplied to libvorbisidec, or the requested link is corrupt. +
    • +
    + +

    +
    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_pcm_tell.html b/libs/tremor/doc/ov_pcm_tell.html new file mode 100644 index 0000000..0bb98d7 --- /dev/null +++ b/libs/tremor/doc/ov_pcm_tell.html @@ -0,0 +1,63 @@ + + + +Tremor - function - ov_pcm_tell + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_pcm_tell

    + +

    declared in "ivorbisfile.h";

    + +

    Returns the current offset in samples. + +

    + + + + +
    +
    
    +ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    + + +

    Return Values

    +
    +
  • n indicates the current offset in samples.
  • +
  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist.
  • +
    +

    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_pcm_total.html b/libs/tremor/doc/ov_pcm_total.html new file mode 100644 index 0000000..a19744a --- /dev/null +++ b/libs/tremor/doc/ov_pcm_total.html @@ -0,0 +1,67 @@ + + + +Tremor - function - ov_pcm_total + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_pcm_total

    + +

    declared in "ivorbisfile.h";

    + +

    Returns the total pcm samples of the physical bitstream or a specified logical bitstream. + +

    + + + + +
    +
    
    +ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    i
    +
    Link to the desired logical bitstream. To retrieve the total pcm samples for the entire physical bitstream, this parameter should be set to -1.
    +
    + + +

    Return Values

    +
    +
  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist or the bitstream is unseekable.
  • +
  • +total length in pcm samples of content if i=-1.
  • +
  • length in pcm samples of logical bitstream if i=1 to n.
  • +
    +

    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_raw_seek.html b/libs/tremor/doc/ov_raw_seek.html new file mode 100644 index 0000000..e7f0bd3 --- /dev/null +++ b/libs/tremor/doc/ov_raw_seek.html @@ -0,0 +1,75 @@ + + + +Tremor - function - ov_raw_seek + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_raw_seek

    + +

    declared in "ivorbisfile.h";

    + +

    Seeks to the offset specified (in compressed raw bytes) within the physical bitstream. This function only works for seekable streams. +

    This also updates everything needed within the +decoder, so you can immediately call ov_read() and get data from +the newly seeked to position. +

    When seek speed is a priority, this is the best seek funtion to use. +

    + + + + +
    +
    
    +int ov_raw_seek(OggVorbis_File *vf,long pos);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    pos
    +
    Position in compressed bytes to seek to in the bitstream.
    +
    + + +

    Return Values

    +
    +
  • 0 indicates success
  • +
  • nonzero indicates failure, described by several error codes:
  • +
      +
    • OV_ENOSEEK - Bitstream is not seekable. +
    • +
    • OV_EINVAL - Invalid argument value. +
    • +
    • OV_EBADLINK - Invalid stream section supplied to libvorbisidec, or the requested link is corrupt. +
    • +
    +
    +

    + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_raw_tell.html b/libs/tremor/doc/ov_raw_tell.html new file mode 100644 index 0000000..f0d1f6a --- /dev/null +++ b/libs/tremor/doc/ov_raw_tell.html @@ -0,0 +1,63 @@ + + + +Tremor - function - ov_raw_tell + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_raw_tell

    + +

    declared in "ivorbisfile.h";

    + +

    Returns the current offset in raw compressed bytes. + +

    + + + + +
    +
    
    +ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    + + +

    Return Values

    +
    +
  • n indicates the current offset in bytes.
  • +
  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist.
  • +
    +

    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_raw_total.html b/libs/tremor/doc/ov_raw_total.html new file mode 100644 index 0000000..d0af35f --- /dev/null +++ b/libs/tremor/doc/ov_raw_total.html @@ -0,0 +1,68 @@ + + + +Tremor - function - ov_raw_total + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_raw_total

    + +

    declared in "ivorbisfile.h";

    + +

    Returns the total (compressed) bytes of the physical bitstream or a specified logical bitstream. + +

    + + + + +
    +
    
    +ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    i
    +
    Link to the desired logical bitstream. To retrieve the total bytes for the entire physical bitstream, this parameter should be set to -1.
    +
    + + +

    Return Values

    +
    +
  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist or the bitstream is nonseekable
  • +
  • n +total length in compressed bytes of content if i=-1.
  • +
  • n length in compressed bytes of logical bitstream if i=1 to n.
  • +
    +

    + + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_read.html b/libs/tremor/doc/ov_read.html new file mode 100644 index 0000000..208ef18 --- /dev/null +++ b/libs/tremor/doc/ov_read.html @@ -0,0 +1,115 @@ + + + +Tremor - function - ov_read + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_read()

    + +

    declared in "ivorbisfile.h";

    + +

    + This is the main function used to decode a Vorbis file within a + loop. It returns up to the specified number of bytes of decoded audio + in host-endian, signed 16 bit PCM format. If the audio is + multichannel, the channels are interleaved in the output buffer. + If the passed in buffer is large, ov_read() will not fill + it; the passed in buffer size is treated as a limit and + not a request. +

    + +Note that up to this point, the Tremor API could more or less hide the + multiple logical bitstream nature of chaining from the toplevel + application if the toplevel application didn't particularly care. + However, when reading audio back, the application must be aware + that multiple bitstream sections do not necessarily use the same + number of channels or sampling rate.

    ov_read() passes + back the index of the sequential logical bitstream currently being + decoded (in *bitstream) along with the PCM data in order + that the toplevel application can handle channel and/or sample + rate changes. This number will be incremented at chaining + boundaries even for non-seekable streams. For seekable streams, it + represents the actual chaining index within the physical bitstream. +

    + +

    + + + + +
    +
    
    +long ov_read(OggVorbis_File *vf, char *buffer, int length, int *bitstream);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    buffer
    +
    A pointer to an output buffer. The decoded output is inserted into this buffer.
    +
    length
    +
    Number of bytes to be read into the buffer. Should be the same size as the buffer. A typical value is 4096.
    +
    bitstream
    +
    A pointer to the number of the current logical bitstream.
    +
    + + +

    Return Values

    +
    +
    +
    OV_HOLE
    +
    indicates there was an interruption in the data. +
    (one of: garbage between pages, loss of sync followed by + recapture, or a corrupt page)
    +
    OV_EBADLINK
    +
    indicates that an invalid stream section was supplied to + libvorbisidec, or the requested link is corrupt.
    +
    0
    +
    indicates EOF
    +
    n
    +
    indicates actual number of bytes read. ov_read() will + decode at most one vorbis packet per invocation, so the value + returned will generally be less than length. +
    +
    + +

    Notes

    +

    Typical usage: +

    +bytes_read = ov_read(&vf, +buffer, 4096,&current_section) +
    + +This reads up to 4096 bytes into a buffer, with signed 16-bit +little-endian samples. +

    + + + +

    +
    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_seekable.html b/libs/tremor/doc/ov_seekable.html new file mode 100644 index 0000000..9bd7fc3 --- /dev/null +++ b/libs/tremor/doc/ov_seekable.html @@ -0,0 +1,63 @@ + + + +Tremor - function - ov_seekable + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_seekable

    + +

    declared in "ivorbisfile.h";

    + +

    This indicates whether or not the bitstream is seekable. + + +

    + + + + +
    +
    
    +long ov_seekable(OggVorbis_File *vf);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    + + +

    Return Values

    +
    +
  • 0 indicates that the file is not seekable.
  • +
  • nonzero indicates that the file is seekable.
  • +
    +

    + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_serialnumber.html b/libs/tremor/doc/ov_serialnumber.html new file mode 100644 index 0000000..d7d7c62 --- /dev/null +++ b/libs/tremor/doc/ov_serialnumber.html @@ -0,0 +1,67 @@ + + + +Tremor - function - ov_serialnumber + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_serialnumber

    + +

    declared in "ivorbisfile.h";

    + +

    Returns the serialnumber of the specified logical bitstream link number within the overall physical bitstream. + +

    + + + + +
    +
    
    +long ov_serialnumber(OggVorbis_File *vf,int i);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    i
    +
    Link to the desired logical bitstream. For nonseekable files, this argument is ignored. To retrieve the serial number of the current bitstream, this parameter should be set to -1.
    +
    + + +

    Return Values

    +
    +
  • +-1 if the specified logical bitstream i does not exist.
  • + +
  • Returns the serial number of the logical bitstream i or the serial number of the current bitstream if the file is nonseekable.
  • +
    +

    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_streams.html b/libs/tremor/doc/ov_streams.html new file mode 100644 index 0000000..7ffee42 --- /dev/null +++ b/libs/tremor/doc/ov_streams.html @@ -0,0 +1,64 @@ + + + +Tremor - function - ov_streams + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_streams

    + +

    declared in "ivorbisfile.h";

    + +

    Returns the number of logical bitstreams within our physical bitstream. + +

    + + + + +
    +
    
    +long ov_streams(OggVorbis_File *vf);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    + + +

    Return Values

    +
    +
  • +1 indicates a single logical bitstream or an unseekable file.
  • +
  • n indicates the number of logical bitstreams.
  • +
    +

    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_test.html b/libs/tremor/doc/ov_test.html new file mode 100644 index 0000000..96a9af0 --- /dev/null +++ b/libs/tremor/doc/ov_test.html @@ -0,0 +1,89 @@ + + + +Tremor - function - ov_test + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_test

    + +

    declared in "ivorbisfile.h";

    + +

    +This partially opens a vorbis file to test for Vorbis-ness. It loads +the headers for the first chain, and tests for seekability (but does not seek). +Use ov_test_open() to finish opening the file +or ov_clear to close/free it. +

    + + + + + +
    +
    
    +int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
    +
    +
    + +

    Parameters

    +
    +
    f
    +
    File pointer to an already opened file +or pipe (it need not be seekable--though this obviously restricts what +can be done with the bitstream).
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions. Once this has been called, the same OggVorbis_File +struct should be passed to all the libvorbisidec functions.
    +
    initial
    +
    Typically set to NULL. This parameter is useful if some data has already been +read from the file and the stream is not seekable. It is used in conjunction with ibytes. In this case, initial +should be a pointer to a buffer containing the data read.
    +
    ibytes
    +
    Typically set to 0. This parameter is useful if some data has already been +read from the file and the stream is not seekable. In this case, ibytes +should contain the length (in bytes) of the buffer. Used together with initial
    +
    + + +

    Return Values

    +
    +
  • 0 for success
  • + +
  • less than zero for failure:
  • +
      +
    • OV_EREAD - A read from media returned an error.
    • +
    • OV_ENOTVORBIS - Bitstream is not Vorbis data.
    • +
    • OV_EVERSION - Vorbis version mismatch.
    • +
    • OV_EBADHEADER - Invalid Vorbis bitstream header.
    • +
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.
    • +
    +
    +

    + + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_test_callbacks.html b/libs/tremor/doc/ov_test_callbacks.html new file mode 100644 index 0000000..4049548 --- /dev/null +++ b/libs/tremor/doc/ov_test_callbacks.html @@ -0,0 +1,90 @@ + + + +Tremor - function - ov_test_callbacks + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_test_callbacks

    + +

    declared in "ivorbisfile.h";

    + +

    This is an alternative function used to open and test an OggVorbis_File +structure when using a data source other than a file. It allows you to specify custom file manipulation routines and sets up all the related decoding structures. +

    Once this has been called, the same OggVorbis_File +struct should be passed to all the libvorbisidec functions. +

    +

    + + + + +
    +
    
    +int ov_test_callbacks(void *datasource, OggVorbis_File *vf, char *initial, long ibytes, ov_callbacks callbacks);
    +
    +
    + +

    Parameters

    +
    +
    f
    +
    File pointer to an already opened file +or pipe (it need not be seekable--though this obviously restricts what +can be done with the bitstream).
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions. Once this has been called, the same OggVorbis_File +struct should be passed to all the libvorbisidec functions.
    +
    initial
    +
    Typically set to NULL. This parameter is useful if some data has already been +read from the file and the stream is not seekable. It is used in conjunction with ibytes. In this case, initial +should be a pointer to a buffer containing the data read.
    +
    ibytes
    +
    Typically set to 0. This parameter is useful if some data has already been +read from the file and the stream is not seekable. In this case, ibytes +should contain the length (in bytes) of the buffer. Used together with initial.
    +
    callbacks
    +
    Pointer to a completed ov_callbacks struct which indicates desired custom file manipulation routines.
    +
    + + +

    Return Values

    +
    +
  • 0 for success
  • +
  • less than zero for failure:
  • +
      +
    • OV_EREAD - A read from media returned an error.
    • +
    • OV_ENOTVORBIS - Bitstream is not Vorbis data.
    • +
    • OV_EVERSION - Vorbis version mismatch.
    • +
    • OV_EBADHEADER - Invalid Vorbis bitstream header.
    • +
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.
    • +
    +
    +

    + + + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_test_open.html b/libs/tremor/doc/ov_test_open.html new file mode 100644 index 0000000..74f4410 --- /dev/null +++ b/libs/tremor/doc/ov_test_open.html @@ -0,0 +1,82 @@ + + + +Tremor - function - ov_test_open + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_test_open

    + +

    declared in "ivorbisfile.h";

    + +

    +Finish opening a file partially opened with ov_test() +or ov_test_callbacks(). +

    + + + + + +
    +
    
    +int ov_test_open(OggVorbis_File *vf);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions. Once this has been called, the same OggVorbis_File +struct should be passed to all the libvorbisidec functions.
    +
    + + +

    Return Values

    +
    +
  • +0 for success
  • + +
  • less than zero for failure:
  • +
      +
    • OV_EREAD - A read from media returned an error.
    • +
    • OV_ENOTVORBIS - Bitstream is not Vorbis data.
    • +
    • OV_EVERSION - Vorbis version mismatch.
    • +
    • OV_EBADHEADER - Invalid Vorbis bitstream header.
    • +
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack corruption.
    • +
    +
    +

    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + + + + + + + + diff --git a/libs/tremor/doc/ov_time_seek.html b/libs/tremor/doc/ov_time_seek.html new file mode 100644 index 0000000..6dfa130 --- /dev/null +++ b/libs/tremor/doc/ov_time_seek.html @@ -0,0 +1,70 @@ + + + +Tremor - function - ov_time_seek + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_time_seek

    + +

    declared in "ivorbisfile.h";

    + +

    For seekable +streams, this seeks to the given time. For implementing seeking in a player, +this is the only function generally needed. This also updates everything needed within the +decoder, so you can immediately call ov_read() and get data from +the newly seeked to position. This function does not work for unseekable streams. + +

    + + + + +
    +
    
    +int ov_time_seek(OggVorbis_File *vf, ogg_int64_t ms);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    Pointer to our already opened and initialized OggVorbis_File structure.
    +
    ms
    +
    Location to seek to within the file, specified in milliseconds.
    +
    + + +

    Return Values

    +
    +
  • +0 for success
  • + +
  • +Nonzero for failure
  • +
    + + +

    +
    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_time_seek_page.html b/libs/tremor/doc/ov_time_seek_page.html new file mode 100644 index 0000000..83cfefb --- /dev/null +++ b/libs/tremor/doc/ov_time_seek_page.html @@ -0,0 +1,83 @@ + + + +Tremor - function - ov_time_seek_page + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_time_seek_page

    + +

    declared in "ivorbisfile.h";

    + +

    For seekable +streams, this seeks to closest full page preceding the given time. This function is faster than ov_time_seek because it doesn't seek through the last few samples to reach an exact time, but it is also less accurate. This should be used when speed is important. +

    This function also updates everything needed within the +decoder, so you can immediately call ov_read() and get data from +the newly seeked to position. +

    This function does not work for unseekable streams. + +

    + + + + +
    +
    
    +int ov_time_seek_page(OggVorbis_File *vf, ogg_int64_t ms);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    Pointer to our already opened and initialized OggVorbis_File structure.
    +
    ms
    +
    Location to seek to within the file, specified in milliseconds.
    +
    + + +

    Return Values

    +
    +
  • +0 for success
  • + +
  • +nonzero indicates failure, described by several error codes:
  • +
      +
    • OV_ENOSEEK - Bitstream is not seekable. +
    • +
    • OV_EINVAL - Invalid argument value. +
    • +
    • OV_EREAD - A read from media returned an error. +
    • +
    • OV_EFAULT - Internal logic fault; indicates a bug or heap/stack + corruption. +
    • +
    • OV_EBADLINK - Invalid stream section supplied to libvorbisidec, or the requested link is corrupt. +
    • +
    + + +

    +
    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_time_tell.html b/libs/tremor/doc/ov_time_tell.html new file mode 100644 index 0000000..25d159b --- /dev/null +++ b/libs/tremor/doc/ov_time_tell.html @@ -0,0 +1,63 @@ + + + +Tremor - function - ov_bitrate + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_time_tell

    + +

    declared in "ivorbisfile.h";

    + +

    Returns the current decoding offset in milliseconds. + +

    + + + + +
    +
    
    +ogg_int64_t ov_time_tell(OggVorbis_File *vf);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    + + +

    Return Values

    +
    +
  • n indicates the current decoding time offset in milliseconds.
  • +
  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist.
  • +
    +

    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/ov_time_total.html b/libs/tremor/doc/ov_time_total.html new file mode 100644 index 0000000..7c26b92 --- /dev/null +++ b/libs/tremor/doc/ov_time_total.html @@ -0,0 +1,67 @@ + + + +Tremor - function - ov_time_total + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    ov_time_total

    + +

    declared in "ivorbisfile.h";

    + + +

    Returns the total time in seconds of the physical bitstream or a specified logical bitstream. + + +

    + + + + +
    +
    
    +ogg_int64_t ov_time_total(OggVorbis_File *vf,int i);
    +
    +
    + +

    Parameters

    +
    +
    vf
    +
    A pointer to the OggVorbis_File structure--this is used for ALL the externally visible libvorbisidec +functions.
    +
    i
    +
    Link to the desired logical bitstream. To retrieve the time total for the entire physical bitstream, this parameter should be set to -1.
    +
    + + +

    Return Values

    +
    +
  • OV_EINVAL means that the argument was invalid. In this case, the requested bitstream did not exist or the bitstream is nonseekable.
  • +
  • n total length in milliseconds of content if i=-1.
  • +
  • n length in milliseconds of logical bitstream if i=1 to n.
  • +
    +

    + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/overview.html b/libs/tremor/doc/overview.html new file mode 100644 index 0000000..0c82cb2 --- /dev/null +++ b/libs/tremor/doc/overview.html @@ -0,0 +1,61 @@ + + + +Tremor - API Overview + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    Tremor API Overview

    + +

    The makeup of the Tremor libvorbisidec library API is relatively +simple. It revolves around a single file resource. This file resource is +passed to libvorbisidec, where it is opened, manipulated, and closed, +in the form of an OggVorbis_File +struct. +

    +The Tremor API consists of the following functional categories: +

    +

    +

    +In addition, the following subjects deserve attention additional to +the above general overview: +

    +

    +

    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + + diff --git a/libs/tremor/doc/reference.html b/libs/tremor/doc/reference.html new file mode 100644 index 0000000..20e0a5f --- /dev/null +++ b/libs/tremor/doc/reference.html @@ -0,0 +1,75 @@ + + + +Tremor API Reference + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    Tremor API Reference

    + +

    +Data Structures
    +OggVorbis_File
    +vorbis_comment
    +vorbis_info
    +ov_callbacks
    +
    +Setup/Teardown
    +ov_open()
    +ov_open_callbacks()
    +ov_clear()
    +ov_test()
    +ov_test_callbacks()
    +ov_test_open()
    +
    +Decoding
    +ov_read()
    +
    +Seeking
    +ov_raw_seek()
    +ov_pcm_seek()
    +ov_time_seek()
    +ov_pcm_seek_page()
    +ov_time_seek_page()
    +
    +File Information
    +ov_bitrate()
    +ov_bitrate_instant()
    +ov_streams()
    +ov_seekable()
    +ov_serialnumber()
    +ov_raw_total()
    +ov_pcm_total()
    +ov_time_total()
    +ov_raw_tell()
    +ov_pcm_tell()
    +ov_time_tell()
    +ov_info()
    +ov_comment()
    +
    +Return Codes
    + + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/return.html b/libs/tremor/doc/return.html new file mode 100644 index 0000000..0a3f96c --- /dev/null +++ b/libs/tremor/doc/return.html @@ -0,0 +1,77 @@ + + + +Tremor - Return Codes + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    Return Codes

    + +

    + +The following return codes are #defined in "ivorbiscodec.h" +may be returned by libvorbisidec. Descriptions of a code relevant to +a specific function are found in the reference description of that +function. + +

    + +
    OV_FALSE
    +
    Not true, or no data available
    + +
    OV_HOLE
    +
    Tremor encoutered missing or corrupt data in the bitstream. Recovery +is normally automatic and this return code is for informational purposes only.
    + +
    OV_EREAD
    +
    Read error while fetching compressed data for decode
    + +
    OV_EFAULT
    +
    Internal inconsistency in decode state. Continuing is likely not possible.
    + +
    OV_EIMPL
    +
    Feature not implemented
    + +
    OV_EINVAL
    +
    Either an invalid argument, or incompletely initialized argument passed to libvorbisidec call
    + +
    OV_ENOTVORBIS
    +
    The given file/data was not recognized as Ogg Vorbis data.
    + +
    OV_EBADHEADER
    +
    The file/data is apparently an Ogg Vorbis stream, but contains a corrupted or undecipherable header.
    + +
    OV_EVERSION
    +
    The bitstream format revision of the given stream is not supported.
    + +
    OV_EBADLINK
    +
    The given link exists in the Vorbis data stream, but is not decipherable due to garbacge or corruption.
    + +
    OV_ENOSEEK
    +
    The given stream is not seekable
    + +
    + +

    +
    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/seeking.html b/libs/tremor/doc/seeking.html new file mode 100644 index 0000000..652368a --- /dev/null +++ b/libs/tremor/doc/seeking.html @@ -0,0 +1,74 @@ + + + +Tremor - Seeking + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    Seeking

    +

    Seeking functions allow you to specify a specific point in the stream to begin or continue decoding. +

    +All libvorbisidec seeking routines are declared in "ivorbisfile.h". + +

    Certain seeking functions are best suited to different situations. +When speed is important and exact positioning isn't required, +page-level seeking should be used. Note also that Vorbis files do not +necessarily start at a sample number or time offset of zero. Do not +be surprised if a file begins at a positive offset of several minutes +or hours, such as would happen if a large stream (such as a concert +recording) is chopped into multiple separate files. Requesting to +seek to a position before the beginning of such a file will seek to +the position where audio begins.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    functionpurpose
    ov_raw_seekThis function seeks to a position specified in the compressed bitstream, specified in bytes.
    ov_pcm_seekThis function seeks to a specific audio sample number, specified in pcm samples.
    ov_pcm_seek_pageThis function seeks to the closest page preceding the specified audio sample number, specified in pcm samples.
    ov_time_seekThis function seeks to the specific time location in the bitstream, specified in integer milliseconds. Note that this differs from the reference vorbisfile implementation, which takes seconds as a float.
    ov_time_seek_pageThis function seeks to the closest page preceding the specified time position in the bitstream, specified in integer milliseconds.
    + +

    +


    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/style.css b/libs/tremor/doc/style.css new file mode 100644 index 0000000..81cf417 --- /dev/null +++ b/libs/tremor/doc/style.css @@ -0,0 +1,7 @@ +BODY { font-family: Helvetica, sans-serif } +TD { font-family: Helvetica, sans-serif } +P { font-family: Helvetica, sans-serif } +H1 { font-family: Helvetica, sans-serif } +H2 { font-family: Helvetica, sans-serif } +H4 { font-family: Helvetica, sans-serif } +P.tiny { font-size: 8pt } diff --git a/libs/tremor/doc/threads.html b/libs/tremor/doc/threads.html new file mode 100644 index 0000000..53ed76a --- /dev/null +++ b/libs/tremor/doc/threads.html @@ -0,0 +1,50 @@ + + + +Tremor - Thread Safety + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    Thread Safety

    + +Tremor's libvorbisidec may be used safely in a threading environment +so long as thread access to individual OggVorbis_File instances is serialized. +
      + +
    • Only one thread at a time may enter a function that takes a given OggVorbis_File instance, even if the +functions involved appear to be read-only.

      + +

    • Multiple threads may enter +libvorbisidec at a given time, so long as each thread's function calls +are using different OggVorbis_File +instances.

      + +

    • Any one OggVorbis_File instance may be used safely from multiple threads so long as only one thread at a time is making calls using that instance.

      +

    + +

    +
    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/vorbis_comment.html b/libs/tremor/doc/vorbis_comment.html new file mode 100644 index 0000000..3232d96 --- /dev/null +++ b/libs/tremor/doc/vorbis_comment.html @@ -0,0 +1,70 @@ + + + +Tremor - datatype - vorbis_comment + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    vorbis_comment

    + +

    declared in "ivorbiscodec.h"

    + +

    +The vorbis_comment structure defines an Ogg Vorbis comment. +

    +Only the fields the program needs must be defined. If a field isn't +defined by the application, it will either be blank (if it's a string value) +or set to some reasonable default (usually 0). +

    + + + + + +
    +
    typedef struct vorbis_comment{
    +  /* unlimited user comment fields. */
    +  char **user_comments;
    +  int  *comment_lengths;
    +  int  comments;
    +  char *vendor;
    +
    +} vorbis_comment;
    +
    + +

    Parameters

    +
    +
    user_comments
    +
    Unlimited user comment array. The individual strings in the array are 8 bit clean, by the Vorbis specification, and as such the comment_lengths array should be consulted to determine string length. For convenience, each string is also NULL-terminated by the decode library (although Vorbis comments are not NULL terminated within the bitstream itself).
    +
    comment_lengths
    +
    An int array that stores the length of each comment string
    +
    comments
    +
    Int signifying number of user comments in user_comments field.
    +
    vendor
    +
    Information about the creator of the file. Stored in a standard C 0-terminated string.
    +
    + + +

    +
    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/doc/vorbis_info.html b/libs/tremor/doc/vorbis_info.html new file mode 100644 index 0000000..bd938cd --- /dev/null +++ b/libs/tremor/doc/vorbis_info.html @@ -0,0 +1,80 @@ + + + +Tremor - datatype - vorbis_info + + + + + + + + + +

    Tremor documentation

    Tremor version 1.0 - 20020403

    + +

    vorbis_info

    + +

    declared in "ivorbiscodec.h"

    + +

    +The vorbis_info structure contains basic information about the audio in a vorbis bitstream. +

    + + + + + +
    +
    typedef struct vorbis_info{
    +  int version;
    +  int channels;
    +  long rate;
    +  
    +  long bitrate_upper;
    +  long bitrate_nominal;
    +  long bitrate_lower;
    +  long bitrate_window;
    +
    +  void *codec_setup;
    +
    +} vorbis_info;
    +
    + +

    Relevant Struct Members

    +
    +
    version
    +
    Vorbis encoder version used to create this bitstream.
    +
    channels
    +
    Int signifying number of channels in bitstream.
    +
    rate
    +
    Sampling rate of the bitstream.
    +
    bitrate_upper
    +
    Specifies the upper limit in a VBR bitstream. If the value matches the bitrate_nominal and bitrate_lower parameters, the stream is fixed bitrate. May be unset if no limit exists.
    +
    bitrate_nominal
    +
    Specifies the average bitrate for a VBR bitstream. May be unset. If the bitrate_upper and bitrate_lower parameters match, the stream is fixed bitrate.
    +
    bitrate_lower
    +
    Specifies the lower limit in a VBR bitstream. If the value matches the bitrate_nominal and bitrate_upper parameters, the stream is fixed bitrate. May be unset if no limit exists.
    +
    bitrate_window
    +
    Currently unset.
    + +
    codec_setup
    +
    Internal structure that contains the detailed/unpacked configuration for decoding the current Vorbis bitstream.
    +
    + + +

    +
    + + + + + + + + +

    copyright © 2002 Xiph.org

    Ogg Vorbis

    Tremor documentation

    Tremor version 1.0 - 20020403

    + + + + diff --git a/libs/tremor/floor0.c b/libs/tremor/floor0.c new file mode 100644 index 0000000..964383e --- /dev/null +++ b/libs/tremor/floor0.c @@ -0,0 +1,439 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: floor backend 0 implementation + + ********************************************************************/ + +#include +#include +#include +#include +#include "ivorbiscodec.h" +#include "codec_internal.h" +#include "registry.h" +#include "codebook.h" +#include "misc.h" +#include "block.h" + +#define LSP_FRACBITS 14 + +typedef struct { + long n; + int ln; + int m; + int *linearmap; + + vorbis_info_floor0 *vi; + ogg_int32_t *lsp_look; + +} vorbis_look_floor0; + +/*************** LSP decode ********************/ + +#include "lsp_lookup.h" + +/* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in + 16.16 format + returns in m.8 format */ + +static long ADJUST_SQRT2[2]={8192,5792}; +STIN ogg_int32_t vorbis_invsqlook_i(long a,long e){ + long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1); + long d=a&INVSQ_LOOKUP_I_MASK; /* 0.10 */ + long val=INVSQ_LOOKUP_I[i]- /* 1.16 */ + ((INVSQ_LOOKUP_IDel[i]*d)>>INVSQ_LOOKUP_I_SHIFT); /* result 1.16 */ + val*=ADJUST_SQRT2[e&1]; + e=(e>>1)+21; + return(val>>e); +} + +/* interpolated lookup based fromdB function, domain -140dB to 0dB only */ +/* a is in n.12 format */ +STIN ogg_int32_t vorbis_fromdBlook_i(long a){ + int i=(-a)>>(12-FROMdB2_SHIFT); + if(i<0) return 0x7fffffff; + if(i>=(FROMdB_LOOKUP_SZ<>FROMdB_SHIFT] * FROMdB2_LOOKUP[i&FROMdB2_MASK]; +} + +/* interpolated lookup based cos function, domain 0 to PI only */ +/* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */ +STIN ogg_int32_t vorbis_coslook_i(long a){ + int i=a>>COS_LOOKUP_I_SHIFT; + int d=a&COS_LOOKUP_I_MASK; + return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>> + COS_LOOKUP_I_SHIFT); +} + +/* interpolated lookup based cos function */ +/* a is in 0.16 format, where 0==0, 2^^16==PI, return .LSP_FRACBITS */ +STIN ogg_int32_t vorbis_coslook2_i(long a){ + a=a&0x1ffff; + + if(a>0x10000)a=0x20000-a; + { + int i=a>>COS_LOOKUP_I_SHIFT; + int d=a&COS_LOOKUP_I_MASK; + a=((COS_LOOKUP_I[i]<> + (COS_LOOKUP_I_SHIFT-LSP_FRACBITS+14); + } + + return(a); +} + +static const int barklook[28]={ + 0,100,200,301, 405,516,635,766, + 912,1077,1263,1476, 1720,2003,2333,2721, + 3184,3742,4428,5285, 6376,7791,9662,12181, + 15624,20397,27087,36554 +}; + +/* used in init only; interpolate the long way */ +STIN ogg_int32_t toBARK(int n){ + int i; + for(i=0;i<27;i++) + if(n>=barklook[i] && n>10)*0x517d)>>14; +#endif + + /* safeguard against a malicious stream */ + if(val<0 || (val>>COS_LOOKUP_I_SHIFT)>=COS_LOOKUP_I_SZ){ + memset(curve,0,sizeof(*curve)*n); + return; + } + + ilsp[i]=vorbis_coslook_i(val); + } + + i=0; + while(i>16); + qi=((qi*qi)>>16); + + if(m&1){ + qexp= qexp*2-28*((m+1)>>1)+m; + pi*=(1<<14)-((wi*wi)>>14); + qi+=pi>>14; + }else{ + qexp= qexp*2-13*m; + + pi*=(1<<14)-wi; + qi*=(1<<14)+wi; + + qi=(qi+pi)>>14; + } + + if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */ + qi>>=1; qexp++; + }else + lsp_norm_asm(&qi,&qexp); + +#else + + j=1; + if(m>1){ + qi*=labs(ilsp[0]-wi); + pi*=labs(ilsp[1]-wi); + + for(j+=2;j>25])) + if(!(shift=MLOOP_2[(pi|qi)>>19])) + shift=MLOOP_3[(pi|qi)>>16]; + qi=(qi>>shift)*labs(ilsp[j-1]-wi); + pi=(pi>>shift)*labs(ilsp[j]-wi); + qexp+=shift; + } + } + if(!(shift=MLOOP_1[(pi|qi)>>25])) + if(!(shift=MLOOP_2[(pi|qi)>>19])) + shift=MLOOP_3[(pi|qi)>>16]; + + /* pi,qi normalized collectively, both tracked using qexp */ + + if(m&1){ + /* odd order filter; slightly assymetric */ + /* the last coefficient */ + qi=(qi>>shift)*labs(ilsp[j-1]-wi); + pi=(pi>>shift)<<14; + qexp+=shift; + + if(!(shift=MLOOP_1[(pi|qi)>>25])) + if(!(shift=MLOOP_2[(pi|qi)>>19])) + shift=MLOOP_3[(pi|qi)>>16]; + + pi>>=shift; + qi>>=shift; + qexp+=shift-14*((m+1)>>1); + + pi=((pi*pi)>>16); + qi=((qi*qi)>>16); + qexp=qexp*2+m; + + pi*=(1<<14)-((wi*wi)>>14); + qi+=pi>>14; + + }else{ + /* even order filter; still symmetric */ + + /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't + worth tracking step by step */ + + pi>>=shift; + qi>>=shift; + qexp+=shift-7*m; + + pi=((pi*pi)>>16); + qi=((qi*qi)>>16); + qexp=qexp*2+m; + + pi*=(1<<14)-wi; + qi*=(1<<14)+wi; + qi=(qi+pi)>>14; + + } + + + /* we've let the normalization drift because it wasn't important; + however, for the lookup, things must be normalized again. We + need at most one right shift or a number of left shifts */ + + if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */ + qi>>=1; qexp++; + }else + while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/ + qi<<=1; qexp--; + } + +#endif + + amp=vorbis_fromdBlook_i(ampi* /* n.4 */ + vorbis_invsqlook_i(qi,qexp)- + /* m.8, m+n<=8 */ + ampoffseti); /* 8.12[0] */ + +#ifdef _LOW_ACCURACY_ + amp>>=9; +#endif + curve[i]= MULT31_SHIFT15(curve[i],amp); + while(map[++i]==k) curve[i]= MULT31_SHIFT15(curve[i],amp); + } +} + +/*************** vorbis decode glue ************/ + +static void floor0_free_info(vorbis_info_floor *i){ + vorbis_info_floor0 *info=(vorbis_info_floor0 *)i; + if(info){ + memset(info,0,sizeof(*info)); + _ogg_free(info); + } +} + +static void floor0_free_look(vorbis_look_floor *i){ + vorbis_look_floor0 *look=(vorbis_look_floor0 *)i; + if(look){ + + if(look->linearmap)_ogg_free(look->linearmap); + if(look->lsp_look)_ogg_free(look->lsp_look); + memset(look,0,sizeof(*look)); + _ogg_free(look); + } +} + +static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){ + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + int j; + + vorbis_info_floor0 *info=(vorbis_info_floor0 *)_ogg_malloc(sizeof(*info)); + info->order=oggpack_read(opb,8); + info->rate=oggpack_read(opb,16); + info->barkmap=oggpack_read(opb,16); + info->ampbits=oggpack_read(opb,6); + info->ampdB=oggpack_read(opb,8); + info->numbooks=oggpack_read(opb,4)+1; + + if(info->order<1)goto err_out; + if(info->rate<1)goto err_out; + if(info->barkmap<1)goto err_out; + if(info->numbooks<1)goto err_out; + + for(j=0;jnumbooks;j++){ + info->books[j]=oggpack_read(opb,8); + if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out; + if(ci->book_param[info->books[j]]->maptype==0)goto err_out; + if(ci->book_param[info->books[j]]->dim<1)goto err_out; + } + return(info); + + err_out: + floor0_free_info(info); + return(NULL); +} + +/* initialize Bark scale and normalization lookups. We could do this + with static tables, but Vorbis allows a number of possible + combinations, so it's best to do it computationally. + + The below is authoritative in terms of defining scale mapping. + Note that the scale depends on the sampling rate as well as the + linear block and mapping sizes */ + +static vorbis_look_floor *floor0_look (vorbis_dsp_state *vd,vorbis_info_mode *mi, + vorbis_info_floor *i){ + int j; + vorbis_info *vi=vd->vi; + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + vorbis_info_floor0 *info=(vorbis_info_floor0 *)i; + vorbis_look_floor0 *look=(vorbis_look_floor0 *)_ogg_calloc(1,sizeof(*look)); + look->m=info->order; + look->n=ci->blocksizes[mi->blockflag]/2; + look->ln=info->barkmap; + look->vi=info; + + /* the mapping from a linear scale to a smaller bark scale is + straightforward. We do *not* make sure that the linear mapping + does not skip bark-scale bins; the decoder simply skips them and + the encoder may do what it wishes in filling them. They're + necessary in some mapping combinations to keep the scale spacing + accurate */ + look->linearmap=(int *)_ogg_malloc((look->n+1)*sizeof(*look->linearmap)); + for(j=0;jn;j++){ + + int val=(look->ln* + ((toBARK(info->rate/2*j/look->n)<<11)/toBARK(info->rate/2)))>>11; + + if(val>=look->ln)val=look->ln-1; /* guard against the approximation */ + look->linearmap[j]=val; + } + look->linearmap[j]=-1; + + look->lsp_look=(ogg_int32_t *)_ogg_malloc(look->ln*sizeof(*look->lsp_look)); + for(j=0;jln;j++) + look->lsp_look[j]=vorbis_coslook2_i(0x10000*j/look->ln); + + return look; +} + +static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){ + vorbis_look_floor0 *look=(vorbis_look_floor0 *)i; + vorbis_info_floor0 *info=look->vi; + int j,k; + + int ampraw=oggpack_read(&vb->opb,info->ampbits); + if(ampraw>0){ /* also handles the -1 out of data case */ + long maxval=(1<ampbits)-1; + int amp=((ampraw*info->ampdB)<<4)/maxval; + int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks)); + + if(booknum!=-1 && booknumnumbooks){ /* be paranoid */ + codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup; + codebook *b=ci->fullbooks+info->books[booknum]; + ogg_int32_t last=0; + ogg_int32_t *lsp=(ogg_int32_t *)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+1)); + + if(vorbis_book_decodev_set(b,lsp,&vb->opb,look->m,-24)==-1)goto eop; + for(j=0;jm;){ + for(k=0;jm && kdim;k++,j++)lsp[j]+=last; + last=lsp[j-1]; + } + + lsp[look->m]=amp; + return(lsp); + } + } + eop: + return(NULL); +} + +static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i, + void *memo,ogg_int32_t *out){ + vorbis_look_floor0 *look=(vorbis_look_floor0 *)i; + vorbis_info_floor0 *info=look->vi; + + if(memo){ + ogg_int32_t *lsp=(ogg_int32_t *)memo; + ogg_int32_t amp=lsp[look->m]; + + /* take the coefficients back to a spectral envelope curve */ + vorbis_lsp_to_curve(out,look->linearmap,look->n,look->ln, + lsp,look->m,amp,info->ampdB,look->lsp_look); + return(1); + } + memset(out,0,sizeof(*out)*look->n); + return(0); +} + +/* export hooks */ +vorbis_func_floor floor0_exportbundle={ + &floor0_unpack,&floor0_look,&floor0_free_info, + &floor0_free_look,&floor0_inverse1,&floor0_inverse2 +}; + + diff --git a/libs/tremor/floor1.c b/libs/tremor/floor1.c new file mode 100644 index 0000000..e63ae9f --- /dev/null +++ b/libs/tremor/floor1.c @@ -0,0 +1,460 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: floor backend 1 implementation + + ********************************************************************/ + +#include +#include +#include +#include +#include "ivorbiscodec.h" +#include "codec_internal.h" +#include "registry.h" +#include "codebook.h" +#include "misc.h" +#include "block.h" + +#define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */ + +typedef struct { + int forward_index[VIF_POSIT+2]; + + int hineighbor[VIF_POSIT]; + int loneighbor[VIF_POSIT]; + int posts; + + int n; + int quant_q; + vorbis_info_floor1 *vi; + +} vorbis_look_floor1; + +/***********************************************/ + +static void floor1_free_info(vorbis_info_floor *i){ + vorbis_info_floor1 *info=(vorbis_info_floor1 *)i; + if(info){ + memset(info,0,sizeof(*info)); + _ogg_free(info); + } +} + +static void floor1_free_look(vorbis_look_floor *i){ + vorbis_look_floor1 *look=(vorbis_look_floor1 *)i; + if(look){ + memset(look,0,sizeof(*look)); + _ogg_free(look); + } +} + +static int ilog(unsigned int v){ + int ret=0; + while(v){ + ret++; + v>>=1; + } + return(ret); +} + +static int icomp(const void *a,const void *b){ + return(**(int **)a-**(int **)b); +} + +static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){ + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + int j,k,count=0,maxclass=-1,rangebits; + + vorbis_info_floor1 *info=(vorbis_info_floor1 *)_ogg_calloc(1,sizeof(*info)); + /* read partitions */ + info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */ + for(j=0;jpartitions;j++){ + info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */ + if(info->partitionclass[j]<0)goto err_out; + if(maxclasspartitionclass[j])maxclass=info->partitionclass[j]; + } + + /* read partition classes */ + for(j=0;jclass_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */ + info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */ + if(info->class_subs[j]<0) + goto err_out; + if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8); + if(info->class_book[j]<0 || info->class_book[j]>=ci->books) + goto err_out; + for(k=0;k<(1<class_subs[j]);k++){ + info->class_subbook[j][k]=oggpack_read(opb,8)-1; + if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books) + goto err_out; + } + } + + /* read the post list */ + info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */ + rangebits=oggpack_read(opb,4); + if(rangebits<0)goto err_out; + + for(j=0,k=0;jpartitions;j++){ + count+=info->class_dim[info->partitionclass[j]]; + if(count>VIF_POSIT)goto err_out; + for(;kpostlist[k+2]=oggpack_read(opb,rangebits); + if(t<0 || t>=(1<postlist[0]=0; + info->postlist[1]=1<postlist+j; + qsort(sortpointer,count+2,sizeof(*sortpointer),icomp); + + for(j=1;jvi=info; + look->n=info->postlist[1]; + + /* we drop each position value in-between already decoded values, + and use linear interpolation to predict each new value past the + edges. The positions are read in the order of the position + list... we precompute the bounding positions in the lookup. Of + course, the neighbors can change (if a position is declined), but + this is an initial mapping */ + + for(i=0;ipartitions;i++)n+=info->class_dim[info->partitionclass[i]]; + n+=2; + look->posts=n; + + /* also store a sorted position index */ + for(i=0;ipostlist+i; + qsort(sortpointer,n,sizeof(*sortpointer),icomp); + + /* points from sort order back to range number */ + for(i=0;iforward_index[i]=sortpointer[i]-info->postlist; + + /* quantize values to multiplier spec */ + switch(info->mult){ + case 1: /* 1024 -> 256 */ + look->quant_q=256; + break; + case 2: /* 1024 -> 128 */ + look->quant_q=128; + break; + case 3: /* 1024 -> 86 */ + look->quant_q=86; + break; + case 4: /* 1024 -> 64 */ + look->quant_q=64; + break; + } + + /* discover our neighbors for decode where we don't use fit flags + (that would push the neighbors outward) */ + for(i=0;in; + int currentx=info->postlist[i+2]; + for(j=0;jpostlist[j]; + if(x>lx && xcurrentx){ + hi=j; + hx=x; + } + } + look->loneighbor[i]=lo; + look->hineighbor[i]=hi; + } + + return(look); +} + +static int render_point(int x0,int x1,int y0,int y1,int x){ + y0&=0x7fff; /* mask off flag */ + y1&=0x7fff; + + { + int dy=y1-y0; + int adx=x1-x0; + int ady=abs(dy); + int err=ady*(x-x0); + + int off=err/adx; + if(dy<0)return(y0-off); + return(y0+off); + } +} + +#ifdef _LOW_ACCURACY_ +# define XdB(n) ((((n)>>8)+1)>>1) +#else +# define XdB(n) (n) +#endif + +static const ogg_int32_t FLOOR_fromdB_LOOKUP[256]={ + XdB(0x000000e5), XdB(0x000000f4), XdB(0x00000103), XdB(0x00000114), + XdB(0x00000126), XdB(0x00000139), XdB(0x0000014e), XdB(0x00000163), + XdB(0x0000017a), XdB(0x00000193), XdB(0x000001ad), XdB(0x000001c9), + XdB(0x000001e7), XdB(0x00000206), XdB(0x00000228), XdB(0x0000024c), + XdB(0x00000272), XdB(0x0000029b), XdB(0x000002c6), XdB(0x000002f4), + XdB(0x00000326), XdB(0x0000035a), XdB(0x00000392), XdB(0x000003cd), + XdB(0x0000040c), XdB(0x00000450), XdB(0x00000497), XdB(0x000004e4), + XdB(0x00000535), XdB(0x0000058c), XdB(0x000005e8), XdB(0x0000064a), + XdB(0x000006b3), XdB(0x00000722), XdB(0x00000799), XdB(0x00000818), + XdB(0x0000089e), XdB(0x0000092e), XdB(0x000009c6), XdB(0x00000a69), + XdB(0x00000b16), XdB(0x00000bcf), XdB(0x00000c93), XdB(0x00000d64), + XdB(0x00000e43), XdB(0x00000f30), XdB(0x0000102d), XdB(0x0000113a), + XdB(0x00001258), XdB(0x0000138a), XdB(0x000014cf), XdB(0x00001629), + XdB(0x0000179a), XdB(0x00001922), XdB(0x00001ac4), XdB(0x00001c82), + XdB(0x00001e5c), XdB(0x00002055), XdB(0x0000226f), XdB(0x000024ac), + XdB(0x0000270e), XdB(0x00002997), XdB(0x00002c4b), XdB(0x00002f2c), + XdB(0x0000323d), XdB(0x00003581), XdB(0x000038fb), XdB(0x00003caf), + XdB(0x000040a0), XdB(0x000044d3), XdB(0x0000494c), XdB(0x00004e10), + XdB(0x00005323), XdB(0x0000588a), XdB(0x00005e4b), XdB(0x0000646b), + XdB(0x00006af2), XdB(0x000071e5), XdB(0x0000794c), XdB(0x0000812e), + XdB(0x00008993), XdB(0x00009283), XdB(0x00009c09), XdB(0x0000a62d), + XdB(0x0000b0f9), XdB(0x0000bc79), XdB(0x0000c8b9), XdB(0x0000d5c4), + XdB(0x0000e3a9), XdB(0x0000f274), XdB(0x00010235), XdB(0x000112fd), + XdB(0x000124dc), XdB(0x000137e4), XdB(0x00014c29), XdB(0x000161bf), + XdB(0x000178bc), XdB(0x00019137), XdB(0x0001ab4a), XdB(0x0001c70e), + XdB(0x0001e4a1), XdB(0x0002041f), XdB(0x000225aa), XdB(0x00024962), + XdB(0x00026f6d), XdB(0x000297f0), XdB(0x0002c316), XdB(0x0002f109), + XdB(0x000321f9), XdB(0x00035616), XdB(0x00038d97), XdB(0x0003c8b4), + XdB(0x000407a7), XdB(0x00044ab2), XdB(0x00049218), XdB(0x0004de23), + XdB(0x00052f1e), XdB(0x0005855c), XdB(0x0005e135), XdB(0x00064306), + XdB(0x0006ab33), XdB(0x00071a24), XdB(0x0007904b), XdB(0x00080e20), + XdB(0x00089422), XdB(0x000922da), XdB(0x0009bad8), XdB(0x000a5cb6), + XdB(0x000b091a), XdB(0x000bc0b1), XdB(0x000c8436), XdB(0x000d5471), + XdB(0x000e3233), XdB(0x000f1e5f), XdB(0x001019e4), XdB(0x001125c1), + XdB(0x00124306), XdB(0x001372d5), XdB(0x0014b663), XdB(0x00160ef7), + XdB(0x00177df0), XdB(0x001904c1), XdB(0x001aa4f9), XdB(0x001c603d), + XdB(0x001e384f), XdB(0x00202f0f), XdB(0x0022467a), XdB(0x002480b1), + XdB(0x0026dff7), XdB(0x002966b3), XdB(0x002c1776), XdB(0x002ef4fc), + XdB(0x0032022d), XdB(0x00354222), XdB(0x0038b828), XdB(0x003c67c2), + XdB(0x004054ae), XdB(0x004482e8), XdB(0x0048f6af), XdB(0x004db488), + XdB(0x0052c142), XdB(0x005821ff), XdB(0x005ddc33), XdB(0x0063f5b0), + XdB(0x006a74a7), XdB(0x00715faf), XdB(0x0078bdce), XdB(0x0080967f), + XdB(0x0088f1ba), XdB(0x0091d7f9), XdB(0x009b5247), XdB(0x00a56a41), + XdB(0x00b02a27), XdB(0x00bb9ce2), XdB(0x00c7ce12), XdB(0x00d4ca17), + XdB(0x00e29e20), XdB(0x00f15835), XdB(0x0101074b), XdB(0x0111bb4e), + XdB(0x01238531), XdB(0x01367704), XdB(0x014aa402), XdB(0x016020a7), + XdB(0x017702c3), XdB(0x018f6190), XdB(0x01a955cb), XdB(0x01c4f9cf), + XdB(0x01e269a8), XdB(0x0201c33b), XdB(0x0223265a), XdB(0x0246b4ea), + XdB(0x026c9302), XdB(0x0294e716), XdB(0x02bfda13), XdB(0x02ed9793), + XdB(0x031e4e09), XdB(0x03522ee4), XdB(0x03896ed0), XdB(0x03c445e2), + XdB(0x0402efd6), XdB(0x0445ac4b), XdB(0x048cbefc), XdB(0x04d87013), + XdB(0x05290c67), XdB(0x057ee5ca), XdB(0x05da5364), XdB(0x063bb204), + XdB(0x06a36485), XdB(0x0711d42b), XdB(0x0787710e), XdB(0x0804b299), + XdB(0x088a17ef), XdB(0x0918287e), XdB(0x09af747c), XdB(0x0a50957e), + XdB(0x0afc2f19), XdB(0x0bb2ef7f), XdB(0x0c759034), XdB(0x0d44d6ca), + XdB(0x0e2195bc), XdB(0x0f0cad0d), XdB(0x10070b62), XdB(0x1111aeea), + XdB(0x122da66c), XdB(0x135c120f), XdB(0x149e24d9), XdB(0x15f525b1), + XdB(0x176270e3), XdB(0x18e7794b), XdB(0x1a85c9ae), XdB(0x1c3f06d1), + XdB(0x1e14f07d), XdB(0x200963d7), XdB(0x221e5ccd), XdB(0x2455f870), + XdB(0x26b2770b), XdB(0x29363e2b), XdB(0x2be3db5c), XdB(0x2ebe06b6), + XdB(0x31c7a55b), XdB(0x3503ccd4), XdB(0x3875c5aa), XdB(0x3c210f44), + XdB(0x4009632b), XdB(0x4432b8cf), XdB(0x48a149bc), XdB(0x4d59959e), + XdB(0x52606733), XdB(0x57bad899), XdB(0x5d6e593a), XdB(0x6380b298), + XdB(0x69f80e9a), XdB(0x70dafda8), XdB(0x78307d76), XdB(0x7fffffff), +}; + +static void render_line(int n, int x0,int x1,int y0,int y1,ogg_int32_t *d){ + int dy=y1-y0; + int adx=x1-x0; + int ady=abs(dy); + int base=dy/adx; + int sy=(dy<0?base-1:base+1); + int x=x0; + int y=y0; + int err=0; + + if(n>x1)n=x1; + ady-=abs(base*adx); + + if(x=adx){ + err-=adx; + y+=sy; + }else{ + y+=base; + } + d[x]= MULT31_SHIFT15(d[x],FLOOR_fromdB_LOOKUP[y]); + } +} + +static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){ + vorbis_look_floor1 *look=(vorbis_look_floor1 *)in; + vorbis_info_floor1 *info=look->vi; + codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup; + + int i,j,k; + codebook *books=ci->fullbooks; + + /* unpack wrapped/predicted values from stream */ + if(oggpack_read(&vb->opb,1)==1){ + int *fit_value=(int *)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value)); + + fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1)); + fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1)); + + /* partition by partition */ + /* partition by partition */ + for(i=0,j=2;ipartitions;i++){ + int classv=info->partitionclass[i]; + int cdim=info->class_dim[classv]; + int csubbits=info->class_subs[classv]; + int csub=1<class_book[classv],&vb->opb); + + if(cval==-1)goto eop; + } + + for(k=0;kclass_subbook[classv][cval&(csub-1)]; + cval>>=csubbits; + if(book>=0){ + if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1) + goto eop; + }else{ + fit_value[j+k]=0; + } + } + j+=cdim; + } + + /* unwrap positive values and reconsitute via linear interpolation */ + for(i=2;iposts;i++){ + int predicted=render_point(info->postlist[look->loneighbor[i-2]], + info->postlist[look->hineighbor[i-2]], + fit_value[look->loneighbor[i-2]], + fit_value[look->hineighbor[i-2]], + info->postlist[i]); + int hiroom=look->quant_q-predicted; + int loroom=predicted; + int room=(hiroom=room){ + if(hiroom>loroom){ + val = val-loroom; + }else{ + val = -1-(val-hiroom); + } + }else{ + if(val&1){ + val= -((val+1)>>1); + }else{ + val>>=1; + } + } + + fit_value[i]=(val+predicted)&0x7fff;; + fit_value[look->loneighbor[i-2]]&=0x7fff; + fit_value[look->hineighbor[i-2]]&=0x7fff; + + }else{ + fit_value[i]=predicted|0x8000; + } + + } + + return(fit_value); + } + eop: + return(NULL); +} + +static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo, + ogg_int32_t *out){ + vorbis_look_floor1 *look=(vorbis_look_floor1 *)in; + vorbis_info_floor1 *info=look->vi; + + codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup; + int n=ci->blocksizes[vb->W]/2; + int j; + + if(memo){ + /* render the lines */ + int *fit_value=(int *)memo; + int hx=0; + int lx=0; + int ly=fit_value[0]*info->mult; + /* guard lookup against out-of-range values */ + ly=(ly<0?0:ly>255?255:ly); + + for(j=1;jposts;j++){ + int current=look->forward_index[j]; + int hy=fit_value[current]&0x7fff; + if(hy==fit_value[current]){ + + hx=info->postlist[current]; + hy*=info->mult; + /* guard lookup against out-of-range values */ + hy=(hy<0?0:hy>255?255:hy); + + render_line(n,lx,hx,ly,hy,out); + + lx=hx; + ly=hy; + } + } + for(j=hx;j header packets + + ********************************************************************/ + +/* general handling of the header and the vorbis_info structure (and + substructures) */ + +#include +#include +#include +#include +#include +#include "ivorbiscodec.h" +#include "codec_internal.h" +#include "codebook.h" +#include "registry.h" +#include "window.h" +#include "misc.h" + +/* helpers */ +static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){ + while(bytes--){ + *buf++=oggpack_read(o,8); + } +} + +void vorbis_comment_init(vorbis_comment *vc){ + memset(vc,0,sizeof(*vc)); +} + +/* This is more or less the same as strncasecmp - but that doesn't exist + * everywhere, and this is a fairly trivial function, so we include it */ +static int tagcompare(const char *s1, const char *s2, int n){ + int c=0; + while(c < n){ + if(toupper(s1[c]) != toupper(s2[c])) + return !0; + c++; + } + return 0; +} + +char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){ + long i; + int found = 0; + int taglen = strlen(tag)+1; /* +1 for the = we append */ + char *fulltag = (char *)alloca(taglen+ 1); + + strcpy(fulltag, tag); + strcat(fulltag, "="); + + for(i=0;icomments;i++){ + if(!tagcompare(vc->user_comments[i], fulltag, taglen)){ + if(count == found) + /* We return a pointer to the data, not a copy */ + return vc->user_comments[i] + taglen; + else + found++; + } + } + return NULL; /* didn't find anything */ +} + +int vorbis_comment_query_count(vorbis_comment *vc, char *tag){ + int i,count=0; + int taglen = strlen(tag)+1; /* +1 for the = we append */ + char *fulltag = (char *)alloca(taglen+1); + strcpy(fulltag,tag); + strcat(fulltag, "="); + + for(i=0;icomments;i++){ + if(!tagcompare(vc->user_comments[i], fulltag, taglen)) + count++; + } + + return count; +} + +void vorbis_comment_clear(vorbis_comment *vc){ + if(vc){ + long i; + if(vc->user_comments){ + for(i=0;icomments;i++) + if(vc->user_comments[i])_ogg_free(vc->user_comments[i]); + _ogg_free(vc->user_comments); + } + if(vc->comment_lengths)_ogg_free(vc->comment_lengths); + if(vc->vendor)_ogg_free(vc->vendor); + memset(vc,0,sizeof(*vc)); + } +} + +/* blocksize 0 is guaranteed to be short, 1 is guarantted to be long. + They may be equal, but short will never ge greater than long */ +int vorbis_info_blocksize(vorbis_info *vi,int zo){ + codec_setup_info *ci = (codec_setup_info *)vi->codec_setup; + return ci ? ci->blocksizes[zo] : -1; +} + +/* used by synthesis, which has a full, alloced vi */ +void vorbis_info_init(vorbis_info *vi){ + memset(vi,0,sizeof(*vi)); + vi->codec_setup=(codec_setup_info *)_ogg_calloc(1,sizeof(codec_setup_info)); +} + +void vorbis_info_clear(vorbis_info *vi){ + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + int i; + + if(ci){ + + for(i=0;imodes;i++) + if(ci->mode_param[i])_ogg_free(ci->mode_param[i]); + + for(i=0;imaps;i++) /* unpack does the range checking */ + if(ci->map_param[i]) + _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]); + + for(i=0;ifloors;i++) /* unpack does the range checking */ + if(ci->floor_param[i]) + _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]); + + for(i=0;iresidues;i++) /* unpack does the range checking */ + if(ci->residue_param[i]) + _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]); + + for(i=0;ibooks;i++){ + if(ci->book_param[i]){ + /* knows if the book was not alloced */ + vorbis_staticbook_destroy(ci->book_param[i]); + } + if(ci->fullbooks) + vorbis_book_clear(ci->fullbooks+i); + } + if(ci->fullbooks) + _ogg_free(ci->fullbooks); + + _ogg_free(ci); + } + + memset(vi,0,sizeof(*vi)); +} + +/* Header packing/unpacking ********************************************/ + +static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){ + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + if(!ci)return(OV_EFAULT); + + vi->version=oggpack_read(opb,32); + if(vi->version!=0)return(OV_EVERSION); + + vi->channels=oggpack_read(opb,8); + vi->rate=oggpack_read(opb,32); + + vi->bitrate_upper=oggpack_read(opb,32); + vi->bitrate_nominal=oggpack_read(opb,32); + vi->bitrate_lower=oggpack_read(opb,32); + + ci->blocksizes[0]=1<blocksizes[1]=1<rate<1)goto err_out; + if(vi->channels<1)goto err_out; + if(ci->blocksizes[0]<64)goto err_out; + if(ci->blocksizes[1]blocksizes[0])goto err_out; + if(ci->blocksizes[1]>8192)goto err_out; + + if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */ + + return(0); + err_out: + vorbis_info_clear(vi); + return(OV_EBADHEADER); +} + +static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){ + int i; + int vendorlen; + vendorlen=oggpack_read(opb,32); + if(vendorlen<0)goto err_out; + if(vendorlen>opb->storage-oggpack_bytes(opb))goto err_out; + vc->vendor=(char *)_ogg_calloc(vendorlen+1,1); + if(vc->vendor==NULL)goto err_out; + _v_readstring(opb,vc->vendor,vendorlen); + i=oggpack_read(opb,32); + if(i<0||i>=INT_MAX||i>(opb->storage-oggpack_bytes(opb))>>2)goto err_out; + vc->user_comments=(char **)_ogg_calloc(i+1,sizeof(*vc->user_comments)); + vc->comment_lengths=(int *)_ogg_calloc(i+1, sizeof(*vc->comment_lengths)); + if(vc->user_comments==NULL||vc->comment_lengths==NULL)goto err_out; + vc->comments=i; + + for(i=0;icomments;i++){ + int len=oggpack_read(opb,32); + if(len<0||len>opb->storage-oggpack_bytes(opb))goto err_out; + vc->comment_lengths[i]=len; + vc->user_comments[i]=(char *)_ogg_calloc(len+1,1); + if(vc->user_comments[i]==NULL){ + vc->comments=i; + goto err_out; + } + _v_readstring(opb,vc->user_comments[i],len); + } + if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */ + + return(0); + err_out: + vorbis_comment_clear(vc); + return(OV_EBADHEADER); +} + +/* all of the real encoding details are here. The modes, books, + everything */ +static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){ + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + int i; + if(!ci)return(OV_EFAULT); + + /* codebooks */ + ci->books=oggpack_read(opb,8)+1; + if(ci->books<=0)goto err_out; + for(i=0;ibooks;i++){ + ci->book_param[i]=vorbis_staticbook_unpack(opb); + if(!ci->book_param[i])goto err_out; + } + + /* time backend settings */ + ci->times=oggpack_read(opb,6)+1; + if(ci->times<=0)goto err_out; + for(i=0;itimes;i++){ + ci->time_type[i]=oggpack_read(opb,16); + if(ci->time_type[i]<0 || ci->time_type[i]>=VI_TIMEB)goto err_out; + /* ci->time_param[i]=_time_P[ci->time_type[i]]->unpack(vi,opb); + Vorbis I has no time backend */ + /*if(!ci->time_param[i])goto err_out;*/ + } + + /* floor backend settings */ + ci->floors=oggpack_read(opb,6)+1; + if(ci->floors<=0)goto err_out; + for(i=0;ifloors;i++){ + ci->floor_type[i]=oggpack_read(opb,16); + if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out; + ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb); + if(!ci->floor_param[i])goto err_out; + } + + /* residue backend settings */ + ci->residues=oggpack_read(opb,6)+1; + if(ci->residues<=0)goto err_out; + for(i=0;iresidues;i++){ + ci->residue_type[i]=oggpack_read(opb,16); + if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out; + ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb); + if(!ci->residue_param[i])goto err_out; + } + + /* map backend settings */ + ci->maps=oggpack_read(opb,6)+1; + if(ci->maps<=0)goto err_out; + for(i=0;imaps;i++){ + ci->map_type[i]=oggpack_read(opb,16); + if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out; + ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb); + if(!ci->map_param[i])goto err_out; + } + + /* mode settings */ + ci->modes=oggpack_read(opb,6)+1; + if(ci->modes<=0)goto err_out; + for(i=0;imodes;i++){ + ci->mode_param[i]=(vorbis_info_mode *)_ogg_calloc(1,sizeof(*ci->mode_param[i])); + ci->mode_param[i]->blockflag=oggpack_read(opb,1); + ci->mode_param[i]->windowtype=oggpack_read(opb,16); + ci->mode_param[i]->transformtype=oggpack_read(opb,16); + ci->mode_param[i]->mapping=oggpack_read(opb,8); + + if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out; + if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out; + if(ci->mode_param[i]->mapping>=ci->maps)goto err_out; + if(ci->mode_param[i]->mapping<0)goto err_out; + } + + if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */ + + return(0); + err_out: + vorbis_info_clear(vi); + return(OV_EBADHEADER); +} + +/* Is this packet a vorbis ID header? */ +int vorbis_synthesis_idheader(ogg_packet *op){ + oggpack_buffer opb; + char buffer[6]; + + if(op){ + oggpack_readinit(&opb,op->packet,op->bytes); + + if(!op->b_o_s) + return(0); /* Not the initial packet */ + + if(oggpack_read(&opb,8) != 1) + return 0; /* not an ID header */ + + memset(buffer,0,6); + _v_readstring(&opb,buffer,6); + if(memcmp(buffer,"vorbis",6)) + return 0; /* not vorbis */ + + return 1; + } + + return 0; +} + +/* The Vorbis header is in three packets; the initial small packet in + the first page that identifies basic parameters, a second packet + with bitstream comments and a third packet that holds the + codebook. */ + +int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){ + oggpack_buffer opb; + + if(op){ + oggpack_readinit(&opb,op->packet,op->bytes); + + /* Which of the three types of header is this? */ + /* Also verify header-ness, vorbis */ + { + char buffer[6]; + int packtype=oggpack_read(&opb,8); + memset(buffer,0,6); + _v_readstring(&opb,buffer,6); + if(memcmp(buffer,"vorbis",6)){ + /* not a vorbis header */ + return(OV_ENOTVORBIS); + } + switch(packtype){ + case 0x01: /* least significant *bit* is read first */ + if(!op->b_o_s){ + /* Not the initial packet */ + return(OV_EBADHEADER); + } + if(vi->rate!=0){ + /* previously initialized info header */ + return(OV_EBADHEADER); + } + + return(_vorbis_unpack_info(vi,&opb)); + + case 0x03: /* least significant *bit* is read first */ + if(vi->rate==0){ + /* um... we didn't get the initial header */ + return(OV_EBADHEADER); + } + + return(_vorbis_unpack_comment(vc,&opb)); + + case 0x05: /* least significant *bit* is read first */ + if(vi->rate==0 || vc->vendor==NULL){ + /* um... we didn;t get the initial header or comments yet */ + return(OV_EBADHEADER); + } + + return(_vorbis_unpack_books(vi,&opb)); + + default: + /* Not a valid vorbis header type */ + return(OV_EBADHEADER); + break; + } + } + } + return(OV_EBADHEADER); +} + diff --git a/libs/tremor/iseeking_example.dontcompile b/libs/tremor/iseeking_example.dontcompile new file mode 100644 index 0000000..dc971ba --- /dev/null +++ b/libs/tremor/iseeking_example.dontcompile @@ -0,0 +1,265 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2009 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: illustrate seeking, and test it too + last mod: $Id$ + + ********************************************************************/ + +#include +#include +#include "ivorbiscodec.h" +#include "ivorbisfile.h" + +#ifdef _WIN32 /* We need the following two to set stdin/stdout to binary */ +# include +# include +#endif + +void _verify(OggVorbis_File *ov, + ogg_int64_t val, + ogg_int64_t pcmval, + ogg_int64_t timeval, + ogg_int64_t pcmlength, + char *bigassbuffer){ + int j; + long bread; + char buffer[4096]; + int dummy; + ogg_int64_t pos; + + /* verify the raw position, the pcm position and position decode */ + if(val!=-1 && ov_raw_tell(ov)pcmval){ + fprintf(stderr,"pcm position out of tolerance: requested %ld, got %ld\n", + (long)pcmval,(long)ov_pcm_tell(ov)); + exit(1); + } + if(timeval!=-1 && ov_time_tell(ov)>timeval){ + fprintf(stderr,"time position out of tolerance: requested %ld, got %ld\n", + (long)timeval,(long)ov_time_tell(ov)); + exit(1); + } + pos=ov_pcm_tell(ov); + if(pos<0 || pos>pcmlength){ + fprintf(stderr,"pcm position out of bounds: got %ld\n",(long)pos); + exit(1); + } + bread=ov_read(ov,buffer,4096,&dummy); + if(bigassbuffer){ + for(j=0;jchannels!=2){ + fprintf(stderr,"Sorry; right now seeking_test can only use Vorbis files\n" + "that are entirely stereo.\n\n"); + exit(1); + } + } + + /* because we want to do sample-level verification that the seek + does what it claimed, decode the entire file into memory */ + pcmlength=ov_pcm_total(&ov,-1); + timelength=ov_time_total(&ov,-1); + bigassbuffer=malloc(pcmlength*4); /* w00t */ + if(bigassbuffer){ + i=0; + while(ival+1){ + fprintf(stderr,"Declared position didn't perfectly match request: %ld != %ld\n", + (long)val,(long)ov_time_tell(&ov)); + exit(1); + } + + _verify(&ov,-1,-1,val,pcmlength,bigassbuffer); + + } + } + + fprintf(stderr,"\r \nOK.\n\n"); + + + }else{ + fprintf(stderr,"Standard input was not seekable.\n"); + } + + ov_clear(&ov); + return 0; +} + + + + + + + + + + + + + diff --git a/libs/tremor/ivorbiscodec.h b/libs/tremor/ivorbiscodec.h new file mode 100644 index 0000000..17eab58 --- /dev/null +++ b/libs/tremor/ivorbiscodec.h @@ -0,0 +1,204 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: libvorbis codec headers + + ********************************************************************/ + +#ifndef _vorbis_codec_h_ +#define _vorbis_codec_h_ + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#include + +typedef struct vorbis_info{ + int version; + int channels; + long rate; + + /* The below bitrate declarations are *hints*. + Combinations of the three values carry the following implications: + + all three set to the same value: + implies a fixed rate bitstream + only nominal set: + implies a VBR stream that averages the nominal bitrate. No hard + upper/lower limit + upper and or lower set: + implies a VBR bitstream that obeys the bitrate limits. nominal + may also be set to give a nominal rate. + none set: + the coder does not care to speculate. + */ + + long bitrate_upper; + long bitrate_nominal; + long bitrate_lower; + long bitrate_window; + + void *codec_setup; +} vorbis_info; + +/* vorbis_dsp_state buffers the current vorbis audio + analysis/synthesis state. The DSP state belongs to a specific + logical bitstream ****************************************************/ +typedef struct vorbis_dsp_state{ + int analysisp; + vorbis_info *vi; + + ogg_int32_t **pcm; + ogg_int32_t **pcmret; + int pcm_storage; + int pcm_current; + int pcm_returned; + + int preextrapolate; + int eofflag; + + long lW; + long W; + long nW; + long centerW; + + ogg_int64_t granulepos; + ogg_int64_t sequence; + + void *backend_state; +} vorbis_dsp_state; + +typedef struct vorbis_block{ + /* necessary stream state for linking to the framing abstraction */ + ogg_int32_t **pcm; /* this is a pointer into local storage */ + oggpack_buffer opb; + + long lW; + long W; + long nW; + int pcmend; + int mode; + + int eofflag; + ogg_int64_t granulepos; + ogg_int64_t sequence; + vorbis_dsp_state *vd; /* For read-only access of configuration */ + + /* local storage to avoid remallocing; it's up to the mapping to + structure it */ + void *localstore; + long localtop; + long localalloc; + long totaluse; + struct alloc_chain *reap; + +} vorbis_block; + +/* vorbis_block is a single block of data to be processed as part of +the analysis/synthesis stream; it belongs to a specific logical +bitstream, but is independant from other vorbis_blocks belonging to +that logical bitstream. *************************************************/ + +struct alloc_chain{ + void *ptr; + struct alloc_chain *next; +}; + +/* vorbis_info contains all the setup information specific to the + specific compression/decompression mode in progress (eg, + psychoacoustic settings, channel setup, options, codebook + etc). vorbis_info and substructures are in backends.h. +*********************************************************************/ + +/* the comments are not part of vorbis_info so that vorbis_info can be + static storage */ +typedef struct vorbis_comment{ + /* unlimited user comment fields. libvorbis writes 'libvorbis' + whatever vendor is set to in encode */ + char **user_comments; + int *comment_lengths; + int comments; + char *vendor; + +} vorbis_comment; + + +/* libvorbis encodes in two abstraction layers; first we perform DSP + and produce a packet (see docs/analysis.txt). The packet is then + coded into a framed OggSquish bitstream by the second layer (see + docs/framing.txt). Decode is the reverse process; we sync/frame + the bitstream and extract individual packets, then decode the + packet back into PCM audio. + + The extra framing/packetizing is used in streaming formats, such as + files. Over the net (such as with UDP), the framing and + packetization aren't necessary as they're provided by the transport + and the streaming layer is not used */ + +/* Vorbis PRIMITIVES: general ***************************************/ + +extern void vorbis_info_init(vorbis_info *vi); +extern void vorbis_info_clear(vorbis_info *vi); +extern int vorbis_info_blocksize(vorbis_info *vi,int zo); +extern void vorbis_comment_init(vorbis_comment *vc); +extern void vorbis_comment_add(vorbis_comment *vc, char *comment); +extern void vorbis_comment_add_tag(vorbis_comment *vc, + char *tag, char *contents); +extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count); +extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag); +extern void vorbis_comment_clear(vorbis_comment *vc); + +extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb); +extern int vorbis_block_clear(vorbis_block *vb); +extern void vorbis_dsp_clear(vorbis_dsp_state *v); + +/* Vorbis PRIMITIVES: synthesis layer *******************************/ +extern int vorbis_synthesis_idheader(ogg_packet *op); +extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc, + ogg_packet *op); + +extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi); +extern int vorbis_synthesis_restart(vorbis_dsp_state *v); +extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op); +extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op); +extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb); +extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,ogg_int32_t ***pcm); +extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples); +extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op); + +/* Vorbis ERRORS and return codes ***********************************/ + +#define OV_FALSE -1 +#define OV_EOF -2 +#define OV_HOLE -3 + +#define OV_EREAD -128 +#define OV_EFAULT -129 +#define OV_EIMPL -130 +#define OV_EINVAL -131 +#define OV_ENOTVORBIS -132 +#define OV_EBADHEADER -133 +#define OV_EVERSION -134 +#define OV_ENOTAUDIO -135 +#define OV_EBADPACKET -136 +#define OV_EBADLINK -137 +#define OV_ENOSEEK -138 + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif + diff --git a/libs/tremor/ivorbisfile.h b/libs/tremor/ivorbisfile.h new file mode 100644 index 0000000..f6ecb0e --- /dev/null +++ b/libs/tremor/ivorbisfile.h @@ -0,0 +1,131 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: stdio-based convenience library for opening/seeking/decoding + + ********************************************************************/ + +#ifndef _OV_FILE_H_ +#define _OV_FILE_H_ + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#include +#include "ivorbiscodec.h" + +#define CHUNKSIZE 65535 +#define READSIZE 1024 +/* The function prototypes for the callbacks are basically the same as for + * the stdio functions fread, fseek, fclose, ftell. + * The one difference is that the FILE * arguments have been replaced with + * a void * - this is to be used as a pointer to whatever internal data these + * functions might need. In the stdio case, it's just a FILE * cast to a void * + * + * If you use other functions, check the docs for these functions and return + * the right values. For seek_func(), you *MUST* return -1 if the stream is + * unseekable + */ +typedef struct { + size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource); + int (*seek_func) (void *datasource, ogg_int64_t offset, int whence); + int (*close_func) (void *datasource); + long (*tell_func) (void *datasource); +} ov_callbacks; + +#define NOTOPEN 0 +#define PARTOPEN 1 +#define OPENED 2 +#define STREAMSET 3 +#define INITSET 4 + +typedef struct OggVorbis_File { + void *datasource; /* Pointer to a FILE *, etc. */ + int seekable; + ogg_int64_t offset; + ogg_int64_t end; + ogg_sync_state oy; + + /* If the FILE handle isn't seekable (eg, a pipe), only the current + stream appears */ + int links; + ogg_int64_t *offsets; + ogg_int64_t *dataoffsets; + ogg_uint32_t *serialnos; + ogg_int64_t *pcmlengths; + vorbis_info *vi; + vorbis_comment *vc; + + /* Decoding working state local storage */ + ogg_int64_t pcm_offset; + int ready_state; + ogg_uint32_t current_serialno; + int current_link; + + ogg_int64_t bittrack; + ogg_int64_t samptrack; + + ogg_stream_state os; /* take physical pages, weld into a logical + stream of packets */ + vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */ + vorbis_block vb; /* local working space for packet->PCM decode */ + + ov_callbacks callbacks; + +} OggVorbis_File; + +extern int ov_clear(OggVorbis_File *vf); +extern int ov_open(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes); +extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf, + const char *initial, long ibytes, ov_callbacks callbacks); + +extern int ov_test(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes); +extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf, + const char *initial, long ibytes, ov_callbacks callbacks); +extern int ov_test_open(OggVorbis_File *vf); + +extern long ov_bitrate(OggVorbis_File *vf,int i); +extern long ov_bitrate_instant(OggVorbis_File *vf); +extern long ov_streams(OggVorbis_File *vf); +extern long ov_seekable(OggVorbis_File *vf); +extern long ov_serialnumber(OggVorbis_File *vf,int i); + +extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i); +extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i); +extern ogg_int64_t ov_time_total(OggVorbis_File *vf,int i); + +extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos); +extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos); +extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos); +extern int ov_time_seek(OggVorbis_File *vf,ogg_int64_t pos); +extern int ov_time_seek_page(OggVorbis_File *vf,ogg_int64_t pos); + +extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf); +extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf); +extern ogg_int64_t ov_time_tell(OggVorbis_File *vf); + +extern vorbis_info *ov_info(OggVorbis_File *vf,int link); +extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link); + +extern long ov_read(OggVorbis_File *vf,char *buffer,int length, + int *bitstream); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif + + diff --git a/libs/tremor/ivorbisfile_example.dontcompile b/libs/tremor/ivorbisfile_example.dontcompile new file mode 100644 index 0000000..7b0cf10 --- /dev/null +++ b/libs/tremor/ivorbisfile_example.dontcompile @@ -0,0 +1,91 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: simple example decoder using vorbisidec + + ********************************************************************/ + +/* Takes a vorbis bitstream from stdin and writes raw stereo PCM to + stdout using vorbisfile. Using vorbisfile is much simpler than + dealing with libvorbis. */ + +#include +#include +#include "ivorbiscodec.h" +#include "ivorbisfile.h" + +#ifdef _WIN32 /* We need the following two to set stdin/stdout to binary */ +#include +#include +#endif + +char pcmout[4096]; /* take 4k out of the data segment, not the stack */ + +int main(){ + OggVorbis_File vf; + int eof=0; + int current_section; + +#ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */ + /* Beware the evil ifdef. We avoid these where we can, but this one we + cannot. Don't add any more, you'll probably go to hell if you do. */ + _setmode( _fileno( stdin ), _O_BINARY ); + _setmode( _fileno( stdout ), _O_BINARY ); +#endif + + if(ov_open(stdin, &vf, NULL, 0) < 0) { + fprintf(stderr,"Input does not appear to be an Ogg bitstream.\n"); + exit(1); + } + + /* Throw the comments plus a few lines about the bitstream we're + decoding */ + { + char **ptr=ov_comment(&vf,-1)->user_comments; + vorbis_info *vi=ov_info(&vf,-1); + while(*ptr){ + fprintf(stderr,"%s\n",*ptr); + ++ptr; + } + fprintf(stderr,"\nBitstream is %d channel, %ldHz\n",vi->channels,vi->rate); + fprintf(stderr,"\nDecoded length: %ld samples\n", + (long)ov_pcm_total(&vf,-1)); + fprintf(stderr,"Encoded by: %s\n\n",ov_comment(&vf,-1)->vendor); + } + + while(!eof){ + long ret=ov_read(&vf,pcmout,sizeof(pcmout),¤t_section); + if (ret == 0) { + /* EOF */ + eof=1; + } else if (ret < 0) { + if(ret==OV_EBADLINK){ + fprintf(stderr,"Corrupt bitstream section! Exiting.\n"); + exit(1); + } + + /* some other error in the stream. Not a problem, just reporting it in + case we (the app) cares. In this case, we don't. */ + } else { + /* we don't bother dealing with sample rate changes, etc, but + you'll have to*/ + fwrite(pcmout,1,ret,stdout); + } + } + + /* cleanup */ + ov_clear(&vf); + + fprintf(stderr,"Done.\n"); + return(0); +} diff --git a/libs/tremor/lsp_lookup.h b/libs/tremor/lsp_lookup.h new file mode 100644 index 0000000..7162392 --- /dev/null +++ b/libs/tremor/lsp_lookup.h @@ -0,0 +1,136 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: lookup data + + ********************************************************************/ + +#ifndef _V_LOOKUP_DATA_H_ +#define _V_LOOKUP_DATA_H_ + +#include + +#define FROMdB_LOOKUP_SZ 35 +#define FROMdB2_LOOKUP_SZ 32 +#define FROMdB_SHIFT 5 +#define FROMdB2_SHIFT 3 +#define FROMdB2_MASK 31 + +static const ogg_int32_t FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={ + 0x003fffff, 0x0028619b, 0x00197a96, 0x0010137a, + 0x000a24b0, 0x00066666, 0x000409c3, 0x00028c42, + 0x00019b8c, 0x000103ab, 0x0000a3d7, 0x00006760, + 0x0000413a, 0x00002928, 0x000019f8, 0x00001062, + 0x00000a56, 0x00000686, 0x0000041e, 0x00000299, + 0x000001a3, 0x00000109, 0x000000a7, 0x00000069, + 0x00000042, 0x0000002a, 0x0000001a, 0x00000011, + 0x0000000b, 0x00000007, 0x00000004, 0x00000003, + 0x00000002, 0x00000001, 0x00000001}; + +static const ogg_int32_t FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={ + 0x000001fc, 0x000001f5, 0x000001ee, 0x000001e7, + 0x000001e0, 0x000001d9, 0x000001d2, 0x000001cc, + 0x000001c5, 0x000001bf, 0x000001b8, 0x000001b2, + 0x000001ac, 0x000001a6, 0x000001a0, 0x0000019a, + 0x00000194, 0x0000018e, 0x00000188, 0x00000183, + 0x0000017d, 0x00000178, 0x00000172, 0x0000016d, + 0x00000168, 0x00000163, 0x0000015e, 0x00000159, + 0x00000154, 0x0000014f, 0x0000014a, 0x00000145, +}; + +#define INVSQ_LOOKUP_I_SHIFT 10 +#define INVSQ_LOOKUP_I_MASK 1023 +static const long INVSQ_LOOKUP_I[64+1]={ + 92682, 91966, 91267, 90583, + 89915, 89261, 88621, 87995, + 87381, 86781, 86192, 85616, + 85051, 84497, 83953, 83420, + 82897, 82384, 81880, 81385, + 80899, 80422, 79953, 79492, + 79039, 78594, 78156, 77726, + 77302, 76885, 76475, 76072, + 75674, 75283, 74898, 74519, + 74146, 73778, 73415, 73058, + 72706, 72359, 72016, 71679, + 71347, 71019, 70695, 70376, + 70061, 69750, 69444, 69141, + 68842, 68548, 68256, 67969, + 67685, 67405, 67128, 66855, + 66585, 66318, 66054, 65794, + 65536, +}; + +static const long INVSQ_LOOKUP_IDel[64]={ + 716, 699, 684, 668, + 654, 640, 626, 614, + 600, 589, 576, 565, + 554, 544, 533, 523, + 513, 504, 495, 486, + 477, 469, 461, 453, + 445, 438, 430, 424, + 417, 410, 403, 398, + 391, 385, 379, 373, + 368, 363, 357, 352, + 347, 343, 337, 332, + 328, 324, 319, 315, + 311, 306, 303, 299, + 294, 292, 287, 284, + 280, 277, 273, 270, + 267, 264, 260, 258, +}; + +#define COS_LOOKUP_I_SHIFT 9 +#define COS_LOOKUP_I_MASK 511 +#define COS_LOOKUP_I_SZ 128 +static const ogg_int32_t COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={ + 16384, 16379, 16364, 16340, + 16305, 16261, 16207, 16143, + 16069, 15986, 15893, 15791, + 15679, 15557, 15426, 15286, + 15137, 14978, 14811, 14635, + 14449, 14256, 14053, 13842, + 13623, 13395, 13160, 12916, + 12665, 12406, 12140, 11866, + 11585, 11297, 11003, 10702, + 10394, 10080, 9760, 9434, + 9102, 8765, 8423, 8076, + 7723, 7366, 7005, 6639, + 6270, 5897, 5520, 5139, + 4756, 4370, 3981, 3590, + 3196, 2801, 2404, 2006, + 1606, 1205, 804, 402, + 0, -401, -803, -1204, + -1605, -2005, -2403, -2800, + -3195, -3589, -3980, -4369, + -4755, -5138, -5519, -5896, + -6269, -6638, -7004, -7365, + -7722, -8075, -8422, -8764, + -9101, -9433, -9759, -10079, + -10393, -10701, -11002, -11296, + -11584, -11865, -12139, -12405, + -12664, -12915, -13159, -13394, + -13622, -13841, -14052, -14255, + -14448, -14634, -14810, -14977, + -15136, -15285, -15425, -15556, + -15678, -15790, -15892, -15985, + -16068, -16142, -16206, -16260, + -16304, -16339, -16363, -16378, + -16383, +}; + +#endif + + + + + diff --git a/libs/tremor/mapping0.c b/libs/tremor/mapping0.c new file mode 100644 index 0000000..aa03e85 --- /dev/null +++ b/libs/tremor/mapping0.c @@ -0,0 +1,328 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: channel mapping 0 implementation + + ********************************************************************/ + +#include +#include +#include +#include +#include +#include "ivorbiscodec.h" +#include "mdct.h" +#include "codec_internal.h" +#include "codebook.h" +#include "window.h" +#include "registry.h" +#include "misc.h" + +/* simplistic, wasteful way of doing this (unique lookup for each + mode/submapping); there should be a central repository for + identical lookups. That will require minor work, so I'm putting it + off as low priority. + + Why a lookup for each backend in a given mode? Because the + blocksize is set by the mode, and low backend lookups may require + parameters from other areas of the mode/mapping */ + +typedef struct { + vorbis_info_mode *mode; + vorbis_info_mapping0 *map; + + vorbis_look_floor **floor_look; + + vorbis_look_residue **residue_look; + + vorbis_func_floor **floor_func; + vorbis_func_residue **residue_func; + + int ch; + long lastframe; /* if a different mode is called, we need to + invalidate decay */ +} vorbis_look_mapping0; + +static void mapping0_free_info(vorbis_info_mapping *i){ + vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i; + if(info){ + memset(info,0,sizeof(*info)); + _ogg_free(info); + } +} + +static void mapping0_free_look(vorbis_look_mapping *look){ + int i; + vorbis_look_mapping0 *l=(vorbis_look_mapping0 *)look; + if(l){ + + for(i=0;imap->submaps;i++){ + l->floor_func[i]->free_look(l->floor_look[i]); + l->residue_func[i]->free_look(l->residue_look[i]); + } + + _ogg_free(l->floor_func); + _ogg_free(l->residue_func); + _ogg_free(l->floor_look); + _ogg_free(l->residue_look); + memset(l,0,sizeof(*l)); + _ogg_free(l); + } +} + +static vorbis_look_mapping *mapping0_look(vorbis_dsp_state *vd,vorbis_info_mode *vm, + vorbis_info_mapping *m){ + int i; + vorbis_info *vi=vd->vi; + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + vorbis_look_mapping0 *look=(vorbis_look_mapping0 *)_ogg_calloc(1,sizeof(*look)); + vorbis_info_mapping0 *info=look->map=(vorbis_info_mapping0 *)m; + look->mode=vm; + + look->floor_look=(vorbis_look_floor **)_ogg_calloc(info->submaps,sizeof(*look->floor_look)); + + look->residue_look=(vorbis_look_residue **)_ogg_calloc(info->submaps,sizeof(*look->residue_look)); + + look->floor_func=(vorbis_func_floor **)_ogg_calloc(info->submaps,sizeof(*look->floor_func)); + look->residue_func=(vorbis_func_residue **)_ogg_calloc(info->submaps,sizeof(*look->residue_func)); + + for(i=0;isubmaps;i++){ + int floornum=info->floorsubmap[i]; + int resnum=info->residuesubmap[i]; + + look->floor_func[i]=_floor_P[ci->floor_type[floornum]]; + look->floor_look[i]=look->floor_func[i]-> + look(vd,vm,ci->floor_param[floornum]); + look->residue_func[i]=_residue_P[ci->residue_type[resnum]]; + look->residue_look[i]=look->residue_func[i]-> + look(vd,vm,ci->residue_param[resnum]); + + } + + look->ch=vi->channels; + + return(look); +} + +static int ilog(unsigned int v){ + int ret=0; + if(v)--v; + while(v){ + ret++; + v>>=1; + } + return(ret); +} + +/* also responsible for range checking */ +static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){ + int i,b; + vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)_ogg_calloc(1,sizeof(*info)); + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + memset(info,0,sizeof(*info)); + + b=oggpack_read(opb,1); + if(b<0)goto err_out; + if(b){ + info->submaps=oggpack_read(opb,4)+1; + if(info->submaps<=0)goto err_out; + }else + info->submaps=1; + + b=oggpack_read(opb,1); + if(b<0)goto err_out; + if(b){ + info->coupling_steps=oggpack_read(opb,8)+1; + if(info->coupling_steps<=0)goto err_out; + for(i=0;icoupling_steps;i++){ + int testM=info->coupling_mag[i]=oggpack_read(opb,ilog(vi->channels)); + int testA=info->coupling_ang[i]=oggpack_read(opb,ilog(vi->channels)); + + if(testM<0 || + testA<0 || + testM==testA || + testM>=vi->channels || + testA>=vi->channels) goto err_out; + } + + } + + if(oggpack_read(opb,2)!=0)goto err_out; /* 2,3:reserved */ + + if(info->submaps>1){ + for(i=0;ichannels;i++){ + info->chmuxlist[i]=oggpack_read(opb,4); + if(info->chmuxlist[i]>=info->submaps || info->chmuxlist[i]<0)goto err_out; + } + } + for(i=0;isubmaps;i++){ + int temp=oggpack_read(opb,8); + if(temp>=ci->times)goto err_out; + info->floorsubmap[i]=oggpack_read(opb,8); + if(info->floorsubmap[i]>=ci->floors || info->floorsubmap[i]<0)goto err_out; + info->residuesubmap[i]=oggpack_read(opb,8); + if(info->residuesubmap[i]>=ci->residues || info->residuesubmap[i]<0) + goto err_out; + } + + return info; + + err_out: + mapping0_free_info(info); + return(NULL); +} + +static int seq=0; +static int mapping0_inverse(vorbis_block *vb,vorbis_look_mapping *l){ + vorbis_dsp_state *vd=vb->vd; + vorbis_info *vi=vd->vi; + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + private_state *b=(private_state *)vd->backend_state; + vorbis_look_mapping0 *look=(vorbis_look_mapping0 *)l; + vorbis_info_mapping0 *info=look->map; + + int i,j; + long n=vb->pcmend=ci->blocksizes[vb->W]; + + ogg_int32_t **pcmbundle=(ogg_int32_t **)alloca(sizeof(*pcmbundle)*vi->channels); + int *zerobundle=(int *)alloca(sizeof(*zerobundle)*vi->channels); + + int *nonzero =(int *)alloca(sizeof(*nonzero)*vi->channels); + void **floormemo=(void **)alloca(sizeof(*floormemo)*vi->channels); + + /* time domain information decode (note that applying the + information would have to happen later; we'll probably add a + function entry to the harness for that later */ + /* NOT IMPLEMENTED */ + + /* recover the spectral envelope; store it in the PCM vector for now */ + for(i=0;ichannels;i++){ + int submap=info->chmuxlist[i]; + floormemo[i]=look->floor_func[submap]-> + inverse1(vb,look->floor_look[submap]); + if(floormemo[i]) + nonzero[i]=1; + else + nonzero[i]=0; + memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2); + } + + /* channel coupling can 'dirty' the nonzero listing */ + for(i=0;icoupling_steps;i++){ + if(nonzero[info->coupling_mag[i]] || + nonzero[info->coupling_ang[i]]){ + nonzero[info->coupling_mag[i]]=1; + nonzero[info->coupling_ang[i]]=1; + } + } + + /* recover the residue into our working vectors */ + for(i=0;isubmaps;i++){ + int ch_in_bundle=0; + for(j=0;jchannels;j++){ + if(info->chmuxlist[j]==i){ + if(nonzero[j]) + zerobundle[ch_in_bundle]=1; + else + zerobundle[ch_in_bundle]=0; + pcmbundle[ch_in_bundle++]=vb->pcm[j]; + } + } + + look->residue_func[i]->inverse(vb,look->residue_look[i], + pcmbundle,zerobundle,ch_in_bundle); + } + + //for(j=0;jchannels;j++) + //_analysis_output("coupled",seq+j,vb->pcm[j],-8,n/2,0,0); + + + /* channel coupling */ + for(i=info->coupling_steps-1;i>=0;i--){ + ogg_int32_t *pcmM=vb->pcm[info->coupling_mag[i]]; + ogg_int32_t *pcmA=vb->pcm[info->coupling_ang[i]]; + + for(j=0;j0) + if(ang>0){ + pcmM[j]=mag; + pcmA[j]=mag-ang; + }else{ + pcmA[j]=mag; + pcmM[j]=mag+ang; + } + else + if(ang>0){ + pcmM[j]=mag; + pcmA[j]=mag+ang; + }else{ + pcmA[j]=mag; + pcmM[j]=mag-ang; + } + } + } + + //for(j=0;jchannels;j++) + //_analysis_output("residue",seq+j,vb->pcm[j],-8,n/2,0,0); + + /* compute and apply spectral envelope */ + for(i=0;ichannels;i++){ + ogg_int32_t *pcm=vb->pcm[i]; + int submap=info->chmuxlist[i]; + look->floor_func[submap]-> + inverse2(vb,look->floor_look[submap],floormemo[i],pcm); + } + + //for(j=0;jchannels;j++) + //_analysis_output("mdct",seq+j,vb->pcm[j],-24,n/2,0,1); + + /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */ + /* only MDCT right now.... */ + for(i=0;ichannels;i++){ + ogg_int32_t *pcm=vb->pcm[i]; + mdct_backward(n,pcm,pcm); + } + + //for(j=0;jchannels;j++) + //_analysis_output("imdct",seq+j,vb->pcm[j],-24,n,0,0); + + /* window the data */ + for(i=0;ichannels;i++){ + ogg_int32_t *pcm=vb->pcm[i]; + if(nonzero[i]) + _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW); + else + for(j=0;jchannels;j++) + //_analysis_output("window",seq+j,vb->pcm[j],-24,n,0,0); + + seq+=vi->channels; + /* all done! */ + return(0); +} + +/* export hooks */ +vorbis_func_mapping mapping0_exportbundle={ + &mapping0_unpack, + &mapping0_look, + &mapping0_free_info, + &mapping0_free_look, + &mapping0_inverse +}; diff --git a/libs/tremor/mdct.c b/libs/tremor/mdct.c new file mode 100644 index 0000000..2aed62c --- /dev/null +++ b/libs/tremor/mdct.c @@ -0,0 +1,510 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: normalized modified discrete cosine transform + power of two length transform only [64 <= n ] + last mod: $Id$ + + Original algorithm adapted long ago from _The use of multirate filter + banks for coding of high quality digital audio_, by T. Sporer, + K. Brandenburg and B. Edler, collection of the European Signal + Processing Conference (EUSIPCO), Amsterdam, June 1992, Vol.1, pp + 211-214 + + The below code implements an algorithm that no longer looks much like + that presented in the paper, but the basic structure remains if you + dig deep enough to see it. + + This module DOES NOT INCLUDE code to generate/apply the window + function. Everybody has their own weird favorite including me... I + happen to like the properties of y=sin(.5PI*sin^2(x)), but others may + vehemently disagree. + + ********************************************************************/ + +#include "ivorbiscodec.h" +#include "codebook.h" +#include "misc.h" +#include "mdct.h" +#include "mdct_lookup.h" + + +/* 8 point butterfly (in place) */ +STIN void mdct_butterfly_8(DATA_TYPE *x){ + + REG_TYPE r0 = x[4] + x[0]; + REG_TYPE r1 = x[4] - x[0]; + REG_TYPE r2 = x[5] + x[1]; + REG_TYPE r3 = x[5] - x[1]; + REG_TYPE r4 = x[6] + x[2]; + REG_TYPE r5 = x[6] - x[2]; + REG_TYPE r6 = x[7] + x[3]; + REG_TYPE r7 = x[7] - x[3]; + + x[0] = r5 + r3; + x[1] = r7 - r1; + x[2] = r5 - r3; + x[3] = r7 + r1; + x[4] = r4 - r0; + x[5] = r6 - r2; + x[6] = r4 + r0; + x[7] = r6 + r2; + MB(); +} + +/* 16 point butterfly (in place, 4 register) */ +STIN void mdct_butterfly_16(DATA_TYPE *x){ + + REG_TYPE r0, r1; + + r0 = x[ 0] - x[ 8]; x[ 8] += x[ 0]; + r1 = x[ 1] - x[ 9]; x[ 9] += x[ 1]; + x[ 0] = MULT31((r0 + r1) , cPI2_8); + x[ 1] = MULT31((r1 - r0) , cPI2_8); + MB(); + + r0 = x[10] - x[ 2]; x[10] += x[ 2]; + r1 = x[ 3] - x[11]; x[11] += x[ 3]; + x[ 2] = r1; x[ 3] = r0; + MB(); + + r0 = x[12] - x[ 4]; x[12] += x[ 4]; + r1 = x[13] - x[ 5]; x[13] += x[ 5]; + x[ 4] = MULT31((r0 - r1) , cPI2_8); + x[ 5] = MULT31((r0 + r1) , cPI2_8); + MB(); + + r0 = x[14] - x[ 6]; x[14] += x[ 6]; + r1 = x[15] - x[ 7]; x[15] += x[ 7]; + x[ 6] = r0; x[ 7] = r1; + MB(); + + mdct_butterfly_8(x); + mdct_butterfly_8(x+8); +} + +/* 32 point butterfly (in place, 4 register) */ +STIN void mdct_butterfly_32(DATA_TYPE *x){ + + REG_TYPE r0, r1; + + r0 = x[30] - x[14]; x[30] += x[14]; + r1 = x[31] - x[15]; x[31] += x[15]; + x[14] = r0; x[15] = r1; + MB(); + + r0 = x[28] - x[12]; x[28] += x[12]; + r1 = x[29] - x[13]; x[29] += x[13]; + XNPROD31( r0, r1, cPI1_8, cPI3_8, &x[12], &x[13] ); + MB(); + + r0 = x[26] - x[10]; x[26] += x[10]; + r1 = x[27] - x[11]; x[27] += x[11]; + x[10] = MULT31((r0 - r1) , cPI2_8); + x[11] = MULT31((r0 + r1) , cPI2_8); + MB(); + + r0 = x[24] - x[ 8]; x[24] += x[ 8]; + r1 = x[25] - x[ 9]; x[25] += x[ 9]; + XNPROD31( r0, r1, cPI3_8, cPI1_8, &x[ 8], &x[ 9] ); + MB(); + + r0 = x[22] - x[ 6]; x[22] += x[ 6]; + r1 = x[ 7] - x[23]; x[23] += x[ 7]; + x[ 6] = r1; x[ 7] = r0; + MB(); + + r0 = x[ 4] - x[20]; x[20] += x[ 4]; + r1 = x[ 5] - x[21]; x[21] += x[ 5]; + XPROD31 ( r0, r1, cPI3_8, cPI1_8, &x[ 4], &x[ 5] ); + MB(); + + r0 = x[ 2] - x[18]; x[18] += x[ 2]; + r1 = x[ 3] - x[19]; x[19] += x[ 3]; + x[ 2] = MULT31((r1 + r0) , cPI2_8); + x[ 3] = MULT31((r1 - r0) , cPI2_8); + MB(); + + r0 = x[ 0] - x[16]; x[16] += x[ 0]; + r1 = x[ 1] - x[17]; x[17] += x[ 1]; + XPROD31 ( r0, r1, cPI1_8, cPI3_8, &x[ 0], &x[ 1] ); + MB(); + + mdct_butterfly_16(x); + mdct_butterfly_16(x+16); +} + +/* N/stage point generic N stage butterfly (in place, 2 register) */ +STIN void mdct_butterfly_generic(DATA_TYPE *x,int points,int step){ + + LOOKUP_T *T = sincos_lookup0; + DATA_TYPE *x1 = x + points - 8; + DATA_TYPE *x2 = x + (points>>1) - 8; + REG_TYPE r0; + REG_TYPE r1; + + do{ + r0 = x1[6] - x2[6]; x1[6] += x2[6]; + r1 = x2[7] - x1[7]; x1[7] += x2[7]; + XPROD31( r1, r0, T[0], T[1], &x2[6], &x2[7] ); T+=step; + + r0 = x1[4] - x2[4]; x1[4] += x2[4]; + r1 = x2[5] - x1[5]; x1[5] += x2[5]; + XPROD31( r1, r0, T[0], T[1], &x2[4], &x2[5] ); T+=step; + + r0 = x1[2] - x2[2]; x1[2] += x2[2]; + r1 = x2[3] - x1[3]; x1[3] += x2[3]; + XPROD31( r1, r0, T[0], T[1], &x2[2], &x2[3] ); T+=step; + + r0 = x1[0] - x2[0]; x1[0] += x2[0]; + r1 = x2[1] - x1[1]; x1[1] += x2[1]; + XPROD31( r1, r0, T[0], T[1], &x2[0], &x2[1] ); T+=step; + + x1-=8; x2-=8; + }while(Tsincos_lookup0); + do{ + r0 = x2[6] - x1[6]; x1[6] += x2[6]; + r1 = x2[7] - x1[7]; x1[7] += x2[7]; + XPROD31( r0, r1, T[0], T[1], &x2[6], &x2[7] ); T+=step; + + r0 = x2[4] - x1[4]; x1[4] += x2[4]; + r1 = x2[5] - x1[5]; x1[5] += x2[5]; + XPROD31( r0, r1, T[0], T[1], &x2[4], &x2[5] ); T+=step; + + r0 = x2[2] - x1[2]; x1[2] += x2[2]; + r1 = x2[3] - x1[3]; x1[3] += x2[3]; + XPROD31( r0, r1, T[0], T[1], &x2[2], &x2[3] ); T+=step; + + r0 = x2[0] - x1[0]; x1[0] += x2[0]; + r1 = x2[1] - x1[1]; x1[1] += x2[1]; + XPROD31( r0, r1, T[0], T[1], &x2[0], &x2[1] ); T+=step; + + x1-=8; x2-=8; + }while(Tsincos_lookup0); +} + +STIN void mdct_butterflies(DATA_TYPE *x,int points,int shift){ + + int stages=8-shift; + int i,j; + + for(i=0;--stages>0;i++){ + for(j=0;j<(1<>i)*j,points>>i,4<<(i+shift)); + } + + for(j=0;j>8]|(bitrev[(x&0x0f0)>>4]<<4)|(((int)bitrev[x&0x00f])<<8); +} + +STIN void mdct_bitreverse(DATA_TYPE *x,int n,int step,int shift){ + + int bit = 0; + DATA_TYPE *w0 = x; + DATA_TYPE *w1 = x = w0+(n>>1); + LOOKUP_T *T = (step>=4)?(sincos_lookup0+(step>>1)):sincos_lookup1; + LOOKUP_T *Ttop = T+1024; + DATA_TYPE r2; + + do{ + DATA_TYPE r3 = bitrev12(bit++); + DATA_TYPE *x0 = x + ((r3 ^ 0xfff)>>shift) -1; + DATA_TYPE *x1 = x + (r3>>shift); + + REG_TYPE r0 = x0[0] + x1[0]; + REG_TYPE r1 = x1[1] - x0[1]; + + XPROD32( r0, r1, T[1], T[0], &r2, &r3 ); T+=step; + + w1 -= 4; + + r0 = (x0[1] + x1[1])>>1; + r1 = (x0[0] - x1[0])>>1; + w0[0] = r0 + r2; + w0[1] = r1 + r3; + w1[2] = r0 - r2; + w1[3] = r3 - r1; + + r3 = bitrev12(bit++); + x0 = x + ((r3 ^ 0xfff)>>shift) -1; + x1 = x + (r3>>shift); + + r0 = x0[0] + x1[0]; + r1 = x1[1] - x0[1]; + + XPROD32( r0, r1, T[1], T[0], &r2, &r3 ); T+=step; + + r0 = (x0[1] + x1[1])>>1; + r1 = (x0[0] - x1[0])>>1; + w0[2] = r0 + r2; + w0[3] = r1 + r3; + w1[0] = r0 - r2; + w1[1] = r3 - r1; + + w0 += 4; + }while(T>shift) -1; + DATA_TYPE *x1 = x + (r3>>shift); + + REG_TYPE r0 = x0[0] + x1[0]; + REG_TYPE r1 = x1[1] - x0[1]; + + T-=step; XPROD32( r0, r1, T[0], T[1], &r2, &r3 ); + + w1 -= 4; + + r0 = (x0[1] + x1[1])>>1; + r1 = (x0[0] - x1[0])>>1; + w0[0] = r0 + r2; + w0[1] = r1 + r3; + w1[2] = r0 - r2; + w1[3] = r3 - r1; + + r3 = bitrev12(bit++); + x0 = x + ((r3 ^ 0xfff)>>shift) -1; + x1 = x + (r3>>shift); + + r0 = x0[0] + x1[0]; + r1 = x1[1] - x0[1]; + + T-=step; XPROD32( r0, r1, T[0], T[1], &r2, &r3 ); + + r0 = (x0[1] + x1[1])>>1; + r1 = (x0[0] - x1[0])>>1; + w0[2] = r0 + r2; + w0[3] = r1 + r3; + w1[0] = r0 - r2; + w1[1] = r3 - r1; + + w0 += 4; + }while(w0>1; + int n4=n>>2; + DATA_TYPE *iX; + DATA_TYPE *oX; + LOOKUP_T *T; + LOOKUP_T *V; + int shift; + int step; + + for (shift=6;!(n&(1<=in+n4); + do{ + oX-=4; + XPROD31( iX[4], iX[6], T[1], T[0], &oX[2], &oX[3] ); T-=step; + XPROD31( iX[0], iX[2], T[1], T[0], &oX[0], &oX[1] ); T-=step; + iX-=8; + }while(iX>=in); + + iX = in+n2-8; + oX = out+n2+n4; + T = sincos_lookup0; + + do{ + T+=step; XNPROD31( iX[6], iX[4], T[0], T[1], &oX[0], &oX[1] ); + T+=step; XNPROD31( iX[2], iX[0], T[0], T[1], &oX[2], &oX[3] ); + iX-=8; + oX+=4; + }while(iX>=in+n4); + do{ + T-=step; XNPROD31( iX[6], iX[4], T[1], T[0], &oX[0], &oX[1] ); + T-=step; XNPROD31( iX[2], iX[0], T[1], T[0], &oX[2], &oX[3] ); + iX-=8; + oX+=4; + }while(iX>=in); + + mdct_butterflies(out+n2,n2,shift); + mdct_bitreverse(out,n,step,shift); + + /* rotate + window */ + + step>>=2; + { + DATA_TYPE *oX1=out+n2+n4; + DATA_TYPE *oX2=out+n2+n4; + DATA_TYPE *iX =out; + + switch(step) { + default: { + T=(step>=4)?(sincos_lookup0+(step>>1)):sincos_lookup1; + do{ + oX1-=4; + XPROD31( iX[0], -iX[1], T[0], T[1], &oX1[3], &oX2[0] ); T+=step; + XPROD31( iX[2], -iX[3], T[0], T[1], &oX1[2], &oX2[1] ); T+=step; + XPROD31( iX[4], -iX[5], T[0], T[1], &oX1[1], &oX2[2] ); T+=step; + XPROD31( iX[6], -iX[7], T[0], T[1], &oX1[0], &oX2[3] ); T+=step; + oX2+=4; + iX+=8; + }while(iX>1; + t1 = (*T++)>>1; + do{ + oX1-=4; + + t0 += (v0 = (*V++)>>1); + t1 += (v1 = (*V++)>>1); + XPROD31( iX[0], -iX[1], t0, t1, &oX1[3], &oX2[0] ); + v0 += (t0 = (*T++)>>1); + v1 += (t1 = (*T++)>>1); + XPROD31( iX[2], -iX[3], v0, v1, &oX1[2], &oX2[1] ); + t0 += (v0 = (*V++)>>1); + t1 += (v1 = (*V++)>>1); + XPROD31( iX[4], -iX[5], t0, t1, &oX1[1], &oX2[2] ); + v0 += (t0 = (*T++)>>1); + v1 += (t1 = (*T++)>>1); + XPROD31( iX[6], -iX[7], v0, v1, &oX1[0], &oX2[3] ); + + oX2+=4; + iX+=8; + }while(iX>2); + t1 += (q1 = (v1-t1)>>2); + XPROD31( iX[0], -iX[1], t0, t1, &oX1[3], &oX2[0] ); + t0 = v0-q0; + t1 = v1-q1; + XPROD31( iX[2], -iX[3], t0, t1, &oX1[2], &oX2[1] ); + + t0 = *T++; + t1 = *T++; + v0 += (q0 = (t0-v0)>>2); + v1 += (q1 = (t1-v1)>>2); + XPROD31( iX[4], -iX[5], v0, v1, &oX1[1], &oX2[2] ); + v0 = t0-q0; + v1 = t1-q1; + XPROD31( iX[6], -iX[7], v0, v1, &oX1[0], &oX2[3] ); + + oX2+=4; + iX+=8; + }while(iXoX2); + } +} + diff --git a/libs/tremor/mdct.h b/libs/tremor/mdct.h new file mode 100644 index 0000000..6d88907 --- /dev/null +++ b/libs/tremor/mdct.h @@ -0,0 +1,52 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: modified discrete cosine transform prototypes + + ********************************************************************/ + +#ifndef _OGG_mdct_H_ +#define _OGG_mdct_H_ + +#include "ivorbiscodec.h" +#include "misc.h" + +#define DATA_TYPE ogg_int32_t +#define REG_TYPE register ogg_int32_t + +#ifdef _LOW_ACCURACY_ +#define cPI3_8 (0x0062) +#define cPI2_8 (0x00b5) +#define cPI1_8 (0x00ed) +#else +#define cPI3_8 (0x30fbc54d) +#define cPI2_8 (0x5a82799a) +#define cPI1_8 (0x7641af3d) +#endif + +extern void mdct_forward(int n, DATA_TYPE *in, DATA_TYPE *out); +extern void mdct_backward(int n, DATA_TYPE *in, DATA_TYPE *out); + +#endif + + + + + + + + + + + + diff --git a/libs/tremor/mdct_lookup.h b/libs/tremor/mdct_lookup.h new file mode 100644 index 0000000..ee4f101 --- /dev/null +++ b/libs/tremor/mdct_lookup.h @@ -0,0 +1,540 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: sin,cos lookup tables + + ********************************************************************/ + +#include "misc.h" + +/* {sin(2*i*PI/4096), cos(2*i*PI/4096)}, with i = 0 to 512 */ +static const LOOKUP_T sincos_lookup0[1026] = { + X(0x00000000), X(0x7fffffff), X(0x003243f5), X(0x7ffff621), + X(0x006487e3), X(0x7fffd886), X(0x0096cbc1), X(0x7fffa72c), + X(0x00c90f88), X(0x7fff6216), X(0x00fb5330), X(0x7fff0943), + X(0x012d96b1), X(0x7ffe9cb2), X(0x015fda03), X(0x7ffe1c65), + X(0x01921d20), X(0x7ffd885a), X(0x01c45ffe), X(0x7ffce093), + X(0x01f6a297), X(0x7ffc250f), X(0x0228e4e2), X(0x7ffb55ce), + X(0x025b26d7), X(0x7ffa72d1), X(0x028d6870), X(0x7ff97c18), + X(0x02bfa9a4), X(0x7ff871a2), X(0x02f1ea6c), X(0x7ff75370), + X(0x03242abf), X(0x7ff62182), X(0x03566a96), X(0x7ff4dbd9), + X(0x0388a9ea), X(0x7ff38274), X(0x03bae8b2), X(0x7ff21553), + X(0x03ed26e6), X(0x7ff09478), X(0x041f6480), X(0x7feeffe1), + X(0x0451a177), X(0x7fed5791), X(0x0483ddc3), X(0x7feb9b85), + X(0x04b6195d), X(0x7fe9cbc0), X(0x04e8543e), X(0x7fe7e841), + X(0x051a8e5c), X(0x7fe5f108), X(0x054cc7b1), X(0x7fe3e616), + X(0x057f0035), X(0x7fe1c76b), X(0x05b137df), X(0x7fdf9508), + X(0x05e36ea9), X(0x7fdd4eec), X(0x0615a48b), X(0x7fdaf519), + X(0x0647d97c), X(0x7fd8878e), X(0x067a0d76), X(0x7fd6064c), + X(0x06ac406f), X(0x7fd37153), X(0x06de7262), X(0x7fd0c8a3), + X(0x0710a345), X(0x7fce0c3e), X(0x0742d311), X(0x7fcb3c23), + X(0x077501be), X(0x7fc85854), X(0x07a72f45), X(0x7fc560cf), + X(0x07d95b9e), X(0x7fc25596), X(0x080b86c2), X(0x7fbf36aa), + X(0x083db0a7), X(0x7fbc040a), X(0x086fd947), X(0x7fb8bdb8), + X(0x08a2009a), X(0x7fb563b3), X(0x08d42699), X(0x7fb1f5fc), + X(0x09064b3a), X(0x7fae7495), X(0x09386e78), X(0x7faadf7c), + X(0x096a9049), X(0x7fa736b4), X(0x099cb0a7), X(0x7fa37a3c), + X(0x09cecf89), X(0x7f9faa15), X(0x0a00ece8), X(0x7f9bc640), + X(0x0a3308bd), X(0x7f97cebd), X(0x0a6522fe), X(0x7f93c38c), + X(0x0a973ba5), X(0x7f8fa4b0), X(0x0ac952aa), X(0x7f8b7227), + X(0x0afb6805), X(0x7f872bf3), X(0x0b2d7baf), X(0x7f82d214), + X(0x0b5f8d9f), X(0x7f7e648c), X(0x0b919dcf), X(0x7f79e35a), + X(0x0bc3ac35), X(0x7f754e80), X(0x0bf5b8cb), X(0x7f70a5fe), + X(0x0c27c389), X(0x7f6be9d4), X(0x0c59cc68), X(0x7f671a05), + X(0x0c8bd35e), X(0x7f62368f), X(0x0cbdd865), X(0x7f5d3f75), + X(0x0cefdb76), X(0x7f5834b7), X(0x0d21dc87), X(0x7f531655), + X(0x0d53db92), X(0x7f4de451), X(0x0d85d88f), X(0x7f489eaa), + X(0x0db7d376), X(0x7f434563), X(0x0de9cc40), X(0x7f3dd87c), + X(0x0e1bc2e4), X(0x7f3857f6), X(0x0e4db75b), X(0x7f32c3d1), + X(0x0e7fa99e), X(0x7f2d1c0e), X(0x0eb199a4), X(0x7f2760af), + X(0x0ee38766), X(0x7f2191b4), X(0x0f1572dc), X(0x7f1baf1e), + X(0x0f475bff), X(0x7f15b8ee), X(0x0f7942c7), X(0x7f0faf25), + X(0x0fab272b), X(0x7f0991c4), X(0x0fdd0926), X(0x7f0360cb), + X(0x100ee8ad), X(0x7efd1c3c), X(0x1040c5bb), X(0x7ef6c418), + X(0x1072a048), X(0x7ef05860), X(0x10a4784b), X(0x7ee9d914), + X(0x10d64dbd), X(0x7ee34636), X(0x11082096), X(0x7edc9fc6), + X(0x1139f0cf), X(0x7ed5e5c6), X(0x116bbe60), X(0x7ecf1837), + X(0x119d8941), X(0x7ec8371a), X(0x11cf516a), X(0x7ec14270), + X(0x120116d5), X(0x7eba3a39), X(0x1232d979), X(0x7eb31e78), + X(0x1264994e), X(0x7eabef2c), X(0x1296564d), X(0x7ea4ac58), + X(0x12c8106f), X(0x7e9d55fc), X(0x12f9c7aa), X(0x7e95ec1a), + X(0x132b7bf9), X(0x7e8e6eb2), X(0x135d2d53), X(0x7e86ddc6), + X(0x138edbb1), X(0x7e7f3957), X(0x13c0870a), X(0x7e778166), + X(0x13f22f58), X(0x7e6fb5f4), X(0x1423d492), X(0x7e67d703), + X(0x145576b1), X(0x7e5fe493), X(0x148715ae), X(0x7e57dea7), + X(0x14b8b17f), X(0x7e4fc53e), X(0x14ea4a1f), X(0x7e47985b), + X(0x151bdf86), X(0x7e3f57ff), X(0x154d71aa), X(0x7e37042a), + X(0x157f0086), X(0x7e2e9cdf), X(0x15b08c12), X(0x7e26221f), + X(0x15e21445), X(0x7e1d93ea), X(0x16139918), X(0x7e14f242), + X(0x16451a83), X(0x7e0c3d29), X(0x1676987f), X(0x7e0374a0), + X(0x16a81305), X(0x7dfa98a8), X(0x16d98a0c), X(0x7df1a942), + X(0x170afd8d), X(0x7de8a670), X(0x173c6d80), X(0x7ddf9034), + X(0x176dd9de), X(0x7dd6668f), X(0x179f429f), X(0x7dcd2981), + X(0x17d0a7bc), X(0x7dc3d90d), X(0x1802092c), X(0x7dba7534), + X(0x183366e9), X(0x7db0fdf8), X(0x1864c0ea), X(0x7da77359), + X(0x18961728), X(0x7d9dd55a), X(0x18c7699b), X(0x7d9423fc), + X(0x18f8b83c), X(0x7d8a5f40), X(0x192a0304), X(0x7d808728), + X(0x195b49ea), X(0x7d769bb5), X(0x198c8ce7), X(0x7d6c9ce9), + X(0x19bdcbf3), X(0x7d628ac6), X(0x19ef0707), X(0x7d58654d), + X(0x1a203e1b), X(0x7d4e2c7f), X(0x1a517128), X(0x7d43e05e), + X(0x1a82a026), X(0x7d3980ec), X(0x1ab3cb0d), X(0x7d2f0e2b), + X(0x1ae4f1d6), X(0x7d24881b), X(0x1b161479), X(0x7d19eebf), + X(0x1b4732ef), X(0x7d0f4218), X(0x1b784d30), X(0x7d048228), + X(0x1ba96335), X(0x7cf9aef0), X(0x1bda74f6), X(0x7ceec873), + X(0x1c0b826a), X(0x7ce3ceb2), X(0x1c3c8b8c), X(0x7cd8c1ae), + X(0x1c6d9053), X(0x7ccda169), X(0x1c9e90b8), X(0x7cc26de5), + X(0x1ccf8cb3), X(0x7cb72724), X(0x1d00843d), X(0x7cabcd28), + X(0x1d31774d), X(0x7ca05ff1), X(0x1d6265dd), X(0x7c94df83), + X(0x1d934fe5), X(0x7c894bde), X(0x1dc4355e), X(0x7c7da505), + X(0x1df5163f), X(0x7c71eaf9), X(0x1e25f282), X(0x7c661dbc), + X(0x1e56ca1e), X(0x7c5a3d50), X(0x1e879d0d), X(0x7c4e49b7), + X(0x1eb86b46), X(0x7c4242f2), X(0x1ee934c3), X(0x7c362904), + X(0x1f19f97b), X(0x7c29fbee), X(0x1f4ab968), X(0x7c1dbbb3), + X(0x1f7b7481), X(0x7c116853), X(0x1fac2abf), X(0x7c0501d2), + X(0x1fdcdc1b), X(0x7bf88830), X(0x200d888d), X(0x7bebfb70), + X(0x203e300d), X(0x7bdf5b94), X(0x206ed295), X(0x7bd2a89e), + X(0x209f701c), X(0x7bc5e290), X(0x20d0089c), X(0x7bb9096b), + X(0x21009c0c), X(0x7bac1d31), X(0x21312a65), X(0x7b9f1de6), + X(0x2161b3a0), X(0x7b920b89), X(0x219237b5), X(0x7b84e61f), + X(0x21c2b69c), X(0x7b77ada8), X(0x21f3304f), X(0x7b6a6227), + X(0x2223a4c5), X(0x7b5d039e), X(0x225413f8), X(0x7b4f920e), + X(0x22847de0), X(0x7b420d7a), X(0x22b4e274), X(0x7b3475e5), + X(0x22e541af), X(0x7b26cb4f), X(0x23159b88), X(0x7b190dbc), + X(0x2345eff8), X(0x7b0b3d2c), X(0x23763ef7), X(0x7afd59a4), + X(0x23a6887f), X(0x7aef6323), X(0x23d6cc87), X(0x7ae159ae), + X(0x24070b08), X(0x7ad33d45), X(0x243743fa), X(0x7ac50dec), + X(0x24677758), X(0x7ab6cba4), X(0x2497a517), X(0x7aa8766f), + X(0x24c7cd33), X(0x7a9a0e50), X(0x24f7efa2), X(0x7a8b9348), + X(0x25280c5e), X(0x7a7d055b), X(0x2558235f), X(0x7a6e648a), + X(0x2588349d), X(0x7a5fb0d8), X(0x25b84012), X(0x7a50ea47), + X(0x25e845b6), X(0x7a4210d8), X(0x26184581), X(0x7a332490), + X(0x26483f6c), X(0x7a24256f), X(0x26783370), X(0x7a151378), + X(0x26a82186), X(0x7a05eead), X(0x26d809a5), X(0x79f6b711), + X(0x2707ebc7), X(0x79e76ca7), X(0x2737c7e3), X(0x79d80f6f), + X(0x27679df4), X(0x79c89f6e), X(0x27976df1), X(0x79b91ca4), + X(0x27c737d3), X(0x79a98715), X(0x27f6fb92), X(0x7999dec4), + X(0x2826b928), X(0x798a23b1), X(0x2856708d), X(0x797a55e0), + X(0x288621b9), X(0x796a7554), X(0x28b5cca5), X(0x795a820e), + X(0x28e5714b), X(0x794a7c12), X(0x29150fa1), X(0x793a6361), + X(0x2944a7a2), X(0x792a37fe), X(0x29743946), X(0x7919f9ec), + X(0x29a3c485), X(0x7909a92d), X(0x29d34958), X(0x78f945c3), + X(0x2a02c7b8), X(0x78e8cfb2), X(0x2a323f9e), X(0x78d846fb), + X(0x2a61b101), X(0x78c7aba2), X(0x2a911bdc), X(0x78b6fda8), + X(0x2ac08026), X(0x78a63d11), X(0x2aefddd8), X(0x789569df), + X(0x2b1f34eb), X(0x78848414), X(0x2b4e8558), X(0x78738bb3), + X(0x2b7dcf17), X(0x786280bf), X(0x2bad1221), X(0x7851633b), + X(0x2bdc4e6f), X(0x78403329), X(0x2c0b83fa), X(0x782ef08b), + X(0x2c3ab2b9), X(0x781d9b65), X(0x2c69daa6), X(0x780c33b8), + X(0x2c98fbba), X(0x77fab989), X(0x2cc815ee), X(0x77e92cd9), + X(0x2cf72939), X(0x77d78daa), X(0x2d263596), X(0x77c5dc01), + X(0x2d553afc), X(0x77b417df), X(0x2d843964), X(0x77a24148), + X(0x2db330c7), X(0x7790583e), X(0x2de2211e), X(0x777e5cc3), + X(0x2e110a62), X(0x776c4edb), X(0x2e3fec8b), X(0x775a2e89), + X(0x2e6ec792), X(0x7747fbce), X(0x2e9d9b70), X(0x7735b6af), + X(0x2ecc681e), X(0x77235f2d), X(0x2efb2d95), X(0x7710f54c), + X(0x2f29ebcc), X(0x76fe790e), X(0x2f58a2be), X(0x76ebea77), + X(0x2f875262), X(0x76d94989), X(0x2fb5fab2), X(0x76c69647), + X(0x2fe49ba7), X(0x76b3d0b4), X(0x30133539), X(0x76a0f8d2), + X(0x3041c761), X(0x768e0ea6), X(0x30705217), X(0x767b1231), + X(0x309ed556), X(0x76680376), X(0x30cd5115), X(0x7654e279), + X(0x30fbc54d), X(0x7641af3d), X(0x312a31f8), X(0x762e69c4), + X(0x3158970e), X(0x761b1211), X(0x3186f487), X(0x7607a828), + X(0x31b54a5e), X(0x75f42c0b), X(0x31e39889), X(0x75e09dbd), + X(0x3211df04), X(0x75ccfd42), X(0x32401dc6), X(0x75b94a9c), + X(0x326e54c7), X(0x75a585cf), X(0x329c8402), X(0x7591aedd), + X(0x32caab6f), X(0x757dc5ca), X(0x32f8cb07), X(0x7569ca99), + X(0x3326e2c3), X(0x7555bd4c), X(0x3354f29b), X(0x75419de7), + X(0x3382fa88), X(0x752d6c6c), X(0x33b0fa84), X(0x751928e0), + X(0x33def287), X(0x7504d345), X(0x340ce28b), X(0x74f06b9e), + X(0x343aca87), X(0x74dbf1ef), X(0x3468aa76), X(0x74c7663a), + X(0x34968250), X(0x74b2c884), X(0x34c4520d), X(0x749e18cd), + X(0x34f219a8), X(0x7489571c), X(0x351fd918), X(0x74748371), + X(0x354d9057), X(0x745f9dd1), X(0x357b3f5d), X(0x744aa63f), + X(0x35a8e625), X(0x74359cbd), X(0x35d684a6), X(0x74208150), + X(0x36041ad9), X(0x740b53fb), X(0x3631a8b8), X(0x73f614c0), + X(0x365f2e3b), X(0x73e0c3a3), X(0x368cab5c), X(0x73cb60a8), + X(0x36ba2014), X(0x73b5ebd1), X(0x36e78c5b), X(0x73a06522), + X(0x3714f02a), X(0x738acc9e), X(0x37424b7b), X(0x73752249), + X(0x376f9e46), X(0x735f6626), X(0x379ce885), X(0x73499838), + X(0x37ca2a30), X(0x7333b883), X(0x37f76341), X(0x731dc70a), + X(0x382493b0), X(0x7307c3d0), X(0x3851bb77), X(0x72f1aed9), + X(0x387eda8e), X(0x72db8828), X(0x38abf0ef), X(0x72c54fc1), + X(0x38d8fe93), X(0x72af05a7), X(0x39060373), X(0x7298a9dd), + X(0x3932ff87), X(0x72823c67), X(0x395ff2c9), X(0x726bbd48), + X(0x398cdd32), X(0x72552c85), X(0x39b9bebc), X(0x723e8a20), + X(0x39e6975e), X(0x7227d61c), X(0x3a136712), X(0x7211107e), + X(0x3a402dd2), X(0x71fa3949), X(0x3a6ceb96), X(0x71e35080), + X(0x3a99a057), X(0x71cc5626), X(0x3ac64c0f), X(0x71b54a41), + X(0x3af2eeb7), X(0x719e2cd2), X(0x3b1f8848), X(0x7186fdde), + X(0x3b4c18ba), X(0x716fbd68), X(0x3b78a007), X(0x71586b74), + X(0x3ba51e29), X(0x71410805), X(0x3bd19318), X(0x7129931f), + X(0x3bfdfecd), X(0x71120cc5), X(0x3c2a6142), X(0x70fa74fc), + X(0x3c56ba70), X(0x70e2cbc6), X(0x3c830a50), X(0x70cb1128), + X(0x3caf50da), X(0x70b34525), X(0x3cdb8e09), X(0x709b67c0), + X(0x3d07c1d6), X(0x708378ff), X(0x3d33ec39), X(0x706b78e3), + X(0x3d600d2c), X(0x70536771), X(0x3d8c24a8), X(0x703b44ad), + X(0x3db832a6), X(0x7023109a), X(0x3de4371f), X(0x700acb3c), + X(0x3e10320d), X(0x6ff27497), X(0x3e3c2369), X(0x6fda0cae), + X(0x3e680b2c), X(0x6fc19385), X(0x3e93e950), X(0x6fa90921), + X(0x3ebfbdcd), X(0x6f906d84), X(0x3eeb889c), X(0x6f77c0b3), + X(0x3f1749b8), X(0x6f5f02b2), X(0x3f430119), X(0x6f463383), + X(0x3f6eaeb8), X(0x6f2d532c), X(0x3f9a5290), X(0x6f1461b0), + X(0x3fc5ec98), X(0x6efb5f12), X(0x3ff17cca), X(0x6ee24b57), + X(0x401d0321), X(0x6ec92683), X(0x40487f94), X(0x6eaff099), + X(0x4073f21d), X(0x6e96a99d), X(0x409f5ab6), X(0x6e7d5193), + X(0x40cab958), X(0x6e63e87f), X(0x40f60dfb), X(0x6e4a6e66), + X(0x4121589b), X(0x6e30e34a), X(0x414c992f), X(0x6e174730), + X(0x4177cfb1), X(0x6dfd9a1c), X(0x41a2fc1a), X(0x6de3dc11), + X(0x41ce1e65), X(0x6dca0d14), X(0x41f93689), X(0x6db02d29), + X(0x42244481), X(0x6d963c54), X(0x424f4845), X(0x6d7c3a98), + X(0x427a41d0), X(0x6d6227fa), X(0x42a5311b), X(0x6d48047e), + X(0x42d0161e), X(0x6d2dd027), X(0x42faf0d4), X(0x6d138afb), + X(0x4325c135), X(0x6cf934fc), X(0x4350873c), X(0x6cdece2f), + X(0x437b42e1), X(0x6cc45698), X(0x43a5f41e), X(0x6ca9ce3b), + X(0x43d09aed), X(0x6c8f351c), X(0x43fb3746), X(0x6c748b3f), + X(0x4425c923), X(0x6c59d0a9), X(0x4450507e), X(0x6c3f055d), + X(0x447acd50), X(0x6c242960), X(0x44a53f93), X(0x6c093cb6), + X(0x44cfa740), X(0x6bee3f62), X(0x44fa0450), X(0x6bd3316a), + X(0x452456bd), X(0x6bb812d1), X(0x454e9e80), X(0x6b9ce39b), + X(0x4578db93), X(0x6b81a3cd), X(0x45a30df0), X(0x6b66536b), + X(0x45cd358f), X(0x6b4af279), X(0x45f7526b), X(0x6b2f80fb), + X(0x4621647d), X(0x6b13fef5), X(0x464b6bbe), X(0x6af86c6c), + X(0x46756828), X(0x6adcc964), X(0x469f59b4), X(0x6ac115e2), + X(0x46c9405c), X(0x6aa551e9), X(0x46f31c1a), X(0x6a897d7d), + X(0x471cece7), X(0x6a6d98a4), X(0x4746b2bc), X(0x6a51a361), + X(0x47706d93), X(0x6a359db9), X(0x479a1d67), X(0x6a1987b0), + X(0x47c3c22f), X(0x69fd614a), X(0x47ed5be6), X(0x69e12a8c), + X(0x4816ea86), X(0x69c4e37a), X(0x48406e08), X(0x69a88c19), + X(0x4869e665), X(0x698c246c), X(0x48935397), X(0x696fac78), + X(0x48bcb599), X(0x69532442), X(0x48e60c62), X(0x69368bce), + X(0x490f57ee), X(0x6919e320), X(0x49389836), X(0x68fd2a3d), + X(0x4961cd33), X(0x68e06129), X(0x498af6df), X(0x68c387e9), + X(0x49b41533), X(0x68a69e81), X(0x49dd282a), X(0x6889a4f6), + X(0x4a062fbd), X(0x686c9b4b), X(0x4a2f2be6), X(0x684f8186), + X(0x4a581c9e), X(0x683257ab), X(0x4a8101de), X(0x68151dbe), + X(0x4aa9dba2), X(0x67f7d3c5), X(0x4ad2a9e2), X(0x67da79c3), + X(0x4afb6c98), X(0x67bd0fbd), X(0x4b2423be), X(0x679f95b7), + X(0x4b4ccf4d), X(0x67820bb7), X(0x4b756f40), X(0x676471c0), + X(0x4b9e0390), X(0x6746c7d8), X(0x4bc68c36), X(0x67290e02), + X(0x4bef092d), X(0x670b4444), X(0x4c177a6e), X(0x66ed6aa1), + X(0x4c3fdff4), X(0x66cf8120), X(0x4c6839b7), X(0x66b187c3), + X(0x4c9087b1), X(0x66937e91), X(0x4cb8c9dd), X(0x6675658c), + X(0x4ce10034), X(0x66573cbb), X(0x4d092ab0), X(0x66390422), + X(0x4d31494b), X(0x661abbc5), X(0x4d595bfe), X(0x65fc63a9), + X(0x4d8162c4), X(0x65ddfbd3), X(0x4da95d96), X(0x65bf8447), + X(0x4dd14c6e), X(0x65a0fd0b), X(0x4df92f46), X(0x65826622), + X(0x4e210617), X(0x6563bf92), X(0x4e48d0dd), X(0x6545095f), + X(0x4e708f8f), X(0x6526438f), X(0x4e984229), X(0x65076e25), + X(0x4ebfe8a5), X(0x64e88926), X(0x4ee782fb), X(0x64c99498), + X(0x4f0f1126), X(0x64aa907f), X(0x4f369320), X(0x648b7ce0), + X(0x4f5e08e3), X(0x646c59bf), X(0x4f857269), X(0x644d2722), + X(0x4faccfab), X(0x642de50d), X(0x4fd420a4), X(0x640e9386), + X(0x4ffb654d), X(0x63ef3290), X(0x50229da1), X(0x63cfc231), + X(0x5049c999), X(0x63b0426d), X(0x5070e92f), X(0x6390b34a), + X(0x5097fc5e), X(0x637114cc), X(0x50bf031f), X(0x635166f9), + X(0x50e5fd6d), X(0x6331a9d4), X(0x510ceb40), X(0x6311dd64), + X(0x5133cc94), X(0x62f201ac), X(0x515aa162), X(0x62d216b3), + X(0x518169a5), X(0x62b21c7b), X(0x51a82555), X(0x6292130c), + X(0x51ced46e), X(0x6271fa69), X(0x51f576ea), X(0x6251d298), + X(0x521c0cc2), X(0x62319b9d), X(0x524295f0), X(0x6211557e), + X(0x5269126e), X(0x61f1003f), X(0x528f8238), X(0x61d09be5), + X(0x52b5e546), X(0x61b02876), X(0x52dc3b92), X(0x618fa5f7), + X(0x53028518), X(0x616f146c), X(0x5328c1d0), X(0x614e73da), + X(0x534ef1b5), X(0x612dc447), X(0x537514c2), X(0x610d05b7), + X(0x539b2af0), X(0x60ec3830), X(0x53c13439), X(0x60cb5bb7), + X(0x53e73097), X(0x60aa7050), X(0x540d2005), X(0x60897601), + X(0x5433027d), X(0x60686ccf), X(0x5458d7f9), X(0x604754bf), + X(0x547ea073), X(0x60262dd6), X(0x54a45be6), X(0x6004f819), + X(0x54ca0a4b), X(0x5fe3b38d), X(0x54efab9c), X(0x5fc26038), + X(0x55153fd4), X(0x5fa0fe1f), X(0x553ac6ee), X(0x5f7f8d46), + X(0x556040e2), X(0x5f5e0db3), X(0x5585adad), X(0x5f3c7f6b), + X(0x55ab0d46), X(0x5f1ae274), X(0x55d05faa), X(0x5ef936d1), + X(0x55f5a4d2), X(0x5ed77c8a), X(0x561adcb9), X(0x5eb5b3a2), + X(0x56400758), X(0x5e93dc1f), X(0x566524aa), X(0x5e71f606), + X(0x568a34a9), X(0x5e50015d), X(0x56af3750), X(0x5e2dfe29), + X(0x56d42c99), X(0x5e0bec6e), X(0x56f9147e), X(0x5de9cc33), + X(0x571deefa), X(0x5dc79d7c), X(0x5742bc06), X(0x5da5604f), + X(0x57677b9d), X(0x5d8314b1), X(0x578c2dba), X(0x5d60baa7), + X(0x57b0d256), X(0x5d3e5237), X(0x57d5696d), X(0x5d1bdb65), + X(0x57f9f2f8), X(0x5cf95638), X(0x581e6ef1), X(0x5cd6c2b5), + X(0x5842dd54), X(0x5cb420e0), X(0x58673e1b), X(0x5c9170bf), + X(0x588b9140), X(0x5c6eb258), X(0x58afd6bd), X(0x5c4be5b0), + X(0x58d40e8c), X(0x5c290acc), X(0x58f838a9), X(0x5c0621b2), + X(0x591c550e), X(0x5be32a67), X(0x594063b5), X(0x5bc024f0), + X(0x59646498), X(0x5b9d1154), X(0x598857b2), X(0x5b79ef96), + X(0x59ac3cfd), X(0x5b56bfbd), X(0x59d01475), X(0x5b3381ce), + X(0x59f3de12), X(0x5b1035cf), X(0x5a1799d1), X(0x5aecdbc5), + X(0x5a3b47ab), X(0x5ac973b5), X(0x5a5ee79a), X(0x5aa5fda5), + X(0x5a82799a), X(0x5a82799a) + }; + + /* {sin((2*i+1)*PI/4096), cos((2*i+1)*PI/4096)}, with i = 0 to 511 */ +static const LOOKUP_T sincos_lookup1[1024] = { + X(0x001921fb), X(0x7ffffd88), X(0x004b65ee), X(0x7fffe9cb), + X(0x007da9d4), X(0x7fffc251), X(0x00afeda8), X(0x7fff8719), + X(0x00e23160), X(0x7fff3824), X(0x011474f6), X(0x7ffed572), + X(0x0146b860), X(0x7ffe5f03), X(0x0178fb99), X(0x7ffdd4d7), + X(0x01ab3e97), X(0x7ffd36ee), X(0x01dd8154), X(0x7ffc8549), + X(0x020fc3c6), X(0x7ffbbfe6), X(0x024205e8), X(0x7ffae6c7), + X(0x027447b0), X(0x7ff9f9ec), X(0x02a68917), X(0x7ff8f954), + X(0x02d8ca16), X(0x7ff7e500), X(0x030b0aa4), X(0x7ff6bcf0), + X(0x033d4abb), X(0x7ff58125), X(0x036f8a51), X(0x7ff4319d), + X(0x03a1c960), X(0x7ff2ce5b), X(0x03d407df), X(0x7ff1575d), + X(0x040645c7), X(0x7fefcca4), X(0x04388310), X(0x7fee2e30), + X(0x046abfb3), X(0x7fec7c02), X(0x049cfba7), X(0x7feab61a), + X(0x04cf36e5), X(0x7fe8dc78), X(0x05017165), X(0x7fe6ef1c), + X(0x0533ab20), X(0x7fe4ee06), X(0x0565e40d), X(0x7fe2d938), + X(0x05981c26), X(0x7fe0b0b1), X(0x05ca5361), X(0x7fde7471), + X(0x05fc89b8), X(0x7fdc247a), X(0x062ebf22), X(0x7fd9c0ca), + X(0x0660f398), X(0x7fd74964), X(0x06932713), X(0x7fd4be46), + X(0x06c5598a), X(0x7fd21f72), X(0x06f78af6), X(0x7fcf6ce8), + X(0x0729bb4e), X(0x7fcca6a7), X(0x075bea8c), X(0x7fc9ccb2), + X(0x078e18a7), X(0x7fc6df08), X(0x07c04598), X(0x7fc3dda9), + X(0x07f27157), X(0x7fc0c896), X(0x08249bdd), X(0x7fbd9fd0), + X(0x0856c520), X(0x7fba6357), X(0x0888ed1b), X(0x7fb7132b), + X(0x08bb13c5), X(0x7fb3af4e), X(0x08ed3916), X(0x7fb037bf), + X(0x091f5d06), X(0x7facac7f), X(0x09517f8f), X(0x7fa90d8e), + X(0x0983a0a7), X(0x7fa55aee), X(0x09b5c048), X(0x7fa1949e), + X(0x09e7de6a), X(0x7f9dbaa0), X(0x0a19fb04), X(0x7f99ccf4), + X(0x0a4c1610), X(0x7f95cb9a), X(0x0a7e2f85), X(0x7f91b694), + X(0x0ab0475c), X(0x7f8d8de1), X(0x0ae25d8d), X(0x7f895182), + X(0x0b147211), X(0x7f850179), X(0x0b4684df), X(0x7f809dc5), + X(0x0b7895f0), X(0x7f7c2668), X(0x0baaa53b), X(0x7f779b62), + X(0x0bdcb2bb), X(0x7f72fcb4), X(0x0c0ebe66), X(0x7f6e4a5e), + X(0x0c40c835), X(0x7f698461), X(0x0c72d020), X(0x7f64aabf), + X(0x0ca4d620), X(0x7f5fbd77), X(0x0cd6da2d), X(0x7f5abc8a), + X(0x0d08dc3f), X(0x7f55a7fa), X(0x0d3adc4e), X(0x7f507fc7), + X(0x0d6cda53), X(0x7f4b43f2), X(0x0d9ed646), X(0x7f45f47b), + X(0x0dd0d01f), X(0x7f409164), X(0x0e02c7d7), X(0x7f3b1aad), + X(0x0e34bd66), X(0x7f359057), X(0x0e66b0c3), X(0x7f2ff263), + X(0x0e98a1e9), X(0x7f2a40d2), X(0x0eca90ce), X(0x7f247ba5), + X(0x0efc7d6b), X(0x7f1ea2dc), X(0x0f2e67b8), X(0x7f18b679), + X(0x0f604faf), X(0x7f12b67c), X(0x0f923546), X(0x7f0ca2e7), + X(0x0fc41876), X(0x7f067bba), X(0x0ff5f938), X(0x7f0040f6), + X(0x1027d784), X(0x7ef9f29d), X(0x1059b352), X(0x7ef390ae), + X(0x108b8c9b), X(0x7eed1b2c), X(0x10bd6356), X(0x7ee69217), + X(0x10ef377d), X(0x7edff570), X(0x11210907), X(0x7ed94538), + X(0x1152d7ed), X(0x7ed28171), X(0x1184a427), X(0x7ecbaa1a), + X(0x11b66dad), X(0x7ec4bf36), X(0x11e83478), X(0x7ebdc0c6), + X(0x1219f880), X(0x7eb6aeca), X(0x124bb9be), X(0x7eaf8943), + X(0x127d7829), X(0x7ea85033), X(0x12af33ba), X(0x7ea1039b), + X(0x12e0ec6a), X(0x7e99a37c), X(0x1312a230), X(0x7e922fd6), + X(0x13445505), X(0x7e8aa8ac), X(0x137604e2), X(0x7e830dff), + X(0x13a7b1bf), X(0x7e7b5fce), X(0x13d95b93), X(0x7e739e1d), + X(0x140b0258), X(0x7e6bc8eb), X(0x143ca605), X(0x7e63e03b), + X(0x146e4694), X(0x7e5be40c), X(0x149fe3fc), X(0x7e53d462), + X(0x14d17e36), X(0x7e4bb13c), X(0x1503153a), X(0x7e437a9c), + X(0x1534a901), X(0x7e3b3083), X(0x15663982), X(0x7e32d2f4), + X(0x1597c6b7), X(0x7e2a61ed), X(0x15c95097), X(0x7e21dd73), + X(0x15fad71b), X(0x7e194584), X(0x162c5a3b), X(0x7e109a24), + X(0x165dd9f0), X(0x7e07db52), X(0x168f5632), X(0x7dff0911), + X(0x16c0cef9), X(0x7df62362), X(0x16f2443e), X(0x7ded2a47), + X(0x1723b5f9), X(0x7de41dc0), X(0x17552422), X(0x7ddafdce), + X(0x17868eb3), X(0x7dd1ca75), X(0x17b7f5a3), X(0x7dc883b4), + X(0x17e958ea), X(0x7dbf298d), X(0x181ab881), X(0x7db5bc02), + X(0x184c1461), X(0x7dac3b15), X(0x187d6c82), X(0x7da2a6c6), + X(0x18aec0db), X(0x7d98ff17), X(0x18e01167), X(0x7d8f4409), + X(0x19115e1c), X(0x7d85759f), X(0x1942a6f3), X(0x7d7b93da), + X(0x1973ebe6), X(0x7d719eba), X(0x19a52ceb), X(0x7d679642), + X(0x19d669fc), X(0x7d5d7a74), X(0x1a07a311), X(0x7d534b50), + X(0x1a38d823), X(0x7d4908d9), X(0x1a6a0929), X(0x7d3eb30f), + X(0x1a9b361d), X(0x7d3449f5), X(0x1acc5ef6), X(0x7d29cd8c), + X(0x1afd83ad), X(0x7d1f3dd6), X(0x1b2ea43a), X(0x7d149ad5), + X(0x1b5fc097), X(0x7d09e489), X(0x1b90d8bb), X(0x7cff1af5), + X(0x1bc1ec9e), X(0x7cf43e1a), X(0x1bf2fc3a), X(0x7ce94dfb), + X(0x1c240786), X(0x7cde4a98), X(0x1c550e7c), X(0x7cd333f3), + X(0x1c861113), X(0x7cc80a0f), X(0x1cb70f43), X(0x7cbcccec), + X(0x1ce80906), X(0x7cb17c8d), X(0x1d18fe54), X(0x7ca618f3), + X(0x1d49ef26), X(0x7c9aa221), X(0x1d7adb73), X(0x7c8f1817), + X(0x1dabc334), X(0x7c837ad8), X(0x1ddca662), X(0x7c77ca65), + X(0x1e0d84f5), X(0x7c6c06c0), X(0x1e3e5ee5), X(0x7c602fec), + X(0x1e6f342c), X(0x7c5445e9), X(0x1ea004c1), X(0x7c4848ba), + X(0x1ed0d09d), X(0x7c3c3860), X(0x1f0197b8), X(0x7c3014de), + X(0x1f325a0b), X(0x7c23de35), X(0x1f63178f), X(0x7c179467), + X(0x1f93d03c), X(0x7c0b3777), X(0x1fc4840a), X(0x7bfec765), + X(0x1ff532f2), X(0x7bf24434), X(0x2025dcec), X(0x7be5ade6), + X(0x205681f1), X(0x7bd9047c), X(0x208721f9), X(0x7bcc47fa), + X(0x20b7bcfe), X(0x7bbf7860), X(0x20e852f6), X(0x7bb295b0), + X(0x2118e3dc), X(0x7ba59fee), X(0x21496fa7), X(0x7b989719), + X(0x2179f64f), X(0x7b8b7b36), X(0x21aa77cf), X(0x7b7e4c45), + X(0x21daf41d), X(0x7b710a49), X(0x220b6b32), X(0x7b63b543), + X(0x223bdd08), X(0x7b564d36), X(0x226c4996), X(0x7b48d225), + X(0x229cb0d5), X(0x7b3b4410), X(0x22cd12bd), X(0x7b2da2fa), + X(0x22fd6f48), X(0x7b1feee5), X(0x232dc66d), X(0x7b1227d3), + X(0x235e1826), X(0x7b044dc7), X(0x238e646a), X(0x7af660c2), + X(0x23beab33), X(0x7ae860c7), X(0x23eeec78), X(0x7ada4dd8), + X(0x241f2833), X(0x7acc27f7), X(0x244f5e5c), X(0x7abdef25), + X(0x247f8eec), X(0x7aafa367), X(0x24afb9da), X(0x7aa144bc), + X(0x24dfdf20), X(0x7a92d329), X(0x250ffeb7), X(0x7a844eae), + X(0x25401896), X(0x7a75b74f), X(0x25702cb7), X(0x7a670d0d), + X(0x25a03b11), X(0x7a584feb), X(0x25d0439f), X(0x7a497feb), + X(0x26004657), X(0x7a3a9d0f), X(0x26304333), X(0x7a2ba75a), + X(0x26603a2c), X(0x7a1c9ece), X(0x26902b39), X(0x7a0d836d), + X(0x26c01655), X(0x79fe5539), X(0x26effb76), X(0x79ef1436), + X(0x271fda96), X(0x79dfc064), X(0x274fb3ae), X(0x79d059c8), + X(0x277f86b5), X(0x79c0e062), X(0x27af53a6), X(0x79b15435), + X(0x27df1a77), X(0x79a1b545), X(0x280edb23), X(0x79920392), + X(0x283e95a1), X(0x79823f20), X(0x286e49ea), X(0x797267f2), + X(0x289df7f8), X(0x79627e08), X(0x28cd9fc1), X(0x79528167), + X(0x28fd4140), X(0x79427210), X(0x292cdc6d), X(0x79325006), + X(0x295c7140), X(0x79221b4b), X(0x298bffb2), X(0x7911d3e2), + X(0x29bb87bc), X(0x790179cd), X(0x29eb0957), X(0x78f10d0f), + X(0x2a1a847b), X(0x78e08dab), X(0x2a49f920), X(0x78cffba3), + X(0x2a796740), X(0x78bf56f9), X(0x2aa8ced3), X(0x78ae9fb0), + X(0x2ad82fd2), X(0x789dd5cb), X(0x2b078a36), X(0x788cf94c), + X(0x2b36ddf7), X(0x787c0a36), X(0x2b662b0e), X(0x786b088c), + X(0x2b957173), X(0x7859f44f), X(0x2bc4b120), X(0x7848cd83), + X(0x2bf3ea0d), X(0x7837942b), X(0x2c231c33), X(0x78264849), + X(0x2c52478a), X(0x7814e9df), X(0x2c816c0c), X(0x780378f1), + X(0x2cb089b1), X(0x77f1f581), X(0x2cdfa071), X(0x77e05f91), + X(0x2d0eb046), X(0x77ceb725), X(0x2d3db928), X(0x77bcfc3f), + X(0x2d6cbb10), X(0x77ab2ee2), X(0x2d9bb5f6), X(0x77994f11), + X(0x2dcaa9d5), X(0x77875cce), X(0x2df996a3), X(0x7775581d), + X(0x2e287c5a), X(0x776340ff), X(0x2e575af3), X(0x77511778), + X(0x2e863267), X(0x773edb8b), X(0x2eb502ae), X(0x772c8d3a), + X(0x2ee3cbc1), X(0x771a2c88), X(0x2f128d99), X(0x7707b979), + X(0x2f41482e), X(0x76f5340e), X(0x2f6ffb7a), X(0x76e29c4b), + X(0x2f9ea775), X(0x76cff232), X(0x2fcd4c19), X(0x76bd35c7), + X(0x2ffbe95d), X(0x76aa670d), X(0x302a7f3a), X(0x76978605), + X(0x30590dab), X(0x768492b4), X(0x308794a6), X(0x76718d1c), + X(0x30b61426), X(0x765e7540), X(0x30e48c22), X(0x764b4b23), + X(0x3112fc95), X(0x76380ec8), X(0x31416576), X(0x7624c031), + X(0x316fc6be), X(0x76115f63), X(0x319e2067), X(0x75fdec60), + X(0x31cc7269), X(0x75ea672a), X(0x31fabcbd), X(0x75d6cfc5), + X(0x3228ff5c), X(0x75c32634), X(0x32573a3f), X(0x75af6a7b), + X(0x32856d5e), X(0x759b9c9b), X(0x32b398b3), X(0x7587bc98), + X(0x32e1bc36), X(0x7573ca75), X(0x330fd7e1), X(0x755fc635), + X(0x333debab), X(0x754bafdc), X(0x336bf78f), X(0x7537876c), + X(0x3399fb85), X(0x75234ce8), X(0x33c7f785), X(0x750f0054), + X(0x33f5eb89), X(0x74faa1b3), X(0x3423d78a), X(0x74e63108), + X(0x3451bb81), X(0x74d1ae55), X(0x347f9766), X(0x74bd199f), + X(0x34ad6b32), X(0x74a872e8), X(0x34db36df), X(0x7493ba34), + X(0x3508fa66), X(0x747eef85), X(0x3536b5be), X(0x746a12df), + X(0x356468e2), X(0x74552446), X(0x359213c9), X(0x744023bc), + X(0x35bfb66e), X(0x742b1144), X(0x35ed50c9), X(0x7415ece2), + X(0x361ae2d3), X(0x7400b69a), X(0x36486c86), X(0x73eb6e6e), + X(0x3675edd9), X(0x73d61461), X(0x36a366c6), X(0x73c0a878), + X(0x36d0d746), X(0x73ab2ab4), X(0x36fe3f52), X(0x73959b1b), + X(0x372b9ee3), X(0x737ff9ae), X(0x3758f5f2), X(0x736a4671), + X(0x37864477), X(0x73548168), X(0x37b38a6d), X(0x733eaa96), + X(0x37e0c7cc), X(0x7328c1ff), X(0x380dfc8d), X(0x7312c7a5), + X(0x383b28a9), X(0x72fcbb8c), X(0x38684c19), X(0x72e69db7), + X(0x389566d6), X(0x72d06e2b), X(0x38c278d9), X(0x72ba2cea), + X(0x38ef821c), X(0x72a3d9f7), X(0x391c8297), X(0x728d7557), + X(0x39497a43), X(0x7276ff0d), X(0x39766919), X(0x7260771b), + X(0x39a34f13), X(0x7249dd86), X(0x39d02c2a), X(0x72333251), + X(0x39fd0056), X(0x721c7580), X(0x3a29cb91), X(0x7205a716), + X(0x3a568dd4), X(0x71eec716), X(0x3a834717), X(0x71d7d585), + X(0x3aaff755), X(0x71c0d265), X(0x3adc9e86), X(0x71a9bdba), + X(0x3b093ca3), X(0x71929789), X(0x3b35d1a5), X(0x717b5fd3), + X(0x3b625d86), X(0x7164169d), X(0x3b8ee03e), X(0x714cbbeb), + X(0x3bbb59c7), X(0x71354fc0), X(0x3be7ca1a), X(0x711dd220), + X(0x3c143130), X(0x7106430e), X(0x3c408f03), X(0x70eea28e), + X(0x3c6ce38a), X(0x70d6f0a4), X(0x3c992ec0), X(0x70bf2d53), + X(0x3cc5709e), X(0x70a7589f), X(0x3cf1a91c), X(0x708f728b), + X(0x3d1dd835), X(0x70777b1c), X(0x3d49fde1), X(0x705f7255), + X(0x3d761a19), X(0x70475839), X(0x3da22cd7), X(0x702f2ccd), + X(0x3dce3614), X(0x7016f014), X(0x3dfa35c8), X(0x6ffea212), + X(0x3e262bee), X(0x6fe642ca), X(0x3e52187f), X(0x6fcdd241), + X(0x3e7dfb73), X(0x6fb5507a), X(0x3ea9d4c3), X(0x6f9cbd79), + X(0x3ed5a46b), X(0x6f841942), X(0x3f016a61), X(0x6f6b63d8), + X(0x3f2d26a0), X(0x6f529d40), X(0x3f58d921), X(0x6f39c57d), + X(0x3f8481dd), X(0x6f20dc92), X(0x3fb020ce), X(0x6f07e285), + X(0x3fdbb5ec), X(0x6eeed758), X(0x40074132), X(0x6ed5bb10), + X(0x4032c297), X(0x6ebc8db0), X(0x405e3a16), X(0x6ea34f3d), + X(0x4089a7a8), X(0x6e89ffb9), X(0x40b50b46), X(0x6e709f2a), + X(0x40e064ea), X(0x6e572d93), X(0x410bb48c), X(0x6e3daaf8), + X(0x4136fa27), X(0x6e24175c), X(0x416235b2), X(0x6e0a72c5), + X(0x418d6729), X(0x6df0bd35), X(0x41b88e84), X(0x6dd6f6b1), + X(0x41e3abbc), X(0x6dbd1f3c), X(0x420ebecb), X(0x6da336dc), + X(0x4239c7aa), X(0x6d893d93), X(0x4264c653), X(0x6d6f3365), + X(0x428fbabe), X(0x6d551858), X(0x42baa4e6), X(0x6d3aec6e), + X(0x42e584c3), X(0x6d20afac), X(0x43105a50), X(0x6d066215), + X(0x433b2585), X(0x6cec03af), X(0x4365e65b), X(0x6cd1947c), + X(0x43909ccd), X(0x6cb71482), X(0x43bb48d4), X(0x6c9c83c3), + X(0x43e5ea68), X(0x6c81e245), X(0x44108184), X(0x6c67300b), + X(0x443b0e21), X(0x6c4c6d1a), X(0x44659039), X(0x6c319975), + X(0x449007c4), X(0x6c16b521), X(0x44ba74bd), X(0x6bfbc021), + X(0x44e4d71c), X(0x6be0ba7b), X(0x450f2edb), X(0x6bc5a431), + X(0x45397bf4), X(0x6baa7d49), X(0x4563be60), X(0x6b8f45c7), + X(0x458df619), X(0x6b73fdae), X(0x45b82318), X(0x6b58a503), + X(0x45e24556), X(0x6b3d3bcb), X(0x460c5cce), X(0x6b21c208), + X(0x46366978), X(0x6b0637c1), X(0x46606b4e), X(0x6aea9cf8), + X(0x468a624a), X(0x6acef1b2), X(0x46b44e65), X(0x6ab335f4), + X(0x46de2f99), X(0x6a9769c1), X(0x470805df), X(0x6a7b8d1e), + X(0x4731d131), X(0x6a5fa010), X(0x475b9188), X(0x6a43a29a), + X(0x478546de), X(0x6a2794c1), X(0x47aef12c), X(0x6a0b7689), + X(0x47d8906d), X(0x69ef47f6), X(0x48022499), X(0x69d3090e), + X(0x482badab), X(0x69b6b9d3), X(0x48552b9b), X(0x699a5a4c), + X(0x487e9e64), X(0x697dea7b), X(0x48a805ff), X(0x69616a65), + X(0x48d16265), X(0x6944da10), X(0x48fab391), X(0x6928397e), + X(0x4923f97b), X(0x690b88b5), X(0x494d341e), X(0x68eec7b9), + X(0x49766373), X(0x68d1f68f), X(0x499f8774), X(0x68b5153a), + X(0x49c8a01b), X(0x689823bf), X(0x49f1ad61), X(0x687b2224), + X(0x4a1aaf3f), X(0x685e106c), X(0x4a43a5b0), X(0x6840ee9b), + X(0x4a6c90ad), X(0x6823bcb7), X(0x4a957030), X(0x68067ac3), + X(0x4abe4433), X(0x67e928c5), X(0x4ae70caf), X(0x67cbc6c0), + X(0x4b0fc99d), X(0x67ae54ba), X(0x4b387af9), X(0x6790d2b6), + X(0x4b6120bb), X(0x677340ba), X(0x4b89badd), X(0x67559eca), + X(0x4bb24958), X(0x6737ecea), X(0x4bdacc28), X(0x671a2b20), + X(0x4c034345), X(0x66fc596f), X(0x4c2baea9), X(0x66de77dc), + X(0x4c540e4e), X(0x66c0866d), X(0x4c7c622d), X(0x66a28524), + X(0x4ca4aa41), X(0x66847408), X(0x4ccce684), X(0x6666531d), + X(0x4cf516ee), X(0x66482267), X(0x4d1d3b7a), X(0x6629e1ec), + X(0x4d455422), X(0x660b91af), X(0x4d6d60df), X(0x65ed31b5), + X(0x4d9561ac), X(0x65cec204), X(0x4dbd5682), X(0x65b0429f), + X(0x4de53f5a), X(0x6591b38c), X(0x4e0d1c30), X(0x657314cf), + X(0x4e34ecfc), X(0x6554666d), X(0x4e5cb1b9), X(0x6535a86b), + X(0x4e846a60), X(0x6516dacd), X(0x4eac16eb), X(0x64f7fd98), + X(0x4ed3b755), X(0x64d910d1), X(0x4efb4b96), X(0x64ba147d), + X(0x4f22d3aa), X(0x649b08a0), X(0x4f4a4f89), X(0x647bed3f), + X(0x4f71bf2e), X(0x645cc260), X(0x4f992293), X(0x643d8806), + X(0x4fc079b1), X(0x641e3e38), X(0x4fe7c483), X(0x63fee4f8), + X(0x500f0302), X(0x63df7c4d), X(0x50363529), X(0x63c0043b), + X(0x505d5af1), X(0x63a07cc7), X(0x50847454), X(0x6380e5f6), + X(0x50ab814d), X(0x63613fcd), X(0x50d281d5), X(0x63418a50), + X(0x50f975e6), X(0x6321c585), X(0x51205d7b), X(0x6301f171), + X(0x5147388c), X(0x62e20e17), X(0x516e0715), X(0x62c21b7e), + X(0x5194c910), X(0x62a219aa), X(0x51bb7e75), X(0x628208a1), + X(0x51e22740), X(0x6261e866), X(0x5208c36a), X(0x6241b8ff), + X(0x522f52ee), X(0x62217a72), X(0x5255d5c5), X(0x62012cc2), + X(0x527c4bea), X(0x61e0cff5), X(0x52a2b556), X(0x61c06410), + X(0x52c91204), X(0x619fe918), X(0x52ef61ee), X(0x617f5f12), + X(0x5315a50e), X(0x615ec603), X(0x533bdb5d), X(0x613e1df0), + X(0x536204d7), X(0x611d66de), X(0x53882175), X(0x60fca0d2), + X(0x53ae3131), X(0x60dbcbd1), X(0x53d43406), X(0x60bae7e1), + X(0x53fa29ed), X(0x6099f505), X(0x542012e1), X(0x6078f344), + X(0x5445eedb), X(0x6057e2a2), X(0x546bbdd7), X(0x6036c325), + X(0x54917fce), X(0x601594d1), X(0x54b734ba), X(0x5ff457ad), + X(0x54dcdc96), X(0x5fd30bbc), X(0x5502775c), X(0x5fb1b104), + X(0x55280505), X(0x5f90478a), X(0x554d858d), X(0x5f6ecf53), + X(0x5572f8ed), X(0x5f4d4865), X(0x55985f20), X(0x5f2bb2c5), + X(0x55bdb81f), X(0x5f0a0e77), X(0x55e303e6), X(0x5ee85b82), + X(0x5608426e), X(0x5ec699e9), X(0x562d73b2), X(0x5ea4c9b3), + X(0x565297ab), X(0x5e82eae5), X(0x5677ae54), X(0x5e60fd84), + X(0x569cb7a8), X(0x5e3f0194), X(0x56c1b3a1), X(0x5e1cf71c), + X(0x56e6a239), X(0x5dfade20), X(0x570b8369), X(0x5dd8b6a7), + X(0x5730572e), X(0x5db680b4), X(0x57551d80), X(0x5d943c4e), + X(0x5779d65b), X(0x5d71e979), X(0x579e81b8), X(0x5d4f883b), + X(0x57c31f92), X(0x5d2d189a), X(0x57e7afe4), X(0x5d0a9a9a), + X(0x580c32a7), X(0x5ce80e41), X(0x5830a7d6), X(0x5cc57394), + X(0x58550f6c), X(0x5ca2ca99), X(0x58796962), X(0x5c801354), + X(0x589db5b3), X(0x5c5d4dcc), X(0x58c1f45b), X(0x5c3a7a05), + X(0x58e62552), X(0x5c179806), X(0x590a4893), X(0x5bf4a7d2), + X(0x592e5e19), X(0x5bd1a971), X(0x595265df), X(0x5bae9ce7), + X(0x59765fde), X(0x5b8b8239), X(0x599a4c12), X(0x5b68596d), + X(0x59be2a74), X(0x5b452288), X(0x59e1faff), X(0x5b21dd90), + X(0x5a05bdae), X(0x5afe8a8b), X(0x5a29727b), X(0x5adb297d), + X(0x5a4d1960), X(0x5ab7ba6c), X(0x5a70b258), X(0x5a943d5e), +}; + diff --git a/libs/tremor/misc.h b/libs/tremor/misc.h new file mode 100644 index 0000000..ff1b400 --- /dev/null +++ b/libs/tremor/misc.h @@ -0,0 +1,252 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: miscellaneous math and prototypes + + ********************************************************************/ + +#ifndef _V_RANDOM_H_ +#define _V_RANDOM_H_ +#include "ivorbiscodec.h" +#include "os.h" + +#ifdef _LOW_ACCURACY_ +# define X(n) (((((n)>>22)+1)>>1) - ((((n)>>22)+1)>>9)) +# define LOOKUP_T const unsigned char +#else +# define X(n) (n) +# define LOOKUP_T const ogg_int32_t +#endif + +#include "asm_arm.h" +#include /* for abs() */ + +#ifndef _V_WIDE_MATH +#define _V_WIDE_MATH + +#ifndef _LOW_ACCURACY_ +/* 64 bit multiply */ + +#if !(defined WIN32 && defined WINCE) +#include +#endif + +#if BYTE_ORDER==LITTLE_ENDIAN +union magic { + struct { + ogg_int32_t lo; + ogg_int32_t hi; + } halves; + ogg_int64_t whole; +}; +#endif + +/*#if BYTE_ORDER==BIG_ENDIAN +union magic { + struct { + ogg_int32_t hi; + ogg_int32_t lo; + } halves; + ogg_int64_t whole; +}; +#endif*/ + +STIN ogg_int32_t MULT32(ogg_int32_t x, ogg_int32_t y) { + union magic magic; + magic.whole = (ogg_int64_t)x * y; + return magic.halves.hi; +} + +STIN ogg_int32_t MULT31(ogg_int32_t x, ogg_int32_t y) { + return MULT32(x,y)<<1; +} + +STIN ogg_int32_t MULT31_SHIFT15(ogg_int32_t x, ogg_int32_t y) { + union magic magic; + magic.whole = (ogg_int64_t)x * y; + return ((ogg_uint32_t)(magic.halves.lo)>>15) | ((magic.halves.hi)<<17); +} + +#else +/* 32 bit multiply, more portable but less accurate */ + +/* + * Note: Precision is biased towards the first argument therefore ordering + * is important. Shift values were chosen for the best sound quality after + * many listening tests. + */ + +/* + * For MULT32 and MULT31: The second argument is always a lookup table + * value already preshifted from 31 to 8 bits. We therefore take the + * opportunity to save on text space and use unsigned char for those + * tables in this case. + */ + +STIN ogg_int32_t MULT32(ogg_int32_t x, ogg_int32_t y) { + return (x >> 9) * y; /* y preshifted >>23 */ +} + +STIN ogg_int32_t MULT31(ogg_int32_t x, ogg_int32_t y) { + return (x >> 8) * y; /* y preshifted >>23 */ +} + +STIN ogg_int32_t MULT31_SHIFT15(ogg_int32_t x, ogg_int32_t y) { + return (x >> 6) * y; /* y preshifted >>9 */ +} + +#endif + +/* + * This should be used as a memory barrier, forcing all cached values in + * registers to wr writen back to memory. Might or might not be beneficial + * depending on the architecture and compiler. + */ +#define MB() + +/* + * The XPROD functions are meant to optimize the cross products found all + * over the place in mdct.c by forcing memory operation ordering to avoid + * unnecessary register reloads as soon as memory is being written to. + * However this is only beneficial on CPUs with a sane number of general + * purpose registers which exclude the Intel x86. On Intel, better let the + * compiler actually reload registers directly from original memory by using + * macros. + */ + +#ifdef __i386__ + +#define XPROD32(_a, _b, _t, _v, _x, _y) \ + { *(_x)=MULT32(_a,_t)+MULT32(_b,_v); \ + *(_y)=MULT32(_b,_t)-MULT32(_a,_v); } +#define XPROD31(_a, _b, _t, _v, _x, _y) \ + { *(_x)=MULT31(_a,_t)+MULT31(_b,_v); \ + *(_y)=MULT31(_b,_t)-MULT31(_a,_v); } +#define XNPROD31(_a, _b, _t, _v, _x, _y) \ + { *(_x)=MULT31(_a,_t)-MULT31(_b,_v); \ + *(_y)=MULT31(_b,_t)+MULT31(_a,_v); } + +#else + +STIN void XPROD32(ogg_int32_t a, ogg_int32_t b, + ogg_int32_t t, ogg_int32_t v, + ogg_int32_t *x, ogg_int32_t *y) +{ + *x = MULT32(a, t) + MULT32(b, v); + *y = MULT32(b, t) - MULT32(a, v); +} + +STIN void XPROD31(ogg_int32_t a, ogg_int32_t b, + ogg_int32_t t, ogg_int32_t v, + ogg_int32_t *x, ogg_int32_t *y) +{ + *x = MULT31(a, t) + MULT31(b, v); + *y = MULT31(b, t) - MULT31(a, v); +} + +STIN void XNPROD31(ogg_int32_t a, ogg_int32_t b, + ogg_int32_t t, ogg_int32_t v, + ogg_int32_t *x, ogg_int32_t *y) +{ + *x = MULT31(a, t) - MULT31(b, v); + *y = MULT31(b, t) + MULT31(a, v); +} + +#endif + +#endif + +#ifndef _V_CLIP_MATH +#define _V_CLIP_MATH + +STIN ogg_int32_t CLIP_TO_15(ogg_int32_t x) { + int ret=x; + ret-= ((x<=32767)-1)&(x-32767); + ret-= ((x>=-32768)-1)&(x+32768); + return(ret); +} + +#endif + +STIN ogg_int32_t VFLOAT_MULT(ogg_int32_t a,ogg_int32_t ap, + ogg_int32_t b,ogg_int32_t bp, + ogg_int32_t *p){ + if(a && b){ +#ifndef _LOW_ACCURACY_ + *p=ap+bp+32; + return MULT32(a,b); +#else + *p=ap+bp+31; + return (a>>15)*(b>>16); +#endif + }else + return 0; +} + +int _ilog(unsigned int); + +STIN ogg_int32_t VFLOAT_MULTI(ogg_int32_t a,ogg_int32_t ap, + ogg_int32_t i, + ogg_int32_t *p){ + + int ip=_ilog(abs(i))-31; + return VFLOAT_MULT(a,ap,i<<-ip,ip,p); +} + +STIN ogg_int32_t VFLOAT_ADD(ogg_int32_t a,ogg_int32_t ap, + ogg_int32_t b,ogg_int32_t bp, + ogg_int32_t *p){ + + if(!a){ + *p=bp; + return b; + }else if(!b){ + *p=ap; + return a; + } + + /* yes, this can leak a bit. */ + if(ap>bp){ + int shift=ap-bp+1; + *p=ap+1; + a>>=1; + if(shift<32){ + b=(b+(1<<(shift-1)))>>shift; + }else{ + b=0; + } + }else{ + int shift=bp-ap+1; + *p=bp+1; + b>>=1; + if(shift<32){ + a=(a+(1<<(shift-1)))>>shift; + }else{ + a=0; + } + } + + a+=b; + if((a&0xc0000000)==0xc0000000 || + (a&0xc0000000)==0){ + a<<=1; + (*p)--; + } + return(a); +} + +#endif + + + + diff --git a/libs/tremor/os.h b/libs/tremor/os.h new file mode 100644 index 0000000..130d27d --- /dev/null +++ b/libs/tremor/os.h @@ -0,0 +1,64 @@ +#ifndef _OS_H +#define _OS_H +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: #ifdef jail to whip a few platforms into the UNIX ideal. + + ********************************************************************/ + +#include +#include + +#ifndef _V_IFDEFJAIL_H_ +# define _V_IFDEFJAIL_H_ + +# ifdef __GNUC__ +# define STIN static __inline__ +# elif _WIN32 +# define STIN static __inline +# endif +#else +# define STIN static +#endif + +#ifndef M_PI +# define M_PI (3.1415926536f) +#endif + +#ifdef _WIN32 +# include +# define rint(x) (floor((x)+0.5f)) +# define NO_FLOAT_MATH_LIB +# define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b)) +# define LITTLE_ENDIAN 1 +# define BYTE_ORDER LITTLE_ENDIAN +#endif + +#ifdef HAVE_ALLOCA_H +# include +#endif + +#ifdef USE_MEMORY_H +# include +#endif + +#ifndef min +# define min(x,y) ((x)>(y)?(y):(x)) +#endif + +#ifndef max +# define max(x,y) ((x)<(y)?(y):(x)) +#endif + +#endif /* _OS_H */ diff --git a/libs/tremor/registry.c b/libs/tremor/registry.c new file mode 100644 index 0000000..c0b5fec --- /dev/null +++ b/libs/tremor/registry.c @@ -0,0 +1,50 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: registry for floor, res backends and channel mappings + + ********************************************************************/ + +#include "ivorbiscodec.h" +#include "codec_internal.h" +#include "registry.h" +#include "misc.h" + + +/* seems like major overkill now; the backend numbers will grow into + the infrastructure soon enough */ + +extern vorbis_func_floor floor0_exportbundle; +extern vorbis_func_floor floor1_exportbundle; +extern vorbis_func_residue residue0_exportbundle; +extern vorbis_func_residue residue1_exportbundle; +extern vorbis_func_residue residue2_exportbundle; +extern vorbis_func_mapping mapping0_exportbundle; + +vorbis_func_floor *_floor_P[]={ + &floor0_exportbundle, + &floor1_exportbundle, +}; + +vorbis_func_residue *_residue_P[]={ + &residue0_exportbundle, + &residue1_exportbundle, + &residue2_exportbundle, +}; + +vorbis_func_mapping *_mapping_P[]={ + &mapping0_exportbundle, +}; + + + diff --git a/libs/tremor/registry.h b/libs/tremor/registry.h new file mode 100644 index 0000000..2bc8068 --- /dev/null +++ b/libs/tremor/registry.h @@ -0,0 +1,40 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: registry for time, floor, res backends and channel mappings + + ********************************************************************/ + +#ifndef _V_REG_H_ +#define _V_REG_H_ + +#define VI_TRANSFORMB 1 +#define VI_WINDOWB 1 +#define VI_TIMEB 1 +#define VI_FLOORB 2 +#define VI_RESB 3 +#define VI_MAPB 1 + +#include "backends.h" + +#if defined(_WIN32) && defined(VORBISDLL_IMPORT) +# define EXTERN __declspec(dllimport) extern +#else +# define EXTERN extern +#endif + +EXTERN vorbis_func_floor *_floor_P[]; +EXTERN vorbis_func_residue *_residue_P[]; +EXTERN vorbis_func_mapping *_mapping_P[]; + +#endif diff --git a/libs/tremor/res012.c b/libs/tremor/res012.c new file mode 100644 index 0000000..f036caa --- /dev/null +++ b/libs/tremor/res012.c @@ -0,0 +1,374 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: residue backend 0, 1 and 2 implementation + + ********************************************************************/ + +#include +#include +#include +#include +#include "ivorbiscodec.h" +#include "codec_internal.h" +#include "registry.h" +#include "codebook.h" +#include "misc.h" +#include "os.h" +#include "block.h" + +typedef struct { + vorbis_info_residue0 *info; + int map; + + int parts; + int stages; + codebook *fullbooks; + codebook *phrasebook; + codebook ***partbooks; + + int partvals; + int **decodemap; + +} vorbis_look_residue0; + +void res0_free_info(vorbis_info_residue *i){ + vorbis_info_residue0 *info=(vorbis_info_residue0 *)i; + if(info){ + memset(info,0,sizeof(*info)); + _ogg_free(info); + } +} + +void res0_free_look(vorbis_look_residue *i){ + int j; + if(i){ + + vorbis_look_residue0 *look=(vorbis_look_residue0 *)i; + + for(j=0;jparts;j++) + if(look->partbooks[j])_ogg_free(look->partbooks[j]); + _ogg_free(look->partbooks); + for(j=0;jpartvals;j++) + _ogg_free(look->decodemap[j]); + _ogg_free(look->decodemap); + + memset(look,0,sizeof(*look)); + _ogg_free(look); + } +} + +static int ilog(unsigned int v){ + int ret=0; + while(v){ + ret++; + v>>=1; + } + return(ret); +} + +static int icount(unsigned int v){ + int ret=0; + while(v){ + ret+=v&1; + v>>=1; + } + return(ret); +} + +/* vorbis_info is for range checking */ +vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){ + int j,acc=0; + vorbis_info_residue0 *info=(vorbis_info_residue0 *)_ogg_calloc(1,sizeof(*info)); + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + + info->begin=oggpack_read(opb,24); + info->end=oggpack_read(opb,24); + info->grouping=oggpack_read(opb,24)+1; + info->partitions=oggpack_read(opb,6)+1; + info->groupbook=oggpack_read(opb,8); + + /* check for premature EOP */ + if(info->groupbook<0)goto errout; + + for(j=0;jpartitions;j++){ + int cascade=oggpack_read(opb,3); + int cflag=oggpack_read(opb,1); + if(cflag<0) goto errout; + if(cflag){ + int c=oggpack_read(opb,5); + if(c<0) goto errout; + cascade|=(c<<3); + } + info->secondstages[j]=cascade; + + acc+=icount(cascade); + } + for(j=0;jbooklist[j]=book; + } + + if(info->groupbook>=ci->books)goto errout; + for(j=0;jbooklist[j]>=ci->books)goto errout; + if(ci->book_param[info->booklist[j]]->maptype==0)goto errout; + } + + /* verify the phrasebook is not specifying an impossible or + inconsistent partitioning scheme. */ + /* modify the phrasebook ranging check from r16327; an early beta + encoder had a bug where it used an oversized phrasebook by + accident. These files should continue to be playable, but don't + allow an exploit */ + { + int entries = ci->book_param[info->groupbook]->entries; + int dim = ci->book_param[info->groupbook]->dim; + int partvals = 1; + if (dim<1) goto errout; + while(dim>0){ + partvals *= info->partitions; + if(partvals > entries) goto errout; + dim--; + } + info->partvals = partvals; + } + + return(info); + errout: + res0_free_info(info); + return(NULL); +} + +vorbis_look_residue *res0_look(vorbis_dsp_state *vd,vorbis_info_mode *vm, + vorbis_info_residue *vr){ + vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr; + vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look)); + codec_setup_info *ci=(codec_setup_info *)vd->vi->codec_setup; + + int j,k,acc=0; + int dim; + int maxstage=0; + look->info=info; + look->map=vm->mapping; + + look->parts=info->partitions; + look->fullbooks=ci->fullbooks; + look->phrasebook=ci->fullbooks+info->groupbook; + dim=look->phrasebook->dim; + + look->partbooks=(codebook ***)_ogg_calloc(look->parts,sizeof(*look->partbooks)); + + for(j=0;jparts;j++){ + int stages=ilog(info->secondstages[j]); + if(stages){ + if(stages>maxstage)maxstage=stages; + look->partbooks[j]=(codebook **)_ogg_calloc(stages,sizeof(*look->partbooks[j])); + for(k=0;ksecondstages[j]&(1<partbooks[j][k]=ci->fullbooks+info->booklist[acc++]; +#ifdef TRAIN_RES + look->training_data[k][j]=calloc(look->partbooks[j][k]->entries, + sizeof(***look->training_data)); +#endif + } + } + } + + look->partvals=look->parts; + for(j=1;jpartvals*=look->parts; + look->stages=maxstage; + look->decodemap=(int **)_ogg_malloc(look->partvals*sizeof(*look->decodemap)); + for(j=0;jpartvals;j++){ + long val=j; + long mult=look->partvals/look->parts; + look->decodemap[j]=(int *)_ogg_malloc(dim*sizeof(*look->decodemap[j])); + for(k=0;kparts; + look->decodemap[j][k]=deco; + } + } + + return(look); +} + + +/* a truncated packet here just means 'stop working'; it's not an error */ +static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl, + ogg_int32_t **in,int ch, + long (*decodepart)(codebook *, ogg_int32_t *, + oggpack_buffer *,int,int)){ + + long i,j,k,l,s; + vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl; + vorbis_info_residue0 *info=look->info; + + /* move all this setup out later */ + int samples_per_partition=info->grouping; + int partitions_per_word=look->phrasebook->dim; + int max=vb->pcmend>>1; + int end=(info->endend:max); + int n=end-info->begin; + + if(n>0){ + int partvals=n/samples_per_partition; + int partwords=(partvals+partitions_per_word-1)/partitions_per_word; + int ***partword=(int ***)alloca(ch*sizeof(*partword)); + + for(j=0;jstages;s++){ + + /* each loop decodes on partition codeword containing + partitions_pre_word partitions */ + for(i=0,l=0;iphrasebook,&vb->opb); + if(temp==-1 || temp>=info->partvals)goto eopbreak; + partword[j][l]=look->decodemap[temp]; + if(partword[j][l]==NULL)goto errout; + } + } + + /* now we decode residual values for the partitions */ + for(k=0;kbegin+i*samples_per_partition; + if(info->secondstages[partword[j][l][k]]&(1<partbooks[partword[j][l][k]][s]; + if(stagebook){ + if(decodepart(stagebook,in[j]+offset,&vb->opb, + samples_per_partition,-8)==-1)goto eopbreak; + } + } + } + } + } + } + errout: + eopbreak: + return(0); +} + +int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl, + ogg_int32_t **in,int *nonzero,int ch){ + int i,used=0; + for(i=0;iinfo; + + /* move all this setup out later */ + int samples_per_partition=info->grouping; + int partitions_per_word=look->phrasebook->dim; + int max=(vb->pcmend*ch)>>1; + int end=(info->endend:max); + int n=end-info->begin; + + if(n>0){ + + int partvals=n/samples_per_partition; + int partwords=(partvals+partitions_per_word-1)/partitions_per_word; + int **partword=(int **)_vorbis_block_alloc(vb,partwords*sizeof(*partword)); + int beginoff=info->begin/ch; + + for(i=0;istages;s++){ + for(i=0,l=0;iphrasebook,&vb->opb); + if(temp==-1 || temp>=info->partvals)goto eopbreak; + partword[l]=look->decodemap[temp]; + if(partword[l]==NULL)goto errout; + } + + /* now we decode residual values for the partitions */ + for(k=0;ksecondstages[partword[l][k]]&(1<partbooks[partword[l][k]][s]; + + if(stagebook){ + if(vorbis_book_decodevv_add(stagebook,in, + i*samples_per_partition+beginoff,ch, + &vb->opb, + samples_per_partition,-8)==-1) + goto eopbreak; + } + } + } + } + } + errout: + eopbreak: + return(0); +} + + +vorbis_func_residue residue0_exportbundle={ + &res0_unpack, + &res0_look, + &res0_free_info, + &res0_free_look, + &res0_inverse +}; + +vorbis_func_residue residue1_exportbundle={ + &res0_unpack, + &res0_look, + &res0_free_info, + &res0_free_look, + &res1_inverse +}; + +vorbis_func_residue residue2_exportbundle={ + &res0_unpack, + &res0_look, + &res0_free_info, + &res0_free_look, + &res2_inverse +}; diff --git a/libs/tremor/sharedbook.c b/libs/tremor/sharedbook.c new file mode 100644 index 0000000..188485e --- /dev/null +++ b/libs/tremor/sharedbook.c @@ -0,0 +1,447 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: basic shared codebook operations + + ********************************************************************/ + +#include +#include +#include +#include +#include "misc.h" +#include "ivorbiscodec.h" +#include "codebook.h" + +/**** pack/unpack helpers ******************************************/ +int _ilog(unsigned int v){ + int ret=0; + while(v){ + ret++; + v>>=1; + } + return(ret); +} + +/* 32 bit float (not IEEE; nonnormalized mantissa + + biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm + Why not IEEE? It's just not that important here. */ + +#define VQ_FEXP 10 +#define VQ_FMAN 21 +#define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */ + +static ogg_int32_t _float32_unpack(long val,int *point){ + long mant=val&0x1fffff; + int sign=val&0x80000000; + long exp =(val&0x7fe00000L)>>VQ_FMAN; + + exp-=(VQ_FMAN-1)+VQ_FEXP_BIAS; + + if(mant){ + while(!(mant&0x40000000)){ + mant<<=1; + exp-=1; + } + + if(sign)mant= -mant; + }else{ + sign=0; + exp=-9999; + } + + *point=exp; + return mant; +} + +/* given a list of word lengths, generate a list of codewords. Works + for length ordered or unordered, always assigns the lowest valued + codewords first. Extended to handle unused entries (length 0) */ +ogg_uint32_t *_make_words(long *l,long n,long sparsecount){ + long i,j,count=0; + ogg_uint32_t marker[33]; + ogg_uint32_t *r=(ogg_uint32_t *)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r)); + memset(marker,0,sizeof(marker)); + + for(i=0;i0){ + ogg_uint32_t entry=marker[length]; + + /* when we claim a node for an entry, we also claim the nodes + below it (pruning off the imagined tree that may have dangled + from it) as well as blocking the use of any nodes directly + above for leaves */ + + /* update ourself */ + if(length<32 && (entry>>length)){ + /* error condition; the lengths must specify an overpopulated tree */ + _ogg_free(r); + return(NULL); + } + r[count++]=entry; + + /* Look to see if the next shorter marker points to the node + above. if so, update it and repeat. */ + { + for(j=length;j>0;j--){ + + if(marker[j]&1){ + /* have to jump branches */ + if(j==1) + marker[1]++; + else + marker[j]=marker[j-1]<<1; + break; /* invariant says next upper marker would already + have been moved if it was on the same path */ + } + marker[j]++; + } + } + + /* prune the tree; the implicit invariant says all the longer + markers were dangling from our just-taken node. Dangle them + from our *new* node. */ + for(j=length+1;j<33;j++) + if((marker[j]>>1) == entry){ + entry=marker[j]; + marker[j]=marker[j-1]<<1; + }else + break; + }else + if(sparsecount==0)count++; + } + + /* sanity check the huffman tree; an underpopulated tree must be + rejected. The only exception is the one-node pseudo-nil tree, + which appears to be underpopulated because the tree doesn't + really exist; there's only one possible 'codeword' or zero bits, + but the above tree-gen code doesn't mark that. */ + if(sparsecount != 1){ + for(i=1;i<33;i++) + if(marker[i] & (0xffffffffUL>>(32-i))){ + _ogg_free(r); + return(NULL); + } + } + + /* bitreverse the words because our bitwise packer/unpacker is LSb + endian */ + for(i=0,count=0;i>j)&1; + } + + if(sparsecount){ + if(l[i]) + r[count++]=temp; + }else + r[count++]=temp; + } + + return(r); +} + +/* there might be a straightforward one-line way to do the below + that's portable and totally safe against roundoff, but I haven't + thought of it. Therefore, we opt on the side of caution */ +long _book_maptype1_quantvals(const static_codebook *b){ + /* get us a starting hint, we'll polish it below */ + int bits=_ilog(b->entries); + int vals=b->entries>>((bits-1)*(b->dim-1)/b->dim); + + while(1){ + long acc=1; + long acc1=1; + int i; + for(i=0;idim;i++){ + acc*=vals; + acc1*=vals+1; + } + if(acc<=b->entries && acc1>b->entries){ + return(vals); + }else{ + if(acc>b->entries){ + vals--; + }else{ + vals++; + } + } + } +} + +/* different than what _book_unquantize does for mainline: + we repack the book in a fixed point format that shares the same + binary point. Upon first use, we can shift point if needed */ + +/* we need to deal with two map types: in map type 1, the values are + generated algorithmically (each column of the vector counts through + the values in the quant vector). in map type 2, all the values came + in in an explicit list. Both value lists must be unpacked */ + +ogg_int32_t *_book_unquantize(const static_codebook *b,int n,int *sparsemap, + int *maxpoint){ + long j,k,count=0; + if(b->maptype==1 || b->maptype==2){ + int quantvals; + int minpoint,delpoint; + ogg_int32_t mindel=_float32_unpack(b->q_min,&minpoint); + ogg_int32_t delta=_float32_unpack(b->q_delta,&delpoint); + ogg_int32_t *r=(ogg_int32_t *)_ogg_calloc(n*b->dim,sizeof(*r)); + int *rp=(int *)_ogg_calloc(n*b->dim,sizeof(*rp)); + + *maxpoint=minpoint; + + /* maptype 1 and 2 both use a quantized value vector, but + different sizes */ + switch(b->maptype){ + case 1: + /* most of the time, entries%dimensions == 0, but we need to be + well defined. We define that the possible vales at each + scalar is values == entries/dim. If entries%dim != 0, we'll + have 'too few' values (values*dimentries;j++){ + if((sparsemap && b->lengthlist[j]) || !sparsemap){ + ogg_int32_t last=0; + int lastpoint=0; + int indexdiv=1; + for(k=0;kdim;k++){ + int index= (j/indexdiv)%quantvals; + int point=0; + int val=VFLOAT_MULTI(delta,delpoint, + abs(b->quantlist[index]),&point); + + val=VFLOAT_ADD(mindel,minpoint,val,point,&point); + val=VFLOAT_ADD(last,lastpoint,val,point,&point); + + if(b->q_sequencep){ + last=val; + lastpoint=point; + } + + if(sparsemap){ + r[sparsemap[count]*b->dim+k]=val; + rp[sparsemap[count]*b->dim+k]=point; + }else{ + r[count*b->dim+k]=val; + rp[count*b->dim+k]=point; + } + if(*maxpointentries;j++){ + if((sparsemap && b->lengthlist[j]) || !sparsemap){ + ogg_int32_t last=0; + int lastpoint=0; + + for(k=0;kdim;k++){ + int point=0; + int val=VFLOAT_MULTI(delta,delpoint, + abs(b->quantlist[j*b->dim+k]),&point); + + val=VFLOAT_ADD(mindel,minpoint,val,point,&point); + val=VFLOAT_ADD(last,lastpoint,val,point,&point); + + if(b->q_sequencep){ + last=val; + lastpoint=point; + } + + if(sparsemap){ + r[sparsemap[count]*b->dim+k]=val; + rp[sparsemap[count]*b->dim+k]=point; + }else{ + r[count*b->dim+k]=val; + rp[count*b->dim+k]=point; + } + if(*maxpointdim;j++) + if(rp[j]<*maxpoint) + r[j]>>=*maxpoint-rp[j]; + + _ogg_free(rp); + return(r); + } + return(NULL); +} + +void vorbis_staticbook_destroy(static_codebook *b){ + if(b->quantlist)_ogg_free(b->quantlist); + if(b->lengthlist)_ogg_free(b->lengthlist); + memset(b,0,sizeof(*b)); + _ogg_free(b); +} + +void vorbis_book_clear(codebook *b){ + /* static book is not cleared; we're likely called on the lookup and + the static codebook belongs to the info struct */ + if(b->valuelist)_ogg_free(b->valuelist); + if(b->codelist)_ogg_free(b->codelist); + + if(b->dec_index)_ogg_free(b->dec_index); + if(b->dec_codelengths)_ogg_free(b->dec_codelengths); + if(b->dec_firsttable)_ogg_free(b->dec_firsttable); + + memset(b,0,sizeof(*b)); +} + +static ogg_uint32_t bitreverse(ogg_uint32_t x){ + x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL); + x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL); + x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL); + x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL); + return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL); +} + +static int sort32a(const void *a,const void *b){ + return (**(ogg_uint32_t **)a>**(ogg_uint32_t **)b)- + (**(ogg_uint32_t **)a<**(ogg_uint32_t **)b); +} + +/* decode codebook arrangement is more heavily optimized than encode */ +int vorbis_book_init_decode(codebook *c,const static_codebook *s){ + int i,j,n=0,tabn; + int *sortindex; + memset(c,0,sizeof(*c)); + + /* count actually used entries */ + for(i=0;ientries;i++) + if(s->lengthlist[i]>0) + n++; + + c->entries=s->entries; + c->used_entries=n; + c->dim=s->dim; + + if(n>0){ + /* two different remappings go on here. + + First, we collapse the likely sparse codebook down only to + actually represented values/words. This collapsing needs to be + indexed as map-valueless books are used to encode original entry + positions as integers. + + Second, we reorder all vectors, including the entry index above, + by sorted bitreversed codeword to allow treeless decode. */ + + /* perform sort */ + ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries); + ogg_uint32_t **codep=(ogg_uint32_t **)alloca(sizeof(*codep)*n); + + if(codes==NULL)goto err_out; + + for(i=0;icodelist=(ogg_uint32_t *)_ogg_malloc(n*sizeof(*c->codelist)); + /* the index is a reverse index */ + for(i=0;icodelist[sortindex[i]]=codes[i]; + _ogg_free(codes); + + + + c->valuelist=_book_unquantize(s,n,sortindex,&c->binarypoint); + c->dec_index=(int *)_ogg_malloc(n*sizeof(*c->dec_index)); + + for(n=0,i=0;ientries;i++) + if(s->lengthlist[i]>0) + c->dec_index[sortindex[n++]]=i; + + c->dec_codelengths=(char *)_ogg_malloc(n*sizeof(*c->dec_codelengths)); + for(n=0,i=0;ientries;i++) + if(s->lengthlist[i]>0) + c->dec_codelengths[sortindex[n++]]=s->lengthlist[i]; + + c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */ + if(c->dec_firsttablen<5)c->dec_firsttablen=5; + if(c->dec_firsttablen>8)c->dec_firsttablen=8; + + tabn=1<dec_firsttablen; + c->dec_firsttable=(ogg_uint32_t *)_ogg_calloc(tabn,sizeof(*c->dec_firsttable)); + c->dec_maxlength=0; + + for(i=0;idec_maxlengthdec_codelengths[i]) + c->dec_maxlength=c->dec_codelengths[i]; + if(c->dec_codelengths[i]<=c->dec_firsttablen){ + ogg_uint32_t orig=bitreverse(c->codelist[i]); + for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++) + c->dec_firsttable[orig|(j<dec_codelengths[i])]=i+1; + } + } + + /* now fill in 'unused' entries in the firsttable with hi/lo search + hints for the non-direct-hits */ + { + ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen); + long lo=0,hi=0; + + for(i=0;idec_firsttablen); + if(c->dec_firsttable[bitreverse(word)]==0){ + while((lo+1)codelist[lo+1]<=word)lo++; + while( hi=(c->codelist[hi]&mask))hi++; + + /* we only actually have 15 bits per hint to play with here. + In order to overflow gracefully (nothing breaks, efficiency + just drops), encode as the difference from the extremes. */ + { + unsigned long loval=lo; + unsigned long hival=n-hi; + + if(loval>0x7fff)loval=0x7fff; + if(hival>0x7fff)hival=0x7fff; + c->dec_firsttable[bitreverse(word)]= + 0x80000000UL | (loval<<15) | hival; + } + } + } + } + } + + return(0); + err_out: + vorbis_book_clear(c); + return(-1); +} + diff --git a/libs/tremor/synthesis.c b/libs/tremor/synthesis.c new file mode 100644 index 0000000..d22cb82 --- /dev/null +++ b/libs/tremor/synthesis.c @@ -0,0 +1,131 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2003 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: single-block PCM synthesis + last mod: $Id: synthesis.c,v 1.4 2003/03/29 03:07:21 xiphmont Exp $ + + ********************************************************************/ + +#include +#include +#include "ivorbiscodec.h" +#include "codec_internal.h" +#include "registry.h" +#include "misc.h" +#include "block.h" + +static int _vorbis_synthesis1(vorbis_block *vb,ogg_packet *op,int decodep){ + vorbis_dsp_state *vd= vb ? vb->vd : 0; + private_state *b= vd ? (private_state *)vd->backend_state: 0; + vorbis_info *vi= vd ? vd->vi : 0; + codec_setup_info *ci= vi ? (codec_setup_info *)vi->codec_setup : 0; + oggpack_buffer *opb=vb ? &vb->opb : 0; + int type,mode,i; + + if (!vd || !b || !vi || !ci || !opb) { + return OV_EBADPACKET; + } + + /* first things first. Make sure decode is ready */ + _vorbis_block_ripcord(vb); + oggpack_readinit(opb,op->packet,op->bytes); + + /* Check the packet type */ + if(oggpack_read(opb,1)!=0){ + /* Oops. This is not an audio data packet */ + return(OV_ENOTAUDIO); + } + + /* read our mode and pre/post windowsize */ + mode=oggpack_read(opb,b->modebits); + if(mode==-1)return(OV_EBADPACKET); + + vb->mode=mode; + if(!ci->mode_param[mode]){ + return(OV_EBADPACKET); + } + + vb->W=ci->mode_param[mode]->blockflag; + if(vb->W){ + vb->lW=oggpack_read(opb,1); + vb->nW=oggpack_read(opb,1); + if(vb->nW==-1) return(OV_EBADPACKET); + }else{ + vb->lW=0; + vb->nW=0; + } + + /* more setup */ + vb->granulepos=op->granulepos; + vb->sequence=op->packetno; /* first block is third packet */ + vb->eofflag=op->e_o_s; + + if(decodep){ + /* alloc pcm passback storage */ + vb->pcmend=ci->blocksizes[vb->W]; + vb->pcm=(ogg_int32_t **)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels); + for(i=0;ichannels;i++) + vb->pcm[i]=(ogg_int32_t *)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i])); + + /* unpack_header enforces range checking */ + type=ci->map_type[ci->mode_param[mode]->mapping]; + + return(_mapping_P[type]->inverse(vb,b->mode[mode])); + }else{ + /* no pcm */ + vb->pcmend=0; + vb->pcm=NULL; + + return(0); + } +} + +int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){ + return _vorbis_synthesis1(vb,op,1); +} + +/* used to track pcm position without actually performing decode. + Useful for sequential 'fast forward' */ +int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){ + return _vorbis_synthesis1(vb,op,0); +} + +long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){ + codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; + oggpack_buffer opb; + int mode; + + oggpack_readinit(&opb,op->packet,op->bytes); + + /* Check the packet type */ + if(oggpack_read(&opb,1)!=0){ + /* Oops. This is not an audio data packet */ + return(OV_ENOTAUDIO); + } + + { + int modebits=0; + int v=ci->modes; + while(v>1){ + modebits++; + v>>=1; + } + + /* read our mode and pre/post windowsize */ + mode=oggpack_read(&opb,modebits); + } + if(mode==-1 || !ci->mode_param[mode])return(OV_EBADPACKET); + return(ci->blocksizes[ci->mode_param[mode]->blockflag]); +} + + diff --git a/libs/tremor/vorbisfile.c b/libs/tremor/vorbisfile.c new file mode 100644 index 0000000..cd4814d --- /dev/null +++ b/libs/tremor/vorbisfile.c @@ -0,0 +1,1968 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2014 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: stdio-based convenience library for opening/seeking/decoding + last mod: $Id$ + + ********************************************************************/ + +#include +#include +#include +#include +#include + +#include "ivorbiscodec.h" +#include "ivorbisfile.h" + +#include "os.h" +#include "misc.h" + +/* A 'chained bitstream' is a Vorbis bitstream that contains more than + one logical bitstream arranged end to end (the only form of Ogg + multiplexing allowed in a Vorbis bitstream; grouping [parallel + multiplexing] is not allowed in Vorbis) */ + +/* A Vorbis file can be played beginning to end (streamed) without + worrying ahead of time about chaining (see decoder_example.c). If + we have the whole file, however, and want random access + (seeking/scrubbing) or desire to know the total length/time of a + file, we need to account for the possibility of chaining. */ + +/* We can handle things a number of ways; we can determine the entire + bitstream structure right off the bat, or find pieces on demand. + This example determines and caches structure for the entire + bitstream, but builds a virtual decoder on the fly when moving + between links in the chain. */ + +/* There are also different ways to implement seeking. Enough + information exists in an Ogg bitstream to seek to + sample-granularity positions in the output. Or, one can seek by + picking some portion of the stream roughly in the desired area if + we only want coarse navigation through the stream. */ + +/************************************************************************* + * Many, many internal helpers. The intention is not to be confusing; + * rampant duplication and monolithic function implementation would be + * harder to understand anyway. The high level functions are last. Begin + * grokking near the end of the file */ + + +/* read a little more data from the file/pipe into the ogg_sync framer */ +static long _get_data(OggVorbis_File *vf){ + errno=0; + if(!(vf->callbacks.read_func))return(-1); + if(vf->datasource){ + char *buffer=ogg_sync_buffer(&vf->oy,READSIZE); + long bytes=(vf->callbacks.read_func)(buffer,1,READSIZE,vf->datasource); + if(bytes>0)ogg_sync_wrote(&vf->oy,bytes); + if(bytes==0 && errno)return(-1); + return(bytes); + }else + return(0); +} + +/* save a tiny smidge of verbosity to make the code more readable */ +static int _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){ + if(vf->datasource){ + /* only seek if the file position isn't already there */ + if(vf->offset != offset){ + if(!(vf->callbacks.seek_func)|| + (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET) == -1) + return OV_EREAD; + vf->offset=offset; + ogg_sync_reset(&vf->oy); + } + }else{ + /* shouldn't happen unless someone writes a broken callback */ + return OV_EFAULT; + } + return 0; +} + +/* The read/seek functions track absolute position within the stream */ + +/* from the head of the stream, get the next page. boundary specifies + if the function is allowed to fetch more data from the stream (and + how much) or only use internally buffered data. + + boundary: -1) unbounded search + 0) read no additional data; use cached only + n) search for a new page beginning for n bytes + + return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD) + n) found a page at absolute offset n */ + +static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og, + ogg_int64_t boundary){ + if(boundary>0)boundary+=vf->offset; + while(1){ + long more; + + if(boundary>0 && vf->offset>=boundary)return(OV_FALSE); + more=ogg_sync_pageseek(&vf->oy,og); + + if(more<0){ + /* skipped n bytes */ + vf->offset-=more; + }else{ + if(more==0){ + /* send more paramedics */ + if(!boundary)return(OV_FALSE); + { + long ret=_get_data(vf); + if(ret==0)return(OV_EOF); + if(ret<0)return(OV_EREAD); + } + }else{ + /* got a page. Return the offset at the page beginning, + advance the internal offset past the page end */ + ogg_int64_t ret=vf->offset; + vf->offset+=more; + return(ret); + + } + } + } +} + +/* find the latest page beginning before the passed in position. Much + dirtier than the above as Ogg doesn't have any backward search + linkage. no 'readp' as it will certainly have to read. */ +/* returns offset or OV_EREAD, OV_FAULT */ +static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_int64_t begin,ogg_page *og){ + ogg_int64_t end = begin; + ogg_int64_t ret; + ogg_int64_t offset=-1; + + while(offset==-1){ + begin-=CHUNKSIZE; + if(begin<0) + begin=0; + + ret=_seek_helper(vf,begin); + if(ret)return(ret); + + while(vf->offsetoffset); + if(ret==OV_EREAD)return(OV_EREAD); + if(ret<0){ + break; + }else{ + offset=ret; + } + } + } + + /* In a fully compliant, non-multiplexed stream, we'll still be + holding the last page. In multiplexed (or noncompliant streams), + we will probably have to re-read the last page we saw */ + if(og->header_len==0){ + ret=_seek_helper(vf,offset); + if(ret)return(ret); + + ret=_get_next_page(vf,og,CHUNKSIZE); + if(ret<0) + /* this shouldn't be possible */ + return(OV_EFAULT); + } + + return(offset); +} + +static void _add_serialno(ogg_page *og,ogg_uint32_t **serialno_list, int *n){ + ogg_uint32_t s = ogg_page_serialno(og); + (*n)++; + + if(*serialno_list){ + *serialno_list = _ogg_realloc(*serialno_list, sizeof(**serialno_list)*(*n)); + }else{ + *serialno_list = _ogg_malloc(sizeof(**serialno_list)); + } + + (*serialno_list)[(*n)-1] = s; +} + +/* returns nonzero if found */ +static int _lookup_serialno(ogg_uint32_t s, ogg_uint32_t *serialno_list, int n){ + if(serialno_list){ + while(n--){ + if(*serialno_list == s) return 1; + serialno_list++; + } + } + return 0; +} + +static int _lookup_page_serialno(ogg_page *og, ogg_uint32_t *serialno_list, int n){ + ogg_uint32_t s = ogg_page_serialno(og); + return _lookup_serialno(s,serialno_list,n); +} + +/* performs the same search as _get_prev_page, but prefers pages of + the specified serial number. If a page of the specified serialno is + spotted during the seek-back-and-read-forward, it will return the + info of last page of the matching serial number instead of the very + last page. If no page of the specified serialno is seen, it will + return the info of last page and alter *serialno. */ +static ogg_int64_t _get_prev_page_serial(OggVorbis_File *vf, ogg_int64_t begin, + ogg_uint32_t *serial_list, int serial_n, + int *serialno, ogg_int64_t *granpos){ + ogg_page og; + ogg_int64_t end=begin; + ogg_int64_t ret; + + ogg_int64_t prefoffset=-1; + ogg_int64_t offset=-1; + ogg_int64_t ret_serialno=-1; + ogg_int64_t ret_gran=-1; + + while(offset==-1){ + begin-=CHUNKSIZE; + if(begin<0) + begin=0; + + ret=_seek_helper(vf,begin); + if(ret)return(ret); + + while(vf->offsetoffset); + if(ret==OV_EREAD)return(OV_EREAD); + if(ret<0){ + break; + }else{ + ret_serialno=ogg_page_serialno(&og); + ret_gran=ogg_page_granulepos(&og); + offset=ret; + + if((ogg_uint32_t)ret_serialno == *serialno){ + prefoffset=ret; + *granpos=ret_gran; + } + + if(!_lookup_serialno((ogg_uint32_t)ret_serialno,serial_list,serial_n)){ + /* we fell off the end of the link, which means we seeked + back too far and shouldn't have been looking in that link + to begin with. If we found the preferred serial number, + forget that we saw it. */ + prefoffset=-1; + } + } + } + } + + /* we're not interested in the page... just the serialno and granpos. */ + if(prefoffset>=0)return(prefoffset); + + *serialno = ret_serialno; + *granpos = ret_gran; + return(offset); + +} + +/* uses the local ogg_stream storage in vf; this is important for + non-streaming input sources */ +static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc, + ogg_uint32_t **serialno_list, int *serialno_n, + ogg_page *og_ptr){ + ogg_page og; + ogg_packet op; + int i,ret; + int allbos=0; + + if(!og_ptr){ + ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE); + if(llret==OV_EREAD)return(OV_EREAD); + if(llret<0)return(OV_ENOTVORBIS); + og_ptr=&og; + } + + vorbis_info_init(vi); + vorbis_comment_init(vc); + vf->ready_state=OPENED; + + /* extract the serialnos of all BOS pages + the first set of vorbis + headers we see in the link */ + + while(ogg_page_bos(og_ptr)){ + if(serialno_list){ + if(_lookup_page_serialno(og_ptr,*serialno_list,*serialno_n)){ + /* a dupe serialnumber in an initial header packet set == invalid stream */ + if(*serialno_list)_ogg_free(*serialno_list); + *serialno_list=0; + *serialno_n=0; + ret=OV_EBADHEADER; + goto bail_header; + } + + _add_serialno(og_ptr,serialno_list,serialno_n); + } + + if(vf->ready_stateos,ogg_page_serialno(og_ptr)); + ogg_stream_pagein(&vf->os,og_ptr); + + if(ogg_stream_packetout(&vf->os,&op) > 0 && + vorbis_synthesis_idheader(&op)){ + /* vorbis header; continue setup */ + vf->ready_state=STREAMSET; + if((ret=vorbis_synthesis_headerin(vi,vc,&op))){ + ret=OV_EBADHEADER; + goto bail_header; + } + } + } + + /* get next page */ + { + ogg_int64_t llret=_get_next_page(vf,og_ptr,CHUNKSIZE); + if(llret==OV_EREAD){ + ret=OV_EREAD; + goto bail_header; + } + if(llret<0){ + ret=OV_ENOTVORBIS; + goto bail_header; + } + + /* if this page also belongs to our vorbis stream, submit it and break */ + if(vf->ready_state==STREAMSET && + vf->os.serialno == ogg_page_serialno(og_ptr)){ + ogg_stream_pagein(&vf->os,og_ptr); + break; + } + } + } + + if(vf->ready_state!=STREAMSET){ + ret = OV_ENOTVORBIS; + goto bail_header; + } + + while(1){ + + i=0; + while(i<2){ /* get a page loop */ + + while(i<2){ /* get a packet loop */ + + int result=ogg_stream_packetout(&vf->os,&op); + if(result==0)break; + if(result==-1){ + ret=OV_EBADHEADER; + goto bail_header; + } + + if((ret=vorbis_synthesis_headerin(vi,vc,&op))) + goto bail_header; + + i++; + } + + while(i<2){ + if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){ + ret=OV_EBADHEADER; + goto bail_header; + } + + /* if this page belongs to the correct stream, go parse it */ + if(vf->os.serialno == ogg_page_serialno(og_ptr)){ + ogg_stream_pagein(&vf->os,og_ptr); + break; + } + + /* if we never see the final vorbis headers before the link + ends, abort */ + if(ogg_page_bos(og_ptr)){ + if(allbos){ + ret = OV_EBADHEADER; + goto bail_header; + }else + allbos=1; + } + + /* otherwise, keep looking */ + } + } + + return 0; + } + + bail_header: + vorbis_info_clear(vi); + vorbis_comment_clear(vc); + vf->ready_state=OPENED; + + return ret; +} + +/* Starting from current cursor position, get initial PCM offset of + next page. Consumes the page in the process without decoding + audio, however this is only called during stream parsing upon + seekable open. */ +static ogg_int64_t _initial_pcmoffset(OggVorbis_File *vf, vorbis_info *vi){ + ogg_page og; + ogg_int64_t accumulated=0; + long lastblock=-1; + int result; + int serialno = vf->os.serialno; + + while(1){ + ogg_packet op; + if(_get_next_page(vf,&og,-1)<0) + break; /* should not be possible unless the file is truncated/mangled */ + + if(ogg_page_bos(&og)) break; + if(ogg_page_serialno(&og)!=serialno) continue; + + /* count blocksizes of all frames in the page */ + ogg_stream_pagein(&vf->os,&og); + while((result=ogg_stream_packetout(&vf->os,&op))){ + if(result>0){ /* ignore holes */ + long thisblock=vorbis_packet_blocksize(vi,&op); + if(lastblock!=-1) + accumulated+=(lastblock+thisblock)>>2; + lastblock=thisblock; + } + } + + if(ogg_page_granulepos(&og)!=-1){ + /* pcm offset of last packet on the first audio page */ + accumulated= ogg_page_granulepos(&og)-accumulated; + break; + } + } + + /* less than zero? This is a stream with samples trimmed off + the beginning, a normal occurrence; set the offset to zero */ + if(accumulated<0)accumulated=0; + + return accumulated; +} + +/* finds each bitstream link one at a time using a bisection search + (has to begin by knowing the offset of the lb's initial page). + Recurses for each link so it can alloc the link storage after + finding them all, then unroll and fill the cache at the same time */ +static int _bisect_forward_serialno(OggVorbis_File *vf, + ogg_int64_t begin, + ogg_int64_t searched, + ogg_int64_t end, + ogg_int64_t endgran, + int endserial, + ogg_uint32_t *currentno_list, + int currentnos, + long m){ + ogg_int64_t pcmoffset; + ogg_int64_t dataoffset=searched; + ogg_int64_t endsearched=end; + ogg_int64_t next=end; + ogg_int64_t searchgran=-1; + ogg_page og; + ogg_int64_t ret,last; + int serialno = vf->os.serialno; + + /* invariants: + we have the headers and serialnos for the link beginning at 'begin' + we have the offset and granpos of the last page in the file (potentially + not a page we care about) + */ + + /* Is the last page in our list of current serialnumbers? */ + if(_lookup_serialno(endserial,currentno_list,currentnos)){ + + /* last page is in the starting serialno list, so we've bisected + down to (or just started with) a single link. Now we need to + find the last vorbis page belonging to the first vorbis stream + for this link. */ + searched = end; + while(endserial != serialno){ + endserial = serialno; + searched=_get_prev_page_serial(vf,searched,currentno_list,currentnos,&endserial,&endgran); + } + + vf->links=m+1; + if(vf->offsets)_ogg_free(vf->offsets); + if(vf->serialnos)_ogg_free(vf->serialnos); + if(vf->dataoffsets)_ogg_free(vf->dataoffsets); + + vf->offsets=_ogg_malloc((vf->links+1)*sizeof(*vf->offsets)); + vf->vi=_ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi)); + vf->vc=_ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc)); + vf->serialnos=_ogg_malloc(vf->links*sizeof(*vf->serialnos)); + vf->dataoffsets=_ogg_malloc(vf->links*sizeof(*vf->dataoffsets)); + vf->pcmlengths=_ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths)); + + vf->offsets[m+1]=end; + vf->offsets[m]=begin; + vf->pcmlengths[m*2+1]=(endgran<0?0:endgran); + + }else{ + + /* last page is not in the starting stream's serial number list, + so we have multiple links. Find where the stream that begins + our bisection ends. */ + + ogg_uint32_t *next_serialno_list=NULL; + int next_serialnos=0; + vorbis_info vi; + vorbis_comment vc; + int testserial = serialno+1; + + /* the below guards against garbage seperating the last and + first pages of two links. */ + while(searched=0)next=last; + }else{ + searched=vf->offset; + } + } + + /* Bisection point found */ + /* for the time being, fetch end PCM offset the simple way */ + searched = next; + while(testserial != serialno){ + testserial = serialno; + searched = _get_prev_page_serial(vf,searched,currentno_list,currentnos,&testserial,&searchgran); + } + + ret=_seek_helper(vf,next); + if(ret)return(ret); + + ret=_fetch_headers(vf,&vi,&vc,&next_serialno_list,&next_serialnos,NULL); + if(ret)return(ret); + serialno = vf->os.serialno; + dataoffset = vf->offset; + + /* this will consume a page, however the next bisection always + starts with a raw seek */ + pcmoffset = _initial_pcmoffset(vf,&vi); + + ret=_bisect_forward_serialno(vf,next,vf->offset,end,endgran,endserial, + next_serialno_list,next_serialnos,m+1); + if(ret)return(ret); + + if(next_serialno_list)_ogg_free(next_serialno_list); + + vf->offsets[m+1]=next; + vf->serialnos[m+1]=serialno; + vf->dataoffsets[m+1]=dataoffset; + + vf->vi[m+1]=vi; + vf->vc[m+1]=vc; + + vf->pcmlengths[m*2+1]=searchgran; + vf->pcmlengths[m*2+2]=pcmoffset; + vf->pcmlengths[m*2+3]-=pcmoffset; + if(vf->pcmlengths[m*2+3]<0)vf->pcmlengths[m*2+3]=0; + + } + return(0); +} + +static int _make_decode_ready(OggVorbis_File *vf){ + if(vf->ready_state>STREAMSET)return 0; + if(vf->ready_stateseekable){ + if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link)) + return OV_EBADLINK; + }else{ + if(vorbis_synthesis_init(&vf->vd,vf->vi)) + return OV_EBADLINK; + } + vorbis_block_init(&vf->vd,&vf->vb); + vf->ready_state=INITSET; + vf->bittrack=0; + vf->samptrack=0; + return 0; +} + +static int _open_seekable2(OggVorbis_File *vf){ + ogg_int64_t dataoffset=vf->dataoffsets[0],end,endgran=-1; + int endserial=vf->os.serialno; + int serialno=vf->os.serialno; + + /* we're partially open and have a first link header state in + storage in vf */ + + /* fetch initial PCM offset */ + ogg_int64_t pcmoffset = _initial_pcmoffset(vf,vf->vi); + + /* we can seek, so set out learning all about this file */ + if(vf->callbacks.seek_func && vf->callbacks.tell_func){ + (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END); + vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource); + }else{ + vf->offset=vf->end=-1; + } + + /* If seek_func is implemented, tell_func must also be implemented */ + if(vf->end==-1) return(OV_EINVAL); + + /* Get the offset of the last page of the physical bitstream, or, if + we're lucky the last vorbis page of this link as most OggVorbis + files will contain a single logical bitstream */ + end=_get_prev_page_serial(vf,vf->end,vf->serialnos+2,vf->serialnos[1],&endserial,&endgran); + if(end<0)return(end); + + /* now determine bitstream structure recursively */ + if(_bisect_forward_serialno(vf,0,dataoffset,end,endgran,endserial, + vf->serialnos+2,vf->serialnos[1],0)<0)return(OV_EREAD); + + vf->offsets[0]=0; + vf->serialnos[0]=serialno; + vf->dataoffsets[0]=dataoffset; + vf->pcmlengths[0]=pcmoffset; + vf->pcmlengths[1]-=pcmoffset; + if(vf->pcmlengths[1]<0)vf->pcmlengths[1]=0; + + return(ov_raw_seek(vf,dataoffset)); +} + +/* clear out the current logical bitstream decoder */ +static void _decode_clear(OggVorbis_File *vf){ + vorbis_dsp_clear(&vf->vd); + vorbis_block_clear(&vf->vb); + vf->ready_state=OPENED; +} + +/* fetch and process a packet. Handles the case where we're at a + bitstream boundary and dumps the decoding machine. If the decoding + machine is unloaded, it loads it. It also keeps pcm_offset up to + date (seek and read both use this. seek uses a special hack with + readp). + + return: <0) error, OV_HOLE (lost packet) or OV_EOF + 0) need more data (only if readp==0) + 1) got a packet +*/ + +static int _fetch_and_process_packet(OggVorbis_File *vf, + ogg_packet *op_in, + int readp, + int spanp){ + ogg_page og; + + /* handle one packet. Try to fetch it from current stream state */ + /* extract packets from page */ + while(1){ + + if(vf->ready_state==STREAMSET){ + int ret=_make_decode_ready(vf); + if(ret<0)return ret; + } + + /* process a packet if we can. If the machine isn't loaded, + neither is a page */ + if(vf->ready_state==INITSET){ + while(1) { + ogg_packet op; + ogg_packet *op_ptr=(op_in?op_in:&op); + int result=ogg_stream_packetout(&vf->os,op_ptr); + ogg_int64_t granulepos; + + op_in=NULL; + if(result==-1)return(OV_HOLE); /* hole in the data. */ + if(result>0){ + /* got a packet. process it */ + granulepos=op_ptr->granulepos; + if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy + header handling. The + header packets aren't + audio, so if/when we + submit them, + vorbis_synthesis will + reject them */ + + /* suck in the synthesis data and track bitrate */ + { + int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL); + /* for proper use of libvorbis within libvorbisfile, + oldsamples will always be zero. */ + if(oldsamples)return(OV_EFAULT); + + vorbis_synthesis_blockin(&vf->vd,&vf->vb); + vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL); + vf->bittrack+=op_ptr->bytes*8; + } + + /* update the pcm offset. */ + if(granulepos!=-1 && !op_ptr->e_o_s){ + int link=(vf->seekable?vf->current_link:0); + int i,samples; + + /* this packet has a pcm_offset on it (the last packet + completed on a page carries the offset) After processing + (above), we know the pcm position of the *last* sample + ready to be returned. Find the offset of the *first* + + As an aside, this trick is inaccurate if we begin + reading anew right at the last page; the end-of-stream + granulepos declares the last frame in the stream, and the + last packet of the last page may be a partial frame. + So, we need a previous granulepos from an in-sequence page + to have a reference point. Thus the !op_ptr->e_o_s clause + above */ + + if(vf->seekable && link>0) + granulepos-=vf->pcmlengths[link*2]; + if(granulepos<0)granulepos=0; /* actually, this + shouldn't be possible + here unless the stream + is very broken */ + + samples=vorbis_synthesis_pcmout(&vf->vd,NULL); + + granulepos-=samples; + for(i=0;ipcmlengths[i*2+1]; + vf->pcm_offset=granulepos; + } + return(1); + } + } + else + break; + } + } + + if(vf->ready_state>=OPENED){ + ogg_int64_t ret; + + while(1){ + /* the loop is not strictly necessary, but there's no sense in + doing the extra checks of the larger loop for the common + case in a multiplexed bistream where the page is simply + part of a different logical bitstream; keep reading until + we get one with the correct serialno */ + + if(!readp)return(0); + if((ret=_get_next_page(vf,&og,-1))<0){ + return(OV_EOF); /* eof. leave unitialized */ + } + + /* bitrate tracking; add the header's bytes here, the body bytes + are done by packet above */ + vf->bittrack+=og.header_len*8; + + if(vf->ready_state==INITSET){ + if(vf->current_serialno!=ogg_page_serialno(&og)){ + + /* two possibilities: + 1) our decoding just traversed a bitstream boundary + 2) another stream is multiplexed into this logical section */ + + if(ogg_page_bos(&og)){ + /* boundary case */ + if(!spanp) + return(OV_EOF); + + _decode_clear(vf); + + if(!vf->seekable){ + vorbis_info_clear(vf->vi); + vorbis_comment_clear(vf->vc); + } + break; + + }else + continue; /* possibility #2 */ + } + } + + break; + } + } + + /* Do we need to load a new machine before submitting the page? */ + /* This is different in the seekable and non-seekable cases. + + In the seekable case, we already have all the header + information loaded and cached; we just initialize the machine + with it and continue on our merry way. + + In the non-seekable (streaming) case, we'll only be at a + boundary if we just left the previous logical bitstream and + we're now nominally at the header of the next bitstream + */ + + if(vf->ready_state!=INITSET){ + int link; + + if(vf->ready_stateseekable){ + ogg_uint32_t serialno = ogg_page_serialno(&og); + + /* match the serialno to bitstream section. We use this rather than + offset positions to avoid problems near logical bitstream + boundaries */ + + for(link=0;linklinks;link++) + if(vf->serialnos[link]==serialno)break; + + if(link==vf->links) continue; /* not the desired Vorbis + bitstream section; keep + trying */ + + vf->current_serialno=serialno; + vf->current_link=link; + + ogg_stream_reset_serialno(&vf->os,vf->current_serialno); + vf->ready_state=STREAMSET; + + }else{ + /* we're streaming */ + /* fetch the three header packets, build the info struct */ + + int ret=_fetch_headers(vf,vf->vi,vf->vc,NULL,NULL,&og); + if(ret)return(ret); + vf->current_serialno=vf->os.serialno; + vf->current_link++; + link=0; + } + } + } + + /* the buffered page is the data we want, and we're ready for it; + add it to the stream state */ + ogg_stream_pagein(&vf->os,&og); + + } +} + +/* if, eg, 64 bit stdio is configured by default, this will build with + fseek64 */ +static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){ + if(f==NULL)return(-1); + return fseek(f,off,whence); +} + +static int _ov_open1(void *f,OggVorbis_File *vf,const char *initial, + long ibytes, ov_callbacks callbacks){ + int offsettest=((f && callbacks.seek_func)?callbacks.seek_func(f,0,SEEK_CUR):-1); + ogg_uint32_t *serialno_list=NULL; + int serialno_list_size=0; + int ret; + + memset(vf,0,sizeof(*vf)); + vf->datasource=f; + vf->callbacks = callbacks; + + /* init the framing state */ + ogg_sync_init(&vf->oy); + + /* perhaps some data was previously read into a buffer for testing + against other stream types. Allow initialization from this + previously read data (especially as we may be reading from a + non-seekable stream) */ + if(initial){ + char *buffer=ogg_sync_buffer(&vf->oy,ibytes); + memcpy(buffer,initial,ibytes); + ogg_sync_wrote(&vf->oy,ibytes); + } + + /* can we seek? Stevens suggests the seek test was portable */ + if(offsettest!=-1)vf->seekable=1; + + /* No seeking yet; Set up a 'single' (current) logical bitstream + entry for partial open */ + vf->links=1; + vf->vi=_ogg_calloc(vf->links,sizeof(*vf->vi)); + vf->vc=_ogg_calloc(vf->links,sizeof(*vf->vc)); + ogg_stream_init(&vf->os,-1); /* fill in the serialno later */ + + /* Fetch all BOS pages, store the vorbis header and all seen serial + numbers, load subsequent vorbis setup headers */ + if((ret=_fetch_headers(vf,vf->vi,vf->vc,&serialno_list,&serialno_list_size,NULL))<0){ + vf->datasource=NULL; + ov_clear(vf); + }else{ + /* serial number list for first link needs to be held somewhere + for second stage of seekable stream open; this saves having to + seek/reread first link's serialnumber data then. */ + vf->serialnos=_ogg_calloc(serialno_list_size+2,sizeof(*vf->serialnos)); + vf->serialnos[0]=vf->current_serialno=vf->os.serialno; + vf->serialnos[1]=serialno_list_size; + memcpy(vf->serialnos+2,serialno_list,serialno_list_size*sizeof(*vf->serialnos)); + + vf->offsets=_ogg_calloc(1,sizeof(*vf->offsets)); + vf->dataoffsets=_ogg_calloc(1,sizeof(*vf->dataoffsets)); + vf->offsets[0]=0; + vf->dataoffsets[0]=vf->offset; + + vf->ready_state=PARTOPEN; + } + if(serialno_list)_ogg_free(serialno_list); + return(ret); +} + +static int _ov_open2(OggVorbis_File *vf){ + if(vf->ready_state != PARTOPEN) return OV_EINVAL; + vf->ready_state=OPENED; + if(vf->seekable){ + int ret=_open_seekable2(vf); + if(ret){ + vf->datasource=NULL; + ov_clear(vf); + } + return(ret); + }else + vf->ready_state=STREAMSET; + + return 0; +} + + +/* clear out the OggVorbis_File struct */ +int ov_clear(OggVorbis_File *vf){ + if(vf){ + vorbis_block_clear(&vf->vb); + vorbis_dsp_clear(&vf->vd); + ogg_stream_clear(&vf->os); + + if(vf->vi && vf->links){ + int i; + for(i=0;ilinks;i++){ + vorbis_info_clear(vf->vi+i); + vorbis_comment_clear(vf->vc+i); + } + _ogg_free(vf->vi); + _ogg_free(vf->vc); + } + if(vf->dataoffsets)_ogg_free(vf->dataoffsets); + if(vf->pcmlengths)_ogg_free(vf->pcmlengths); + if(vf->serialnos)_ogg_free(vf->serialnos); + if(vf->offsets)_ogg_free(vf->offsets); + ogg_sync_clear(&vf->oy); + if(vf->datasource && vf->callbacks.close_func) + (vf->callbacks.close_func)(vf->datasource); + memset(vf,0,sizeof(*vf)); + } +#ifdef DEBUG_LEAKS + _VDBG_dump(); +#endif + return(0); +} + +/* inspects the OggVorbis file and finds/documents all the logical + bitstreams contained in it. Tries to be tolerant of logical + bitstream sections that are truncated/woogie. + + return: -1) error + 0) OK +*/ + +int ov_open_callbacks(void *f,OggVorbis_File *vf, + const char *initial,long ibytes,ov_callbacks callbacks){ + int ret=_ov_open1(f,vf,initial,ibytes,callbacks); + if(ret)return ret; + return _ov_open2(vf); +} + +int ov_open(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes){ + ov_callbacks callbacks = { + (size_t (*)(void *, size_t, size_t, void *)) fread, + (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap, + (int (*)(void *)) fclose, + (long (*)(void *)) ftell + }; + + return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks); +} + +int ov_fopen(const char *path,OggVorbis_File *vf){ + int ret; + FILE *f = fopen(path,"rb"); + if(!f) return -1; + + ret = ov_open(f,vf,NULL,0); + if(ret) fclose(f); + return ret; +} + + +/* Only partially open the vorbis file; test for Vorbisness, and load + the headers for the first chain. Do not seek (although test for + seekability). Use ov_test_open to finish opening the file, else + ov_clear to close/free it. Same return codes as open. */ + +int ov_test_callbacks(void *f,OggVorbis_File *vf, + const char *initial,long ibytes,ov_callbacks callbacks) +{ + return _ov_open1(f,vf,initial,ibytes,callbacks); +} + +int ov_test(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes){ + ov_callbacks callbacks = { + (size_t (*)(void *, size_t, size_t, void *)) fread, + (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap, + (int (*)(void *)) fclose, + (long (*)(void *)) ftell + }; + + return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks); +} + +int ov_test_open(OggVorbis_File *vf){ + if(vf->ready_state!=PARTOPEN)return(OV_EINVAL); + return _ov_open2(vf); +} + +/* How many logical bitstreams in this physical bitstream? */ +long ov_streams(OggVorbis_File *vf){ + return vf->links; +} + +/* Is the FILE * associated with vf seekable? */ +long ov_seekable(OggVorbis_File *vf){ + return vf->seekable; +} + +/* returns the bitrate for a given logical bitstream or the entire + physical bitstream. If the file is open for random access, it will + find the *actual* average bitrate. If the file is streaming, it + returns the nominal bitrate (if set) else the average of the + upper/lower bounds (if set) else -1 (unset). + + If you want the actual bitrate field settings, get them from the + vorbis_info structs */ + +long ov_bitrate(OggVorbis_File *vf,int i){ + if(vf->ready_state=vf->links)return(OV_EINVAL); + if(!vf->seekable && i!=0)return(ov_bitrate(vf,0)); + if(i<0){ + ogg_int64_t bits=0; + int i; + for(i=0;ilinks;i++) + bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8; + /* This once read: return(rint(bits/ov_time_total(vf,-1))); + * gcc 3.x on x86 miscompiled this at optimisation level 2 and above, + * so this is slightly transformed to make it work. + */ + return(bits*1000/ov_time_total(vf,-1)); + }else{ + if(vf->seekable){ + /* return the actual bitrate */ + return((vf->offsets[i+1]-vf->dataoffsets[i])*8000/ov_time_total(vf,i)); + }else{ + /* return nominal if set */ + if(vf->vi[i].bitrate_nominal>0){ + return vf->vi[i].bitrate_nominal; + }else{ + if(vf->vi[i].bitrate_upper>0){ + if(vf->vi[i].bitrate_lower>0){ + return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2; + }else{ + return vf->vi[i].bitrate_upper; + } + } + return(OV_FALSE); + } + } + } +} + +/* returns the actual bitrate since last call. returns -1 if no + additional data to offer since last call (or at beginning of stream), + EINVAL if stream is only partially open +*/ +long ov_bitrate_instant(OggVorbis_File *vf){ + int link=(vf->seekable?vf->current_link:0); + long ret; + if(vf->ready_statesamptrack==0)return(OV_FALSE); + ret=vf->bittrack/vf->samptrack*vf->vi[link].rate; + vf->bittrack=0; + vf->samptrack=0; + return(ret); +} + +/* Guess */ +long ov_serialnumber(OggVorbis_File *vf,int i){ + if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1)); + if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1)); + if(i<0){ + return(vf->current_serialno); + }else{ + return(vf->serialnos[i]); + } +} + +/* returns: total raw (compressed) length of content if i==-1 + raw (compressed) length of that logical bitstream for i==0 to n + OV_EINVAL if the stream is not seekable (we can't know the length) + or if stream is only partially open +*/ +ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){ + if(vf->ready_stateseekable || i>=vf->links)return(OV_EINVAL); + if(i<0){ + ogg_int64_t acc=0; + int i; + for(i=0;ilinks;i++) + acc+=ov_raw_total(vf,i); + return(acc); + }else{ + return(vf->offsets[i+1]-vf->offsets[i]); + } +} + +/* returns: total PCM length (samples) of content if i==-1 PCM length + (samples) of that logical bitstream for i==0 to n + OV_EINVAL if the stream is not seekable (we can't know the + length) or only partially open +*/ +ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){ + if(vf->ready_stateseekable || i>=vf->links)return(OV_EINVAL); + if(i<0){ + ogg_int64_t acc=0; + int i; + for(i=0;ilinks;i++) + acc+=ov_pcm_total(vf,i); + return(acc); + }else{ + return(vf->pcmlengths[i*2+1]); + } +} + +/* returns: total milliseconds of content if i==-1 + milliseconds in that logical bitstream for i==0 to n + OV_EINVAL if the stream is not seekable (we can't know the + length) or only partially open +*/ +ogg_int64_t ov_time_total(OggVorbis_File *vf,int i){ + if(vf->ready_stateseekable || i>=vf->links)return(OV_EINVAL); + if(i<0){ + ogg_int64_t acc=0; + int i; + for(i=0;ilinks;i++) + acc+=ov_time_total(vf,i); + return(acc); + }else{ + return(((ogg_int64_t)vf->pcmlengths[i*2+1])*1000/vf->vi[i].rate); + } +} + +/* seek to an offset relative to the *compressed* data. This also + scans packets to update the PCM cursor. It will cross a logical + bitstream boundary, but only if it can't get any packets out of the + tail of the bitstream we seek to (so no surprises). + + returns zero on success, nonzero on failure */ + +int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){ + ogg_stream_state work_os; + int ret; + + if(vf->ready_stateseekable) + return(OV_ENOSEEK); /* don't dump machine if we can't seek */ + + if(pos<0 || pos>vf->end)return(OV_EINVAL); + + /* is the seek position outside our current link [if any]? */ + if(vf->ready_state>=STREAMSET){ + if(posoffsets[vf->current_link] || pos>=vf->offsets[vf->current_link+1]) + _decode_clear(vf); /* clear out stream state */ + } + + /* don't yet clear out decoding machine (if it's initialized), in + the case we're in the same link. Restart the decode lapping, and + let _fetch_and_process_packet deal with a potential bitstream + boundary */ + vf->pcm_offset=-1; + ogg_stream_reset_serialno(&vf->os, + vf->current_serialno); /* must set serialno */ + vorbis_synthesis_restart(&vf->vd); + + ret=_seek_helper(vf,pos); + if(ret)goto seek_error; + + /* we need to make sure the pcm_offset is set, but we don't want to + advance the raw cursor past good packets just to get to the first + with a granulepos. That's not equivalent behavior to beginning + decoding as immediately after the seek position as possible. + + So, a hack. We use two stream states; a local scratch state and + the shared vf->os stream state. We use the local state to + scan, and the shared state as a buffer for later decode. + + Unfortuantely, on the last page we still advance to last packet + because the granulepos on the last page is not necessarily on a + packet boundary, and we need to make sure the granpos is + correct. + */ + + { + ogg_page og; + ogg_packet op; + int lastblock=0; + int accblock=0; + int thisblock=0; + int lastflag=0; + int firstflag=0; + ogg_int64_t pagepos=-1; + + ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */ + ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE + return from not necessarily + starting from the beginning */ + + while(1){ + if(vf->ready_state>=STREAMSET){ + /* snarf/scan a packet if we can */ + int result=ogg_stream_packetout(&work_os,&op); + + if(result>0){ + + if(vf->vi[vf->current_link].codec_setup){ + thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op); + if(thisblock<0){ + ogg_stream_packetout(&vf->os,NULL); + thisblock=0; + }else{ + + /* We can't get a guaranteed correct pcm position out of the + last page in a stream because it might have a 'short' + granpos, which can only be detected in the presence of a + preceding page. However, if the last page is also the first + page, the granpos rules of a first page take precedence. Not + only that, but for first==last, the EOS page must be treated + as if its a normal first page for the stream to open/play. */ + if(lastflag && !firstflag) + ogg_stream_packetout(&vf->os,NULL); + else + if(lastblock)accblock+=(lastblock+thisblock)>>2; + } + + if(op.granulepos!=-1){ + int i,link=vf->current_link; + ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2]; + if(granulepos<0)granulepos=0; + + for(i=0;ipcmlengths[i*2+1]; + vf->pcm_offset=granulepos-accblock; + if(vf->pcm_offset<0)vf->pcm_offset=0; + break; + } + lastblock=thisblock; + continue; + }else + ogg_stream_packetout(&vf->os,NULL); + } + } + + if(!lastblock){ + pagepos=_get_next_page(vf,&og,-1); + if(pagepos<0){ + vf->pcm_offset=ov_pcm_total(vf,-1); + break; + } + }else{ + /* huh? Bogus stream with packets but no granulepos */ + vf->pcm_offset=-1; + break; + } + + /* has our decoding just traversed a bitstream boundary? */ + if(vf->ready_state>=STREAMSET){ + if(vf->current_serialno!=ogg_page_serialno(&og)){ + + /* two possibilities: + 1) our decoding just traversed a bitstream boundary + 2) another stream is multiplexed into this logical section? */ + + if(ogg_page_bos(&og)){ + /* we traversed */ + _decode_clear(vf); /* clear out stream state */ + ogg_stream_clear(&work_os); + } /* else, do nothing; next loop will scoop another page */ + } + } + + if(vf->ready_statelinks;link++) + if(vf->serialnos[link]==serialno)break; + + if(link==vf->links) continue; /* not the desired Vorbis + bitstream section; keep + trying */ + vf->current_link=link; + vf->current_serialno=serialno; + ogg_stream_reset_serialno(&vf->os,serialno); + ogg_stream_reset_serialno(&work_os,serialno); + vf->ready_state=STREAMSET; + firstflag=(pagepos<=vf->dataoffsets[link]); + } + + ogg_stream_pagein(&vf->os,&og); + ogg_stream_pagein(&work_os,&og); + lastflag=ogg_page_eos(&og); + + } + } + + ogg_stream_clear(&work_os); + vf->bittrack=0; + vf->samptrack=0; + return(0); + + seek_error: + /* dump the machine so we're in a known state */ + vf->pcm_offset=-1; + ogg_stream_clear(&work_os); + _decode_clear(vf); + return OV_EBADLINK; +} + +/* rescales the number x from the range of [0,from] to [0,to] + x is in the range [0,from] + from, to are in the range [1, 1<<62-1] */ +ogg_int64_t rescale64(ogg_int64_t x, ogg_int64_t from, ogg_int64_t to){ + ogg_int64_t frac=0; + ogg_int64_t ret=0; + int i; + if(x >= from) return to; + if(x <= 0) return 0; + + for(i=0;i<64;i++){ + if(x>=from){ + frac|=1; + x-=from; + } + x<<=1; + frac<<=1; + } + + for(i=0;i<64;i++){ + if(frac & 1){ + ret+=to; + } + frac>>=1; + ret>>=1; + } + + return ret; +} + +/* Page granularity seek (faster than sample granularity because we + don't do the last bit of decode to find a specific sample). + + Seek to the last [granule marked] page preceding the specified pos + location, such that decoding past the returned point will quickly + arrive at the requested position. */ +int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){ + int link=-1; + ogg_int64_t result=0; + ogg_int64_t total=ov_pcm_total(vf,-1); + + if(vf->ready_stateseekable)return(OV_ENOSEEK); + + if(pos<0 || pos>total)return(OV_EINVAL); + + /* which bitstream section does this pcm offset occur in? */ + for(link=vf->links-1;link>=0;link--){ + total-=vf->pcmlengths[link*2+1]; + if(pos>=total)break; + } + + /* Search within the logical bitstream for the page with the highest + pcm_pos preceding pos. If we're looking for a position on the + first page, bisection will halt without finding our position as + it's before the first explicit granulepos fencepost. That case is + handled separately below. + + There is a danger here; missing pages or incorrect frame number + information in the bitstream could make our task impossible. + Account for that (it would be an error condition) */ + + /* new search algorithm originally by HB (Nicholas Vinen) */ + + { + ogg_int64_t end=vf->offsets[link+1]; + ogg_int64_t begin=vf->dataoffsets[link]; + ogg_int64_t begintime = vf->pcmlengths[link*2]; + ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime; + ogg_int64_t target=pos-total+begintime; + ogg_int64_t best=-1; + int got_page=0; + + ogg_page og; + + /* if we have only one page, there will be no bisection. Grab the page here */ + if(begin==end){ + result=_seek_helper(vf,begin); + if(result) goto seek_error; + + result=_get_next_page(vf,&og,1); + if(result<0) goto seek_error; + + got_page=1; + } + + /* bisection loop */ + while(beginoffset); + if(result==OV_EREAD) goto seek_error; + if(result<0){ + /* there is no next page! */ + if(bisect<=begin+1) + /* No bisection left to perform. We've either found the + best candidate already or failed. Exit loop. */ + end=begin; + else{ + /* We tried to load a fraction of the last page; back up a + bit and try to get the whole last page */ + if(bisect==0) goto seek_error; + bisect-=CHUNKSIZE; + + /* don't repeat/loop on a read we've already performed */ + if(bisect<=begin)bisect=begin+1; + + /* seek and continue bisection */ + result=_seek_helper(vf,bisect); + if(result) goto seek_error; + } + }else{ + ogg_int64_t granulepos; + got_page=1; + + /* got a page. analyze it */ + /* only consider pages from primary vorbis stream */ + if(ogg_page_serialno(&og)!=vf->serialnos[link]) + continue; + + /* only consider pages with the granulepos set */ + granulepos=ogg_page_granulepos(&og); + if(granulepos==-1)continue; + + if(granuleposoffset; /* raw offset of next page */ + begintime=granulepos; + + /* if we're before our target but within a short distance, + don't bisect; read forward */ + if(target-begintime>44100)break; + + bisect=begin; /* *not* begin + 1 as above */ + }else{ + + /* This is one of our pages, but the granpos is + post-target; it is not a bisection return + candidate. (The only way we'd use it is if it's the + first page in the stream; we handle that case later + outside the bisection) */ + if(bisect<=begin+1){ + /* No bisection left to perform. We've either found the + best candidate already or failed. Exit loop. */ + end=begin; + }else{ + if(end==vf->offset){ + /* bisection read to the end; use the known page + boundary (result) to update bisection, back up a + little bit, and try again */ + end=result; + bisect-=CHUNKSIZE; + if(bisect<=begin)bisect=begin+1; + result=_seek_helper(vf,bisect); + if(result) goto seek_error; + }else{ + /* Normal bisection */ + end=bisect; + endtime=granulepos; + break; + } + } + } + } + } + } + + /* Out of bisection: did it 'fail?' */ + if(best == -1){ + + /* Check the 'looking for data in first page' special case; + bisection would 'fail' because our search target was before the + first PCM granule position fencepost. */ + + if(got_page && + begin == vf->dataoffsets[link] && + ogg_page_serialno(&og)==vf->serialnos[link]){ + + /* Yes, this is the beginning-of-stream case. We already have + our page, right at the beginning of PCM data. Set state + and return. */ + + vf->pcm_offset=total; + + if(link!=vf->current_link){ + /* Different link; dump entire decode machine */ + _decode_clear(vf); + + vf->current_link=link; + vf->current_serialno=vf->serialnos[link]; + vf->ready_state=STREAMSET; + + }else{ + vorbis_synthesis_restart(&vf->vd); + } + + ogg_stream_reset_serialno(&vf->os,vf->current_serialno); + ogg_stream_pagein(&vf->os,&og); + + }else + goto seek_error; + + }else{ + + /* Bisection found our page. seek to it, update pcm offset. Easier case than + raw_seek, don't keep packets preceding granulepos. */ + + ogg_page og; + ogg_packet op; + + /* seek */ + result=_seek_helper(vf,best); + vf->pcm_offset=-1; + if(result) goto seek_error; + result=_get_next_page(vf,&og,-1); + if(result<0) goto seek_error; + + if(link!=vf->current_link){ + /* Different link; dump entire decode machine */ + _decode_clear(vf); + + vf->current_link=link; + vf->current_serialno=vf->serialnos[link]; + vf->ready_state=STREAMSET; + + }else{ + vorbis_synthesis_restart(&vf->vd); + } + + ogg_stream_reset_serialno(&vf->os,vf->current_serialno); + ogg_stream_pagein(&vf->os,&og); + + /* pull out all but last packet; the one with granulepos */ + while(1){ + result=ogg_stream_packetpeek(&vf->os,&op); + if(result==0){ + /* No packet returned; we exited the bisection with 'best' + pointing to a page with a granule position, so the packet + finishing this page ('best') originated on a preceding + page. Keep fetching previous pages until we get one with + a granulepos or without the 'continued' flag set. Then + just use raw_seek for simplicity. */ + /* Do not rewind past the beginning of link data; if we do, + it's either a bug or a broken stream */ + result=best; + while(result>vf->dataoffsets[link]){ + result=_get_prev_page(vf,result,&og); + if(result<0) goto seek_error; + if(ogg_page_serialno(&og)==vf->current_serialno && + (ogg_page_granulepos(&og)>-1 || + !ogg_page_continued(&og))){ + return ov_raw_seek(vf,result); + } + } + } + if(result<0){ + result = OV_EBADPACKET; + goto seek_error; + } + if(op.granulepos!=-1){ + vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2]; + if(vf->pcm_offset<0)vf->pcm_offset=0; + vf->pcm_offset+=total; + break; + }else + result=ogg_stream_packetout(&vf->os,NULL); + } + } + } + + /* verify result */ + if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){ + result=OV_EFAULT; + goto seek_error; + } + vf->bittrack=0; + vf->samptrack=0; + return(0); + + seek_error: + /* dump machine so we're in a known state */ + vf->pcm_offset=-1; + _decode_clear(vf); + return (int)result; +} + +/* seek to a sample offset relative to the decompressed pcm stream + returns zero on success, nonzero on failure */ + +int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){ + int thisblock,lastblock=0; + int ret=ov_pcm_seek_page(vf,pos); + if(ret<0)return(ret); + if((ret=_make_decode_ready(vf)))return ret; + + /* discard leading packets we don't need for the lapping of the + position we want; don't decode them */ + + while(1){ + ogg_packet op; + ogg_page og; + + int ret=ogg_stream_packetpeek(&vf->os,&op); + if(ret>0){ + thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op); + if(thisblock<0){ + ogg_stream_packetout(&vf->os,NULL); + continue; /* non audio packet */ + } + if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2; + + if(vf->pcm_offset+((thisblock+ + vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break; + + /* remove the packet from packet queue and track its granulepos */ + ogg_stream_packetout(&vf->os,NULL); + vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with + only tracking, no + pcm_decode */ + vorbis_synthesis_blockin(&vf->vd,&vf->vb); + + /* end of logical stream case is hard, especially with exact + length positioning. */ + + if(op.granulepos>-1){ + int i; + /* always believe the stream markers */ + vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2]; + if(vf->pcm_offset<0)vf->pcm_offset=0; + for(i=0;icurrent_link;i++) + vf->pcm_offset+=vf->pcmlengths[i*2+1]; + } + + lastblock=thisblock; + + }else{ + if(ret<0 && ret!=OV_HOLE)break; + + /* suck in a new page */ + if(_get_next_page(vf,&og,-1)<0)break; + if(ogg_page_bos(&og))_decode_clear(vf); + + if(vf->ready_statelinks;link++) + if(vf->serialnos[link]==serialno)break; + if(link==vf->links) continue; + vf->current_link=link; + + vf->ready_state=STREAMSET; + vf->current_serialno=ogg_page_serialno(&og); + ogg_stream_reset_serialno(&vf->os,serialno); + ret=_make_decode_ready(vf); + if(ret)return ret; + lastblock=0; + } + + ogg_stream_pagein(&vf->os,&og); + } + } + + vf->bittrack=0; + vf->samptrack=0; + /* discard samples until we reach the desired position. Crossing a + logical bitstream boundary with abandon is OK. */ + while(vf->pcm_offsetpcm_offset; + long samples=vorbis_synthesis_pcmout(&vf->vd,NULL); + + if(samples>target)samples=target; + vorbis_synthesis_read(&vf->vd,samples); + vf->pcm_offset+=samples; + + if(samplespcm_offset=ov_pcm_total(vf,-1); /* eof */ + } + return 0; +} + +/* seek to a playback time relative to the decompressed pcm stream + returns zero on success, nonzero on failure */ +int ov_time_seek(OggVorbis_File *vf,ogg_int64_t milliseconds){ + /* translate time to PCM position and call ov_pcm_seek */ + + int link=-1; + ogg_int64_t pcm_total=0; + ogg_int64_t time_total=0; + + if(vf->ready_stateseekable)return(OV_ENOSEEK); + if(milliseconds<0)return(OV_EINVAL); + + /* which bitstream section does this time offset occur in? */ + for(link=0;linklinks;link++){ + ogg_int64_t addsec = ov_time_total(vf,link); + if(millisecondspcmlengths[link*2+1]; + } + + if(link==vf->links)return(OV_EINVAL); + + /* enough information to convert time offset to pcm offset */ + { + ogg_int64_t target=pcm_total+(milliseconds-time_total)*vf->vi[link].rate/1000; + return(ov_pcm_seek(vf,target)); + } +} + +/* page-granularity version of ov_time_seek + returns zero on success, nonzero on failure */ +int ov_time_seek_page(OggVorbis_File *vf,ogg_int64_t milliseconds){ + /* translate time to PCM position and call ov_pcm_seek */ + + int link=-1; + ogg_int64_t pcm_total=0; + ogg_int64_t time_total=0; + + if(vf->ready_stateseekable)return(OV_ENOSEEK); + if(milliseconds<0)return(OV_EINVAL); + + /* which bitstream section does this time offset occur in? */ + for(link=0;linklinks;link++){ + ogg_int64_t addsec = ov_time_total(vf,link); + if(millisecondspcmlengths[link*2+1]; + } + + if(link==vf->links)return(OV_EINVAL); + + /* enough information to convert time offset to pcm offset */ + { + ogg_int64_t target=pcm_total+(milliseconds-time_total)*vf->vi[link].rate/1000; + return(ov_pcm_seek_page(vf,target)); + } +} + +/* tell the current stream offset cursor. Note that seek followed by + tell will likely not give the set offset due to caching */ +ogg_int64_t ov_raw_tell(OggVorbis_File *vf){ + if(vf->ready_stateoffset); +} + +/* return PCM offset (sample) of next PCM sample to be read */ +ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){ + if(vf->ready_statepcm_offset); +} + +/* return time offset (milliseconds) of next PCM sample to be read */ +ogg_int64_t ov_time_tell(OggVorbis_File *vf){ + int link=0; + ogg_int64_t pcm_total=0; + ogg_int64_t time_total=0; + + if(vf->ready_stateseekable){ + pcm_total=ov_pcm_total(vf,-1); + time_total=ov_time_total(vf,-1); + + /* which bitstream section does this time offset occur in? */ + for(link=vf->links-1;link>=0;link--){ + pcm_total-=vf->pcmlengths[link*2+1]; + time_total-=ov_time_total(vf,link); + if(vf->pcm_offset>=pcm_total)break; + } + } + + return(time_total+(1000*vf->pcm_offset-pcm_total)/vf->vi[link].rate); +} + +/* link: -1) return the vorbis_info struct for the bitstream section + currently being decoded + 0-n) to request information for a specific bitstream section + + In the case of a non-seekable bitstream, any call returns the + current bitstream. NULL in the case that the machine is not + initialized */ + +vorbis_info *ov_info(OggVorbis_File *vf,int link){ + if(vf->seekable){ + if(link<0) + if(vf->ready_state>=STREAMSET) + return vf->vi+vf->current_link; + else + return vf->vi; + else + if(link>=vf->links) + return NULL; + else + return vf->vi+link; + }else{ + return vf->vi; + } +} + +/* grr, strong typing, grr, no templates/inheritence, grr */ +vorbis_comment *ov_comment(OggVorbis_File *vf,int link){ + if(vf->seekable){ + if(link<0) + if(vf->ready_state>=STREAMSET) + return vf->vc+vf->current_link; + else + return vf->vc; + else + if(link>=vf->links) + return NULL; + else + return vf->vc+link; + }else{ + return vf->vc; + } +} + +/* up to this point, everything could more or less hide the multiple + logical bitstream nature of chaining from the toplevel application + if the toplevel application didn't particularly care. However, at + the point that we actually read audio back, the multiple-section + nature must surface: Multiple bitstream sections do not necessarily + have to have the same number of channels or sampling rate. + + ov_read returns the sequential logical bitstream number currently + being decoded along with the PCM data in order that the toplevel + application can take action on channel/sample rate changes. This + number will be incremented even for streamed (non-seekable) streams + (for seekable streams, it represents the actual logical bitstream + index within the physical bitstream. Note that the accessor + functions above are aware of this dichotomy). + + input values: buffer) a buffer to hold packed PCM data for return + bytes_req) the byte length requested to be placed into buffer + + return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL) + 0) EOF + n) number of bytes of PCM actually returned. The + below works on a packet-by-packet basis, so the + return length is not related to the 'length' passed + in, just guaranteed to fit. + + *section) set to the logical bitstream number */ + +long ov_read(OggVorbis_File *vf,char *buffer,int bytes_req,int *bitstream){ + int i,j; + + ogg_int32_t **pcm; + long samples; + + if(vf->ready_stateready_state==INITSET){ + samples=vorbis_synthesis_pcmout(&vf->vd,&pcm); + if(samples)break; + } + + /* suck in another packet */ + { + int ret=_fetch_and_process_packet(vf,NULL,1,1); + if(ret==OV_EOF) + return(0); + if(ret<=0) + return(ret); + } + + } + + if(samples>0){ + + /* yay! proceed to pack data into the byte buffer */ + + long channels=ov_info(vf,-1)->channels; + + if(samples>(bytes_req/(2*channels))) + samples=bytes_req/(2*channels); + + for(i=0;i>9); + dest+=channels; + } + } + + vorbis_synthesis_read(&vf->vd,samples); + vf->pcm_offset+=samples; + if(bitstream)*bitstream=vf->current_link; + return(samples*2*channels); + }else{ + return(samples); + } +} diff --git a/libs/tremor/vorbisidec.pc.in b/libs/tremor/vorbisidec.pc.in new file mode 100644 index 0000000..56fa656 --- /dev/null +++ b/libs/tremor/vorbisidec.pc.in @@ -0,0 +1,14 @@ +# libvorbisidec pkg-config source file + +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: vorbisidec +Description: vorbisidec is the integer Ogg Vorbis library +Version: @VERSION@ +Requires.private: ogg +Conflicts: +Libs: -L${libdir} -lvorbisidec +Cflags: -I${includedir} diff --git a/libs/tremor/win32/VS2005/libogg.vsprops b/libs/tremor/win32/VS2005/libogg.vsprops new file mode 100644 index 0000000..7fe0db7 --- /dev/null +++ b/libs/tremor/win32/VS2005/libogg.vsprops @@ -0,0 +1,19 @@ + + + + + + diff --git a/libs/tremor/win32/VS2005/libtremor/libtremor.vcproj b/libs/tremor/win32/VS2005/libtremor/libtremor.vcproj new file mode 100644 index 0000000..8f8ddcd --- /dev/null +++ b/libs/tremor/win32/VS2005/libtremor/libtremor.vcproj @@ -0,0 +1,865 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/libs/tremor/win32/VS2008/libogg.vsprops b/libs/tremor/win32/VS2008/libogg.vsprops new file mode 100644 index 0000000..1355b50 --- /dev/null +++ b/libs/tremor/win32/VS2008/libogg.vsprops @@ -0,0 +1,19 @@ + + + + + + diff --git a/libs/tremor/win32/VS2008/libtremor/libtremor.vcproj b/libs/tremor/win32/VS2008/libtremor/libtremor.vcproj new file mode 100644 index 0000000..4fb9f48 --- /dev/null +++ b/libs/tremor/win32/VS2008/libtremor/libtremor.vcproj @@ -0,0 +1,865 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/libs/tremor/window.c b/libs/tremor/window.c new file mode 100644 index 0000000..006a1ee --- /dev/null +++ b/libs/tremor/window.c @@ -0,0 +1,83 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * + * * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * + * * + ******************************************************************** + + function: window functions + + ********************************************************************/ + +#include +#include +#include "misc.h" +#include "window.h" +#include "window_lookup.h" + +const void *_vorbis_window(int type, int left){ + + switch(type){ + case 0: + + switch(left){ + case 32: + return vwin64; + case 64: + return vwin128; + case 128: + return vwin256; + case 256: + return vwin512; + case 512: + return vwin1024; + case 1024: + return vwin2048; + case 2048: + return vwin4096; + case 4096: + return vwin8192; + default: + return(0); + } + break; + default: + return(0); + } +} + +void _vorbis_apply_window(ogg_int32_t *d,const void *window_p[2], + long *blocksizes, + int lW,int W,int nW){ + + LOOKUP_T *window[2]={window_p[0],window_p[1]}; + long n=blocksizes[W]; + long ln=blocksizes[lW]; + long rn=blocksizes[nW]; + + long leftbegin=n/4-ln/4; + long leftend=leftbegin+ln/2; + + long rightbegin=n/2+n/4-rn/4; + long rightend=rightbegin+rn/2; + + int i,p; + + for(i=0;i + +static const LOOKUP_T vwin64[32] = { + X(0x001f0003), X(0x01168c98), X(0x030333c8), X(0x05dfe3a4), + X(0x09a49562), X(0x0e45df18), X(0x13b47ef2), X(0x19dcf676), + X(0x20a74d83), X(0x27f7137c), X(0x2fabb05a), X(0x37a1105a), + X(0x3fb0ab28), X(0x47b2dcd1), X(0x4f807bc6), X(0x56f48e70), + X(0x5dedfc79), X(0x64511653), X(0x6a08cfff), X(0x6f079328), + X(0x734796f4), X(0x76cab7f2), X(0x7999d6e8), X(0x7bc3cf9f), + X(0x7d5c20c1), X(0x7e7961df), X(0x7f33a567), X(0x7fa2e1d0), + X(0x7fdd78a5), X(0x7ff6ec6d), X(0x7ffed0e9), X(0x7ffffc3f), +}; + +static const LOOKUP_T vwin128[64] = { + X(0x0007c04d), X(0x0045bb89), X(0x00c18b87), X(0x017ae294), + X(0x02714a4e), X(0x03a4217a), X(0x05129952), X(0x06bbb24f), + X(0x089e38a1), X(0x0ab8c073), X(0x0d09a228), X(0x0f8ef6bd), + X(0x12469488), X(0x152e0c7a), X(0x1842a81c), X(0x1b81686d), + X(0x1ee705d9), X(0x226ff15d), X(0x26185705), X(0x29dc21cc), + X(0x2db700fe), X(0x31a46f08), X(0x359fb9c1), X(0x39a40c0c), + X(0x3dac78b6), X(0x41b40674), X(0x45b5bcb0), X(0x49acb109), + X(0x4d94152b), X(0x516744bd), X(0x5521d320), X(0x58bf98a5), + X(0x5c3cbef4), X(0x5f95cc5d), X(0x62c7add7), X(0x65cfbf64), + X(0x68abd2ba), X(0x6b5a3405), X(0x6dd9acab), X(0x7029840d), + X(0x72497e38), X(0x7439d8ac), X(0x75fb4532), X(0x778ee30a), + X(0x78f6367e), X(0x7a331f1a), X(0x7b47cccd), X(0x7c36b416), + X(0x7d028192), X(0x7dae0d18), X(0x7e3c4caa), X(0x7eb04763), + X(0x7f0d08a7), X(0x7f5593b7), X(0x7f8cd7d5), X(0x7fb5a513), + X(0x7fd2a1fc), X(0x7fe64212), X(0x7ff2bd4c), X(0x7ffa0890), + X(0x7ffdcf39), X(0x7fff6dac), X(0x7fffed01), X(0x7fffffc4), +}; + +static const LOOKUP_T vwin256[128] = { + X(0x0001f018), X(0x00117066), X(0x00306e9e), X(0x005ee5f1), + X(0x009ccf26), X(0x00ea208b), X(0x0146cdea), X(0x01b2c87f), + X(0x022dfedf), X(0x02b85ced), X(0x0351cbbd), X(0x03fa317f), + X(0x04b17167), X(0x05776b90), X(0x064bfcdc), X(0x072efedd), + X(0x082047b4), X(0x091fa9f1), X(0x0a2cf477), X(0x0b47f25d), + X(0x0c706ad2), X(0x0da620ff), X(0x0ee8d3ef), X(0x10383e75), + X(0x11941716), X(0x12fc0ff6), X(0x146fd6c8), X(0x15ef14c2), + X(0x17796e8e), X(0x190e844f), X(0x1aadf196), X(0x1c574d6e), + X(0x1e0a2a62), X(0x1fc61688), X(0x218a9b9c), X(0x23573f12), + X(0x252b823d), X(0x2706e269), X(0x28e8d913), X(0x2ad0dc0e), + X(0x2cbe5dc1), X(0x2eb0cd60), X(0x30a79733), X(0x32a224d5), + X(0x349fdd8b), X(0x36a02690), X(0x38a2636f), X(0x3aa5f65e), + X(0x3caa409e), X(0x3eaea2df), X(0x40b27da6), X(0x42b531b8), + X(0x44b62086), X(0x46b4ac99), X(0x48b03a05), X(0x4aa82ed5), + X(0x4c9bf37d), X(0x4e8af349), X(0x50749ccb), X(0x52586246), + X(0x5435ba1c), X(0x560c1f31), X(0x57db1152), X(0x59a21591), + X(0x5b60b6a3), X(0x5d168535), X(0x5ec31839), X(0x60660d36), + X(0x61ff0886), X(0x638db595), X(0x6511c717), X(0x668af734), + X(0x67f907b0), X(0x695bc207), X(0x6ab2f787), X(0x6bfe815a), + X(0x6d3e4090), X(0x6e721e16), X(0x6f9a0ab5), X(0x70b5fef8), + X(0x71c5fb16), X(0x72ca06cd), X(0x73c2313d), X(0x74ae90b2), + X(0x758f4275), X(0x76646a85), X(0x772e335c), X(0x77eccda0), + X(0x78a06fd7), X(0x79495613), X(0x79e7c19c), X(0x7a7bf894), + X(0x7b064596), X(0x7b86f757), X(0x7bfe6044), X(0x7c6cd615), + X(0x7cd2b16e), X(0x7d304d71), X(0x7d860756), X(0x7dd43e06), + X(0x7e1b51ad), X(0x7e5ba355), X(0x7e95947e), X(0x7ec986bb), + X(0x7ef7db4a), X(0x7f20f2b9), X(0x7f452c7f), X(0x7f64e6a7), + X(0x7f807d71), X(0x7f984aff), X(0x7faca700), X(0x7fbde662), + X(0x7fcc5b04), X(0x7fd85372), X(0x7fe21a99), X(0x7fe9f791), + X(0x7ff02d58), X(0x7ff4fa9e), X(0x7ff89990), X(0x7ffb3faa), + X(0x7ffd1d8b), X(0x7ffe5ecc), X(0x7fff29e0), X(0x7fff9ff3), + X(0x7fffdcd2), X(0x7ffff6d6), X(0x7ffffed0), X(0x7ffffffc), +}; + +static const LOOKUP_T vwin512[256] = { + X(0x00007c06), X(0x00045c32), X(0x000c1c62), X(0x0017bc4c), + X(0x00273b7a), X(0x003a9955), X(0x0051d51c), X(0x006cede7), + X(0x008be2a9), X(0x00aeb22a), X(0x00d55b0d), X(0x00ffdbcc), + X(0x012e32b6), X(0x01605df5), X(0x01965b85), X(0x01d02939), + X(0x020dc4ba), X(0x024f2b83), X(0x02945ae6), X(0x02dd5004), + X(0x032a07d3), X(0x037a7f19), X(0x03ceb26e), X(0x04269e37), + X(0x04823eab), X(0x04e18fcc), X(0x05448d6d), X(0x05ab3329), + X(0x06157c68), X(0x0683645e), X(0x06f4e607), X(0x0769fc25), + X(0x07e2a146), X(0x085ecfbc), X(0x08de819f), X(0x0961b0cc), + X(0x09e856e3), X(0x0a726d46), X(0x0affed1d), X(0x0b90cf4c), + X(0x0c250c79), X(0x0cbc9d0b), X(0x0d577926), X(0x0df598aa), + X(0x0e96f337), X(0x0f3b8026), X(0x0fe3368f), X(0x108e0d42), + X(0x113bfaca), X(0x11ecf56b), X(0x12a0f324), X(0x1357e9ac), + X(0x1411ce70), X(0x14ce9698), X(0x158e3702), X(0x1650a444), + X(0x1715d2aa), X(0x17ddb638), X(0x18a842aa), X(0x19756b72), + X(0x1a4523b9), X(0x1b175e62), X(0x1bec0e04), X(0x1cc324f0), + X(0x1d9c9532), X(0x1e78508a), X(0x1f564876), X(0x20366e2e), + X(0x2118b2a2), X(0x21fd0681), X(0x22e35a37), X(0x23cb9dee), + X(0x24b5c18e), X(0x25a1b4c0), X(0x268f66f1), X(0x277ec74e), + X(0x286fc4cc), X(0x29624e23), X(0x2a5651d7), X(0x2b4bbe34), + X(0x2c428150), X(0x2d3a8913), X(0x2e33c332), X(0x2f2e1d35), + X(0x30298478), X(0x3125e62d), X(0x32232f61), X(0x33214cfc), + X(0x34202bc2), X(0x351fb85a), X(0x361fdf4f), X(0x37208d10), + X(0x3821adf7), X(0x39232e49), X(0x3a24fa3c), X(0x3b26fdf6), + X(0x3c292593), X(0x3d2b5d29), X(0x3e2d90c8), X(0x3f2fac7f), + X(0x40319c5f), X(0x41334c81), X(0x4234a905), X(0x43359e16), + X(0x443617f3), X(0x453602eb), X(0x46354b65), X(0x4733dde1), + X(0x4831a6ff), X(0x492e937f), X(0x4a2a9045), X(0x4b258a5f), + X(0x4c1f6f06), X(0x4d182ba2), X(0x4e0fadce), X(0x4f05e35b), + X(0x4ffaba53), X(0x50ee20fd), X(0x51e005e1), X(0x52d057ca), + X(0x53bf05ca), X(0x54abff3b), X(0x559733c7), X(0x56809365), + X(0x57680e62), X(0x584d955d), X(0x59311952), X(0x5a128b96), + X(0x5af1dddd), X(0x5bcf023a), X(0x5ca9eb27), X(0x5d828b81), + X(0x5e58d68d), X(0x5f2cbffc), X(0x5ffe3be9), X(0x60cd3edf), + X(0x6199bdda), X(0x6263ae45), X(0x632b0602), X(0x63efbb66), + X(0x64b1c53f), X(0x65711ad0), X(0x662db3d7), X(0x66e7888d), + X(0x679e91a5), X(0x6852c84e), X(0x69042635), X(0x69b2a582), + X(0x6a5e40dd), X(0x6b06f36c), X(0x6bacb8d2), X(0x6c4f8d30), + X(0x6cef6d26), X(0x6d8c55d4), X(0x6e2644d4), X(0x6ebd3840), + X(0x6f512ead), X(0x6fe2272e), X(0x7070214f), X(0x70fb1d17), + X(0x71831b06), X(0x72081c16), X(0x728a21b5), X(0x73092dc8), + X(0x738542a6), X(0x73fe631b), X(0x74749261), X(0x74e7d421), + X(0x75582c72), X(0x75c59fd5), X(0x76303333), X(0x7697ebdd), + X(0x76fccf85), X(0x775ee443), X(0x77be308a), X(0x781abb2e), + X(0x78748b59), X(0x78cba88e), X(0x79201aa7), X(0x7971e9cd), + X(0x79c11e79), X(0x7a0dc170), X(0x7a57dbc2), X(0x7a9f76c1), + X(0x7ae49c07), X(0x7b27556b), X(0x7b67ad02), X(0x7ba5ad1b), + X(0x7be1603a), X(0x7c1ad118), X(0x7c520a9e), X(0x7c8717e1), + X(0x7cba0421), X(0x7ceadac3), X(0x7d19a74f), X(0x7d46756e), + X(0x7d7150e5), X(0x7d9a4592), X(0x7dc15f69), X(0x7de6aa71), + X(0x7e0a32c0), X(0x7e2c0479), X(0x7e4c2bc7), X(0x7e6ab4db), + X(0x7e87abe9), X(0x7ea31d24), X(0x7ebd14be), X(0x7ed59edd), + X(0x7eecc7a3), X(0x7f029b21), X(0x7f17255a), X(0x7f2a723f), + X(0x7f3c8daa), X(0x7f4d835d), X(0x7f5d5f00), X(0x7f6c2c1b), + X(0x7f79f617), X(0x7f86c83a), X(0x7f92ada2), X(0x7f9db146), + X(0x7fa7ddf3), X(0x7fb13e46), X(0x7fb9dcb0), X(0x7fc1c36c), + X(0x7fc8fc83), X(0x7fcf91c7), X(0x7fd58cd2), X(0x7fdaf702), + X(0x7fdfd979), X(0x7fe43d1c), X(0x7fe82a8b), X(0x7febaa29), + X(0x7feec412), X(0x7ff1801c), X(0x7ff3e5d6), X(0x7ff5fc86), + X(0x7ff7cb29), X(0x7ff9586f), X(0x7ffaaaba), X(0x7ffbc81e), + X(0x7ffcb660), X(0x7ffd7af3), X(0x7ffe1afa), X(0x7ffe9b42), + X(0x7fff0047), X(0x7fff4e2f), X(0x7fff88c9), X(0x7fffb390), + X(0x7fffd1a6), X(0x7fffe5d7), X(0x7ffff296), X(0x7ffff9fd), + X(0x7ffffdcd), X(0x7fffff6d), X(0x7fffffed), X(0x7fffffff), +}; + +static const LOOKUP_T vwin1024[512] = { + X(0x00001f02), X(0x0001170e), X(0x00030724), X(0x0005ef40), + X(0x0009cf59), X(0x000ea767), X(0x0014775e), X(0x001b3f2e), + X(0x0022fec8), X(0x002bb618), X(0x00356508), X(0x00400b81), + X(0x004ba968), X(0x00583ea0), X(0x0065cb0a), X(0x00744e84), + X(0x0083c8ea), X(0x00943a14), X(0x00a5a1da), X(0x00b80010), + X(0x00cb5488), X(0x00df9f10), X(0x00f4df76), X(0x010b1584), + X(0x01224101), X(0x013a61b2), X(0x01537759), X(0x016d81b6), + X(0x01888087), X(0x01a47385), X(0x01c15a69), X(0x01df34e6), + X(0x01fe02b1), X(0x021dc377), X(0x023e76e7), X(0x02601ca9), + X(0x0282b466), X(0x02a63dc1), X(0x02cab85d), X(0x02f023d6), + X(0x03167fcb), X(0x033dcbd3), X(0x03660783), X(0x038f3270), + X(0x03b94c29), X(0x03e4543a), X(0x04104a2e), X(0x043d2d8b), + X(0x046afdd5), X(0x0499ba8c), X(0x04c9632d), X(0x04f9f734), + X(0x052b7615), X(0x055ddf46), X(0x05913237), X(0x05c56e53), + X(0x05fa9306), X(0x06309fb6), X(0x066793c5), X(0x069f6e93), + X(0x06d82f7c), X(0x0711d5d9), X(0x074c60fe), X(0x0787d03d), + X(0x07c422e4), X(0x0801583e), X(0x083f6f91), X(0x087e681f), + X(0x08be4129), X(0x08fef9ea), X(0x0940919a), X(0x0983076d), + X(0x09c65a92), X(0x0a0a8a38), X(0x0a4f9585), X(0x0a957b9f), + X(0x0adc3ba7), X(0x0b23d4b9), X(0x0b6c45ee), X(0x0bb58e5a), + X(0x0bffad0f), X(0x0c4aa11a), X(0x0c966982), X(0x0ce3054d), + X(0x0d30737b), X(0x0d7eb308), X(0x0dcdc2eb), X(0x0e1da21a), + X(0x0e6e4f83), X(0x0ebfca11), X(0x0f1210ad), X(0x0f652238), + X(0x0fb8fd91), X(0x100da192), X(0x10630d11), X(0x10b93ee0), + X(0x111035cb), X(0x1167f09a), X(0x11c06e13), X(0x1219acf5), + X(0x1273abfb), X(0x12ce69db), X(0x1329e54a), X(0x13861cf3), + X(0x13e30f80), X(0x1440bb97), X(0x149f1fd8), X(0x14fe3ade), + X(0x155e0b40), X(0x15be8f92), X(0x161fc662), X(0x1681ae38), + X(0x16e4459b), X(0x17478b0b), X(0x17ab7d03), X(0x181019fb), + X(0x18756067), X(0x18db4eb3), X(0x1941e34a), X(0x19a91c92), + X(0x1a10f8ea), X(0x1a7976af), X(0x1ae29439), X(0x1b4c4fda), + X(0x1bb6a7e2), X(0x1c219a9a), X(0x1c8d2649), X(0x1cf9492e), + X(0x1d660188), X(0x1dd34d8e), X(0x1e412b74), X(0x1eaf996a), + X(0x1f1e959b), X(0x1f8e1e2f), X(0x1ffe3146), X(0x206ecd01), + X(0x20dfef78), X(0x215196c2), X(0x21c3c0f0), X(0x22366c10), + X(0x22a9962a), X(0x231d3d45), X(0x23915f60), X(0x2405fa7a), + X(0x247b0c8c), X(0x24f09389), X(0x25668d65), X(0x25dcf80c), + X(0x2653d167), X(0x26cb175e), X(0x2742c7d0), X(0x27bae09e), + X(0x28335fa2), X(0x28ac42b3), X(0x292587a5), X(0x299f2c48), + X(0x2a192e69), X(0x2a938bd1), X(0x2b0e4247), X(0x2b894f8d), + X(0x2c04b164), X(0x2c806588), X(0x2cfc69b2), X(0x2d78bb9a), + X(0x2df558f4), X(0x2e723f6f), X(0x2eef6cbb), X(0x2f6cde83), + X(0x2fea9270), X(0x30688627), X(0x30e6b74e), X(0x31652385), + X(0x31e3c86b), X(0x3262a39e), X(0x32e1b2b8), X(0x3360f352), + X(0x33e06303), X(0x345fff5e), X(0x34dfc5f8), X(0x355fb462), + X(0x35dfc82a), X(0x365ffee0), X(0x36e0560f), X(0x3760cb43), + X(0x37e15c05), X(0x386205df), X(0x38e2c657), X(0x39639af5), + X(0x39e4813e), X(0x3a6576b6), X(0x3ae678e3), X(0x3b678547), + X(0x3be89965), X(0x3c69b2c1), X(0x3ceacedc), X(0x3d6beb37), + X(0x3ded0557), X(0x3e6e1abb), X(0x3eef28e6), X(0x3f702d5a), + X(0x3ff1259a), X(0x40720f29), X(0x40f2e789), X(0x4173ac3f), + X(0x41f45ad0), X(0x4274f0c2), X(0x42f56b9a), X(0x4375c8e0), + X(0x43f6061d), X(0x447620db), X(0x44f616a5), X(0x4575e509), + X(0x45f58994), X(0x467501d6), X(0x46f44b62), X(0x477363cb), + X(0x47f248a6), X(0x4870f78e), X(0x48ef6e1a), X(0x496da9e8), + X(0x49eba897), X(0x4a6967c8), X(0x4ae6e521), X(0x4b641e47), + X(0x4be110e5), X(0x4c5dbaa7), X(0x4cda193f), X(0x4d562a5f), + X(0x4dd1ebbd), X(0x4e4d5b15), X(0x4ec87623), X(0x4f433aa9), + X(0x4fbda66c), X(0x5037b734), X(0x50b16acf), X(0x512abf0e), + X(0x51a3b1c5), X(0x521c40ce), X(0x52946a06), X(0x530c2b50), + X(0x53838292), X(0x53fa6db8), X(0x5470eab3), X(0x54e6f776), + X(0x555c91fc), X(0x55d1b844), X(0x56466851), X(0x56baa02f), + X(0x572e5deb), X(0x57a19f98), X(0x58146352), X(0x5886a737), + X(0x58f8696d), X(0x5969a81c), X(0x59da6177), X(0x5a4a93b4), + X(0x5aba3d0f), X(0x5b295bcb), X(0x5b97ee30), X(0x5c05f28d), + X(0x5c736738), X(0x5ce04a8d), X(0x5d4c9aed), X(0x5db856c1), + X(0x5e237c78), X(0x5e8e0a89), X(0x5ef7ff6f), X(0x5f6159b0), + X(0x5fca17d4), X(0x6032386e), X(0x6099ba15), X(0x61009b69), + X(0x6166db11), X(0x61cc77b9), X(0x62317017), X(0x6295c2e7), + X(0x62f96eec), X(0x635c72f1), X(0x63becdc8), X(0x64207e4b), + X(0x6481835a), X(0x64e1dbde), X(0x654186c8), X(0x65a0830e), + X(0x65fecfb1), X(0x665c6bb7), X(0x66b95630), X(0x67158e30), + X(0x677112d7), X(0x67cbe34b), X(0x6825feb9), X(0x687f6456), + X(0x68d81361), X(0x69300b1e), X(0x69874ada), X(0x69ddd1ea), + X(0x6a339fab), X(0x6a88b382), X(0x6add0cdb), X(0x6b30ab2a), + X(0x6b838dec), X(0x6bd5b4a6), X(0x6c271ee2), X(0x6c77cc36), + X(0x6cc7bc3d), X(0x6d16ee9b), X(0x6d6562fb), X(0x6db31911), + X(0x6e001099), X(0x6e4c4955), X(0x6e97c311), X(0x6ee27d9f), + X(0x6f2c78d9), X(0x6f75b4a2), X(0x6fbe30e4), X(0x7005ed91), + X(0x704ceaa1), X(0x70932816), X(0x70d8a5f8), X(0x711d6457), + X(0x7161634b), X(0x71a4a2f3), X(0x71e72375), X(0x7228e500), + X(0x7269e7c8), X(0x72aa2c0a), X(0x72e9b209), X(0x73287a12), + X(0x73668476), X(0x73a3d18f), X(0x73e061bc), X(0x741c3566), + X(0x74574cfa), X(0x7491a8ee), X(0x74cb49be), X(0x75042fec), + X(0x753c5c03), X(0x7573ce92), X(0x75aa882f), X(0x75e08979), + X(0x7615d313), X(0x764a65a7), X(0x767e41e5), X(0x76b16884), + X(0x76e3da40), X(0x771597dc), X(0x7746a221), X(0x7776f9dd), + X(0x77a69fe6), X(0x77d59514), X(0x7803da49), X(0x7831706a), + X(0x785e5861), X(0x788a9320), X(0x78b6219c), X(0x78e104cf), + X(0x790b3dbb), X(0x7934cd64), X(0x795db4d5), X(0x7985f51d), + X(0x79ad8f50), X(0x79d48486), X(0x79fad5de), X(0x7a208478), + X(0x7a45917b), X(0x7a69fe12), X(0x7a8dcb6c), X(0x7ab0fabb), + X(0x7ad38d36), X(0x7af5841a), X(0x7b16e0a3), X(0x7b37a416), + X(0x7b57cfb8), X(0x7b7764d4), X(0x7b9664b6), X(0x7bb4d0b0), + X(0x7bd2aa14), X(0x7beff23b), X(0x7c0caa7f), X(0x7c28d43c), + X(0x7c4470d2), X(0x7c5f81a5), X(0x7c7a081a), X(0x7c940598), + X(0x7cad7b8b), X(0x7cc66b5e), X(0x7cded680), X(0x7cf6be64), + X(0x7d0e247b), X(0x7d250a3c), X(0x7d3b711c), X(0x7d515a95), + X(0x7d66c822), X(0x7d7bbb3c), X(0x7d903563), X(0x7da43814), + X(0x7db7c4d0), X(0x7dcadd16), X(0x7ddd826a), X(0x7defb64d), + X(0x7e017a44), X(0x7e12cfd3), X(0x7e23b87f), X(0x7e3435cc), + X(0x7e444943), X(0x7e53f467), X(0x7e6338c0), X(0x7e7217d5), + X(0x7e80932b), X(0x7e8eac49), X(0x7e9c64b7), X(0x7ea9bdf8), + X(0x7eb6b994), X(0x7ec35910), X(0x7ecf9def), X(0x7edb89b6), + X(0x7ee71de9), X(0x7ef25c09), X(0x7efd4598), X(0x7f07dc16), + X(0x7f122103), X(0x7f1c15dc), X(0x7f25bc1f), X(0x7f2f1547), + X(0x7f3822cd), X(0x7f40e62b), X(0x7f4960d6), X(0x7f519443), + X(0x7f5981e7), X(0x7f612b31), X(0x7f689191), X(0x7f6fb674), + X(0x7f769b45), X(0x7f7d416c), X(0x7f83aa51), X(0x7f89d757), + X(0x7f8fc9df), X(0x7f958348), X(0x7f9b04ef), X(0x7fa0502e), + X(0x7fa56659), X(0x7faa48c7), X(0x7faef8c7), X(0x7fb377a7), + X(0x7fb7c6b3), X(0x7fbbe732), X(0x7fbfda67), X(0x7fc3a196), + X(0x7fc73dfa), X(0x7fcab0ce), X(0x7fcdfb4a), X(0x7fd11ea0), + X(0x7fd41c00), X(0x7fd6f496), X(0x7fd9a989), X(0x7fdc3bff), + X(0x7fdead17), X(0x7fe0fdee), X(0x7fe32f9d), X(0x7fe54337), + X(0x7fe739ce), X(0x7fe9146c), X(0x7fead41b), X(0x7fec79dd), + X(0x7fee06b2), X(0x7fef7b94), X(0x7ff0d97b), X(0x7ff22158), + X(0x7ff35417), X(0x7ff472a3), X(0x7ff57de0), X(0x7ff676ac), + X(0x7ff75de3), X(0x7ff8345a), X(0x7ff8fae4), X(0x7ff9b24b), + X(0x7ffa5b58), X(0x7ffaf6cd), X(0x7ffb8568), X(0x7ffc07e2), + X(0x7ffc7eed), X(0x7ffceb38), X(0x7ffd4d6d), X(0x7ffda631), + X(0x7ffdf621), X(0x7ffe3dd8), X(0x7ffe7dea), X(0x7ffeb6e7), + X(0x7ffee959), X(0x7fff15c4), X(0x7fff3ca9), X(0x7fff5e80), + X(0x7fff7bc0), X(0x7fff94d6), X(0x7fffaa2d), X(0x7fffbc29), + X(0x7fffcb29), X(0x7fffd786), X(0x7fffe195), X(0x7fffe9a3), + X(0x7fffeffa), X(0x7ffff4dd), X(0x7ffff889), X(0x7ffffb37), + X(0x7ffffd1a), X(0x7ffffe5d), X(0x7fffff29), X(0x7fffffa0), + X(0x7fffffdd), X(0x7ffffff7), X(0x7fffffff), X(0x7fffffff), +}; + +static const LOOKUP_T vwin2048[1024] = { + X(0x000007c0), X(0x000045c4), X(0x0000c1ca), X(0x00017bd3), + X(0x000273de), X(0x0003a9eb), X(0x00051df9), X(0x0006d007), + X(0x0008c014), X(0x000aee1e), X(0x000d5a25), X(0x00100428), + X(0x0012ec23), X(0x00161216), X(0x001975fe), X(0x001d17da), + X(0x0020f7a8), X(0x00251564), X(0x0029710c), X(0x002e0a9e), + X(0x0032e217), X(0x0037f773), X(0x003d4ab0), X(0x0042dbca), + X(0x0048aabe), X(0x004eb788), X(0x00550224), X(0x005b8a8f), + X(0x006250c5), X(0x006954c1), X(0x0070967e), X(0x007815f9), + X(0x007fd32c), X(0x0087ce13), X(0x009006a9), X(0x00987ce9), + X(0x00a130cc), X(0x00aa224f), X(0x00b3516b), X(0x00bcbe1a), + X(0x00c66856), X(0x00d0501a), X(0x00da755f), X(0x00e4d81f), + X(0x00ef7853), X(0x00fa55f4), X(0x010570fc), X(0x0110c963), + X(0x011c5f22), X(0x01283232), X(0x0134428c), X(0x01409027), + X(0x014d1afb), X(0x0159e302), X(0x0166e831), X(0x01742a82), + X(0x0181a9ec), X(0x018f6665), X(0x019d5fe5), X(0x01ab9663), + X(0x01ba09d6), X(0x01c8ba34), X(0x01d7a775), X(0x01e6d18d), + X(0x01f63873), X(0x0205dc1e), X(0x0215bc82), X(0x0225d997), + X(0x02363350), X(0x0246c9a3), X(0x02579c86), X(0x0268abed), + X(0x0279f7cc), X(0x028b801a), X(0x029d44c9), X(0x02af45ce), + X(0x02c1831d), X(0x02d3fcaa), X(0x02e6b269), X(0x02f9a44c), + X(0x030cd248), X(0x03203c4f), X(0x0333e255), X(0x0347c44b), + X(0x035be225), X(0x03703bd5), X(0x0384d14d), X(0x0399a280), + X(0x03aeaf5e), X(0x03c3f7d9), X(0x03d97be4), X(0x03ef3b6e), + X(0x0405366a), X(0x041b6cc8), X(0x0431de78), X(0x04488b6c), + X(0x045f7393), X(0x047696dd), X(0x048df53b), X(0x04a58e9b), + X(0x04bd62ee), X(0x04d57223), X(0x04edbc28), X(0x050640ed), + X(0x051f0060), X(0x0537fa70), X(0x05512f0a), X(0x056a9e1e), + X(0x05844798), X(0x059e2b67), X(0x05b84978), X(0x05d2a1b8), + X(0x05ed3414), X(0x06080079), X(0x062306d3), X(0x063e470f), + X(0x0659c119), X(0x067574dd), X(0x06916247), X(0x06ad8941), + X(0x06c9e9b8), X(0x06e68397), X(0x070356c8), X(0x07206336), + X(0x073da8cb), X(0x075b2772), X(0x0778df15), X(0x0796cf9c), + X(0x07b4f8f3), X(0x07d35b01), X(0x07f1f5b1), X(0x0810c8eb), + X(0x082fd497), X(0x084f189e), X(0x086e94e9), X(0x088e495e), + X(0x08ae35e6), X(0x08ce5a68), X(0x08eeb6cc), X(0x090f4af8), + X(0x093016d3), X(0x09511a44), X(0x09725530), X(0x0993c77f), + X(0x09b57115), X(0x09d751d8), X(0x09f969ae), X(0x0a1bb87c), + X(0x0a3e3e26), X(0x0a60fa91), X(0x0a83eda2), X(0x0aa7173c), + X(0x0aca7743), X(0x0aee0d9b), X(0x0b11da28), X(0x0b35dccc), + X(0x0b5a156a), X(0x0b7e83e5), X(0x0ba3281f), X(0x0bc801fa), + X(0x0bed1159), X(0x0c12561c), X(0x0c37d025), X(0x0c5d7f55), + X(0x0c83638d), X(0x0ca97cae), X(0x0ccfca97), X(0x0cf64d2a), + X(0x0d1d0444), X(0x0d43efc7), X(0x0d6b0f92), X(0x0d926383), + X(0x0db9eb79), X(0x0de1a752), X(0x0e0996ee), X(0x0e31ba29), + X(0x0e5a10e2), X(0x0e829af6), X(0x0eab5841), X(0x0ed448a2), + X(0x0efd6bf4), X(0x0f26c214), X(0x0f504ade), X(0x0f7a062e), + X(0x0fa3f3df), X(0x0fce13cd), X(0x0ff865d2), X(0x1022e9ca), + X(0x104d9f8e), X(0x107886f9), X(0x10a39fe5), X(0x10ceea2c), + X(0x10fa65a6), X(0x1126122d), X(0x1151ef9a), X(0x117dfdc5), + X(0x11aa3c87), X(0x11d6abb6), X(0x12034b2c), X(0x12301ac0), + X(0x125d1a48), X(0x128a499b), X(0x12b7a891), X(0x12e536ff), + X(0x1312f4bb), X(0x1340e19c), X(0x136efd75), X(0x139d481e), + X(0x13cbc16a), X(0x13fa692f), X(0x14293f40), X(0x14584371), + X(0x14877597), X(0x14b6d585), X(0x14e6630d), X(0x15161e04), + X(0x1546063b), X(0x15761b85), X(0x15a65db3), X(0x15d6cc99), + X(0x16076806), X(0x16382fcd), X(0x166923bf), X(0x169a43ab), + X(0x16cb8f62), X(0x16fd06b5), X(0x172ea973), X(0x1760776b), + X(0x1792706e), X(0x17c49449), X(0x17f6e2cb), X(0x18295bc3), + X(0x185bfeff), X(0x188ecc4c), X(0x18c1c379), X(0x18f4e452), + X(0x19282ea4), X(0x195ba23c), X(0x198f3ee6), X(0x19c3046e), + X(0x19f6f2a1), X(0x1a2b094a), X(0x1a5f4833), X(0x1a93af28), + X(0x1ac83df3), X(0x1afcf460), X(0x1b31d237), X(0x1b66d744), + X(0x1b9c034e), X(0x1bd15621), X(0x1c06cf84), X(0x1c3c6f40), + X(0x1c72351e), X(0x1ca820e6), X(0x1cde3260), X(0x1d146953), + X(0x1d4ac587), X(0x1d8146c3), X(0x1db7eccd), X(0x1deeb76c), + X(0x1e25a667), X(0x1e5cb982), X(0x1e93f085), X(0x1ecb4b33), + X(0x1f02c953), X(0x1f3a6aaa), X(0x1f722efb), X(0x1faa160b), + X(0x1fe21f9e), X(0x201a4b79), X(0x2052995d), X(0x208b0910), + X(0x20c39a53), X(0x20fc4cea), X(0x21352097), X(0x216e151c), + X(0x21a72a3a), X(0x21e05fb5), X(0x2219b54d), X(0x22532ac3), + X(0x228cbfd8), X(0x22c6744d), X(0x230047e2), X(0x233a3a58), + X(0x23744b6d), X(0x23ae7ae3), X(0x23e8c878), X(0x242333ec), + X(0x245dbcfd), X(0x24986369), X(0x24d326f1), X(0x250e0750), + X(0x25490446), X(0x25841d90), X(0x25bf52ec), X(0x25faa417), + X(0x263610cd), X(0x267198cc), X(0x26ad3bcf), X(0x26e8f994), + X(0x2724d1d6), X(0x2760c451), X(0x279cd0c0), X(0x27d8f6e0), + X(0x2815366a), X(0x28518f1b), X(0x288e00ac), X(0x28ca8ad8), + X(0x29072d5a), X(0x2943e7eb), X(0x2980ba45), X(0x29bda422), + X(0x29faa53c), X(0x2a37bd4a), X(0x2a74ec07), X(0x2ab2312b), + X(0x2aef8c6f), X(0x2b2cfd8b), X(0x2b6a8437), X(0x2ba8202c), + X(0x2be5d120), X(0x2c2396cc), X(0x2c6170e7), X(0x2c9f5f29), + X(0x2cdd6147), X(0x2d1b76fa), X(0x2d599ff7), X(0x2d97dbf5), + X(0x2dd62aab), X(0x2e148bcf), X(0x2e52ff16), X(0x2e918436), + X(0x2ed01ae5), X(0x2f0ec2d9), X(0x2f4d7bc6), X(0x2f8c4562), + X(0x2fcb1f62), X(0x300a097a), X(0x3049035f), X(0x30880cc6), + X(0x30c72563), X(0x31064cea), X(0x3145830f), X(0x3184c786), + X(0x31c41a03), X(0x32037a39), X(0x3242e7dc), X(0x3282629f), + X(0x32c1ea36), X(0x33017e53), X(0x33411ea9), X(0x3380caec), + X(0x33c082ce), X(0x34004602), X(0x34401439), X(0x347fed27), + X(0x34bfd07e), X(0x34ffbdf0), X(0x353fb52e), X(0x357fb5ec), + X(0x35bfbfda), X(0x35ffd2aa), X(0x363fee0f), X(0x368011b9), + X(0x36c03d5a), X(0x370070a4), X(0x3740ab48), X(0x3780ecf7), + X(0x37c13562), X(0x3801843a), X(0x3841d931), X(0x388233f7), + X(0x38c2943d), X(0x3902f9b4), X(0x3943640d), X(0x3983d2f8), + X(0x39c44626), X(0x3a04bd48), X(0x3a45380e), X(0x3a85b62a), + X(0x3ac6374a), X(0x3b06bb20), X(0x3b47415c), X(0x3b87c9ae), + X(0x3bc853c7), X(0x3c08df57), X(0x3c496c0f), X(0x3c89f99f), + X(0x3cca87b6), X(0x3d0b1605), X(0x3d4ba43d), X(0x3d8c320e), + X(0x3dccbf27), X(0x3e0d4b3a), X(0x3e4dd5f6), X(0x3e8e5f0c), + X(0x3ecee62b), X(0x3f0f6b05), X(0x3f4fed49), X(0x3f906ca8), + X(0x3fd0e8d2), X(0x40116177), X(0x4051d648), X(0x409246f6), + X(0x40d2b330), X(0x41131aa7), X(0x41537d0c), X(0x4193da10), + X(0x41d43162), X(0x421482b4), X(0x4254cdb7), X(0x4295121b), + X(0x42d54f91), X(0x431585ca), X(0x4355b477), X(0x4395db49), + X(0x43d5f9f1), X(0x44161021), X(0x44561d8a), X(0x449621dd), + X(0x44d61ccc), X(0x45160e08), X(0x4555f544), X(0x4595d230), + X(0x45d5a47f), X(0x46156be3), X(0x4655280e), X(0x4694d8b2), + X(0x46d47d82), X(0x4714162f), X(0x4753a26d), X(0x479321ef), + X(0x47d29466), X(0x4811f987), X(0x48515104), X(0x48909a91), + X(0x48cfd5e1), X(0x490f02a7), X(0x494e2098), X(0x498d2f66), + X(0x49cc2ec7), X(0x4a0b1e6f), X(0x4a49fe11), X(0x4a88cd62), + X(0x4ac78c18), X(0x4b0639e6), X(0x4b44d683), X(0x4b8361a2), + X(0x4bc1dafa), X(0x4c004241), X(0x4c3e972c), X(0x4c7cd970), + X(0x4cbb08c5), X(0x4cf924e1), X(0x4d372d7a), X(0x4d752247), + X(0x4db30300), X(0x4df0cf5a), X(0x4e2e870f), X(0x4e6c29d6), + X(0x4ea9b766), X(0x4ee72f78), X(0x4f2491c4), X(0x4f61de02), + X(0x4f9f13ec), X(0x4fdc333b), X(0x50193ba8), X(0x50562ced), + X(0x509306c3), X(0x50cfc8e5), X(0x510c730d), X(0x514904f6), + X(0x51857e5a), X(0x51c1def5), X(0x51fe2682), X(0x523a54bc), + X(0x52766961), X(0x52b2642c), X(0x52ee44d9), X(0x532a0b26), + X(0x5365b6d0), X(0x53a14793), X(0x53dcbd2f), X(0x54181760), + X(0x545355e5), X(0x548e787d), X(0x54c97ee6), X(0x550468e1), + X(0x553f362c), X(0x5579e687), X(0x55b479b3), X(0x55eeef70), + X(0x5629477f), X(0x566381a1), X(0x569d9d97), X(0x56d79b24), + X(0x57117a0a), X(0x574b3a0a), X(0x5784dae9), X(0x57be5c69), + X(0x57f7be4d), X(0x5831005a), X(0x586a2254), X(0x58a32400), + X(0x58dc0522), X(0x5914c57f), X(0x594d64de), X(0x5985e305), + X(0x59be3fba), X(0x59f67ac3), X(0x5a2e93e9), X(0x5a668af2), + X(0x5a9e5fa6), X(0x5ad611ce), X(0x5b0da133), X(0x5b450d9d), + X(0x5b7c56d7), X(0x5bb37ca9), X(0x5bea7ede), X(0x5c215d41), + X(0x5c58179d), X(0x5c8eadbe), X(0x5cc51f6f), X(0x5cfb6c7c), + X(0x5d3194b2), X(0x5d6797de), X(0x5d9d75cf), X(0x5dd32e51), + X(0x5e08c132), X(0x5e3e2e43), X(0x5e737551), X(0x5ea8962d), + X(0x5edd90a7), X(0x5f12648e), X(0x5f4711b4), X(0x5f7b97ea), + X(0x5faff702), X(0x5fe42ece), X(0x60183f20), X(0x604c27cc), + X(0x607fe8a6), X(0x60b38180), X(0x60e6f22f), X(0x611a3a89), + X(0x614d5a62), X(0x61805190), X(0x61b31fe9), X(0x61e5c545), + X(0x62184179), X(0x624a945d), X(0x627cbdca), X(0x62aebd98), + X(0x62e0939f), X(0x63123fba), X(0x6343c1c1), X(0x6375198f), + X(0x63a646ff), X(0x63d749ec), X(0x64082232), X(0x6438cfad), + X(0x64695238), X(0x6499a9b3), X(0x64c9d5f9), X(0x64f9d6ea), + X(0x6529ac63), X(0x65595643), X(0x6588d46a), X(0x65b826b8), + X(0x65e74d0e), X(0x6616474b), X(0x66451552), X(0x6673b704), + X(0x66a22c44), X(0x66d074f4), X(0x66fe90f8), X(0x672c8033), + X(0x675a428a), X(0x6787d7e1), X(0x67b5401f), X(0x67e27b27), + X(0x680f88e1), X(0x683c6934), X(0x68691c05), X(0x6895a13e), + X(0x68c1f8c7), X(0x68ee2287), X(0x691a1e68), X(0x6945ec54), + X(0x69718c35), X(0x699cfdf5), X(0x69c8417f), X(0x69f356c0), + X(0x6a1e3da3), X(0x6a48f615), X(0x6a738002), X(0x6a9ddb5a), + X(0x6ac80808), X(0x6af205fd), X(0x6b1bd526), X(0x6b457575), + X(0x6b6ee6d8), X(0x6b982940), X(0x6bc13c9f), X(0x6bea20e5), + X(0x6c12d605), X(0x6c3b5bf1), X(0x6c63b29c), X(0x6c8bd9fb), + X(0x6cb3d200), X(0x6cdb9aa0), X(0x6d0333d0), X(0x6d2a9d86), + X(0x6d51d7b7), X(0x6d78e25a), X(0x6d9fbd67), X(0x6dc668d3), + X(0x6dece498), X(0x6e1330ad), X(0x6e394d0c), X(0x6e5f39ae), + X(0x6e84f68d), X(0x6eaa83a2), X(0x6ecfe0ea), X(0x6ef50e5e), + X(0x6f1a0bfc), X(0x6f3ed9bf), X(0x6f6377a4), X(0x6f87e5a8), + X(0x6fac23c9), X(0x6fd03206), X(0x6ff4105c), X(0x7017becc), + X(0x703b3d54), X(0x705e8bf5), X(0x7081aaaf), X(0x70a49984), + X(0x70c75874), X(0x70e9e783), X(0x710c46b2), X(0x712e7605), + X(0x7150757f), X(0x71724523), X(0x7193e4f6), X(0x71b554fd), + X(0x71d6953e), X(0x71f7a5bd), X(0x72188681), X(0x72393792), + X(0x7259b8f5), X(0x727a0ab2), X(0x729a2cd2), X(0x72ba1f5d), + X(0x72d9e25c), X(0x72f975d8), X(0x7318d9db), X(0x73380e6f), + X(0x735713a0), X(0x7375e978), X(0x73949003), X(0x73b3074c), + X(0x73d14f61), X(0x73ef684f), X(0x740d5222), X(0x742b0ce9), + X(0x744898b1), X(0x7465f589), X(0x74832381), X(0x74a022a8), + X(0x74bcf30e), X(0x74d994c3), X(0x74f607d8), X(0x75124c5f), + X(0x752e6268), X(0x754a4a05), X(0x7566034b), X(0x75818e4a), + X(0x759ceb16), X(0x75b819c4), X(0x75d31a66), X(0x75eded12), + X(0x760891dc), X(0x762308da), X(0x763d5221), X(0x76576dc8), + X(0x76715be4), X(0x768b1c8c), X(0x76a4afd9), X(0x76be15e0), + X(0x76d74ebb), X(0x76f05a82), X(0x7709394d), X(0x7721eb35), + X(0x773a7054), X(0x7752c8c4), X(0x776af49f), X(0x7782f400), + X(0x779ac701), X(0x77b26dbd), X(0x77c9e851), X(0x77e136d8), + X(0x77f8596f), X(0x780f5032), X(0x78261b3f), X(0x783cbab2), + X(0x78532eaa), X(0x78697745), X(0x787f94a0), X(0x789586db), + X(0x78ab4e15), X(0x78c0ea6d), X(0x78d65c03), X(0x78eba2f7), + X(0x7900bf68), X(0x7915b179), X(0x792a7949), X(0x793f16fb), + X(0x79538aaf), X(0x7967d488), X(0x797bf4a8), X(0x798feb31), + X(0x79a3b846), X(0x79b75c0a), X(0x79cad6a1), X(0x79de282e), + X(0x79f150d5), X(0x7a0450bb), X(0x7a172803), X(0x7a29d6d3), + X(0x7a3c5d50), X(0x7a4ebb9f), X(0x7a60f1e6), X(0x7a73004a), + X(0x7a84e6f2), X(0x7a96a604), X(0x7aa83da7), X(0x7ab9ae01), + X(0x7acaf73a), X(0x7adc1979), X(0x7aed14e6), X(0x7afde9a8), + X(0x7b0e97e8), X(0x7b1f1fcd), X(0x7b2f8182), X(0x7b3fbd2d), + X(0x7b4fd2f9), X(0x7b5fc30f), X(0x7b6f8d98), X(0x7b7f32bd), + X(0x7b8eb2a9), X(0x7b9e0d85), X(0x7bad437d), X(0x7bbc54b9), + X(0x7bcb4166), X(0x7bda09ae), X(0x7be8adbc), X(0x7bf72dbc), + X(0x7c0589d8), X(0x7c13c23d), X(0x7c21d716), X(0x7c2fc88f), + X(0x7c3d96d5), X(0x7c4b4214), X(0x7c58ca78), X(0x7c66302d), + X(0x7c737362), X(0x7c809443), X(0x7c8d92fc), X(0x7c9a6fbc), + X(0x7ca72aaf), X(0x7cb3c404), X(0x7cc03be8), X(0x7ccc9288), + X(0x7cd8c814), X(0x7ce4dcb9), X(0x7cf0d0a5), X(0x7cfca406), + X(0x7d08570c), X(0x7d13e9e5), X(0x7d1f5cbf), X(0x7d2aafca), + X(0x7d35e335), X(0x7d40f72e), X(0x7d4bebe4), X(0x7d56c188), + X(0x7d617848), X(0x7d6c1054), X(0x7d7689db), X(0x7d80e50e), + X(0x7d8b221b), X(0x7d954133), X(0x7d9f4286), X(0x7da92643), + X(0x7db2ec9b), X(0x7dbc95bd), X(0x7dc621da), X(0x7dcf9123), + X(0x7dd8e3c6), X(0x7de219f6), X(0x7deb33e2), X(0x7df431ba), + X(0x7dfd13af), X(0x7e05d9f2), X(0x7e0e84b4), X(0x7e171424), + X(0x7e1f8874), X(0x7e27e1d4), X(0x7e302074), X(0x7e384487), + X(0x7e404e3c), X(0x7e483dc4), X(0x7e501350), X(0x7e57cf11), + X(0x7e5f7138), X(0x7e66f9f4), X(0x7e6e6979), X(0x7e75bff5), + X(0x7e7cfd9a), X(0x7e842298), X(0x7e8b2f22), X(0x7e922366), + X(0x7e98ff97), X(0x7e9fc3e4), X(0x7ea6707f), X(0x7ead0598), + X(0x7eb38360), X(0x7eb9ea07), X(0x7ec039bf), X(0x7ec672b7), + X(0x7ecc9521), X(0x7ed2a12c), X(0x7ed8970a), X(0x7ede76ea), + X(0x7ee440fd), X(0x7ee9f573), X(0x7eef947d), X(0x7ef51e4b), + X(0x7efa930d), X(0x7efff2f2), X(0x7f053e2b), X(0x7f0a74e8), + X(0x7f0f9758), X(0x7f14a5ac), X(0x7f19a013), X(0x7f1e86bc), + X(0x7f2359d8), X(0x7f281995), X(0x7f2cc623), X(0x7f315fb1), + X(0x7f35e66e), X(0x7f3a5a8a), X(0x7f3ebc33), X(0x7f430b98), + X(0x7f4748e7), X(0x7f4b7450), X(0x7f4f8e01), X(0x7f539629), + X(0x7f578cf5), X(0x7f5b7293), X(0x7f5f4732), X(0x7f630b00), + X(0x7f66be2b), X(0x7f6a60df), X(0x7f6df34b), X(0x7f71759b), + X(0x7f74e7fe), X(0x7f784aa0), X(0x7f7b9daf), X(0x7f7ee156), + X(0x7f8215c3), X(0x7f853b22), X(0x7f88519f), X(0x7f8b5967), + X(0x7f8e52a6), X(0x7f913d87), X(0x7f941a36), X(0x7f96e8df), + X(0x7f99a9ad), X(0x7f9c5ccb), X(0x7f9f0265), X(0x7fa19aa5), + X(0x7fa425b5), X(0x7fa6a3c1), X(0x7fa914f3), X(0x7fab7974), + X(0x7fadd16f), X(0x7fb01d0d), X(0x7fb25c78), X(0x7fb48fd9), + X(0x7fb6b75a), X(0x7fb8d323), X(0x7fbae35d), X(0x7fbce831), + X(0x7fbee1c7), X(0x7fc0d047), X(0x7fc2b3d9), X(0x7fc48ca5), + X(0x7fc65ad3), X(0x7fc81e88), X(0x7fc9d7ee), X(0x7fcb872a), + X(0x7fcd2c63), X(0x7fcec7bf), X(0x7fd05966), X(0x7fd1e17c), + X(0x7fd36027), X(0x7fd4d58d), X(0x7fd641d3), X(0x7fd7a51e), + X(0x7fd8ff94), X(0x7fda5157), X(0x7fdb9a8e), X(0x7fdcdb5b), + X(0x7fde13e2), X(0x7fdf4448), X(0x7fe06caf), X(0x7fe18d3b), + X(0x7fe2a60e), X(0x7fe3b74b), X(0x7fe4c114), X(0x7fe5c38b), + X(0x7fe6bed2), X(0x7fe7b30a), X(0x7fe8a055), X(0x7fe986d4), + X(0x7fea66a7), X(0x7feb3ff0), X(0x7fec12cd), X(0x7fecdf5f), + X(0x7feda5c5), X(0x7fee6620), X(0x7fef208d), X(0x7fefd52c), + X(0x7ff0841c), X(0x7ff12d7a), X(0x7ff1d164), X(0x7ff26ff9), + X(0x7ff30955), X(0x7ff39d96), X(0x7ff42cd9), X(0x7ff4b739), + X(0x7ff53cd4), X(0x7ff5bdc5), X(0x7ff63a28), X(0x7ff6b217), + X(0x7ff725af), X(0x7ff7950a), X(0x7ff80043), X(0x7ff86773), + X(0x7ff8cab4), X(0x7ff92a21), X(0x7ff985d1), X(0x7ff9dddf), + X(0x7ffa3262), X(0x7ffa8374), X(0x7ffad12c), X(0x7ffb1ba1), + X(0x7ffb62ec), X(0x7ffba723), X(0x7ffbe85c), X(0x7ffc26b0), + X(0x7ffc6233), X(0x7ffc9afb), X(0x7ffcd11e), X(0x7ffd04b1), + X(0x7ffd35c9), X(0x7ffd647b), X(0x7ffd90da), X(0x7ffdbafa), + X(0x7ffde2f0), X(0x7ffe08ce), X(0x7ffe2ca7), X(0x7ffe4e8e), + X(0x7ffe6e95), X(0x7ffe8cce), X(0x7ffea94a), X(0x7ffec41b), + X(0x7ffedd52), X(0x7ffef4ff), X(0x7fff0b33), X(0x7fff1ffd), + X(0x7fff336e), X(0x7fff4593), X(0x7fff567d), X(0x7fff663a), + X(0x7fff74d8), X(0x7fff8265), X(0x7fff8eee), X(0x7fff9a81), + X(0x7fffa52b), X(0x7fffaef8), X(0x7fffb7f5), X(0x7fffc02d), + X(0x7fffc7ab), X(0x7fffce7c), X(0x7fffd4a9), X(0x7fffda3e), + X(0x7fffdf44), X(0x7fffe3c6), X(0x7fffe7cc), X(0x7fffeb60), + X(0x7fffee8a), X(0x7ffff153), X(0x7ffff3c4), X(0x7ffff5e3), + X(0x7ffff7b8), X(0x7ffff94b), X(0x7ffffaa1), X(0x7ffffbc1), + X(0x7ffffcb2), X(0x7ffffd78), X(0x7ffffe19), X(0x7ffffe9a), + X(0x7ffffeff), X(0x7fffff4e), X(0x7fffff89), X(0x7fffffb3), + X(0x7fffffd2), X(0x7fffffe6), X(0x7ffffff3), X(0x7ffffffa), + X(0x7ffffffe), X(0x7fffffff), X(0x7fffffff), X(0x7fffffff), +}; + +static const LOOKUP_T vwin4096[2048] = { + X(0x000001f0), X(0x00001171), X(0x00003072), X(0x00005ef5), + X(0x00009cf8), X(0x0000ea7c), X(0x00014780), X(0x0001b405), + X(0x0002300b), X(0x0002bb91), X(0x00035698), X(0x0004011e), + X(0x0004bb25), X(0x000584ac), X(0x00065db3), X(0x0007463a), + X(0x00083e41), X(0x000945c7), X(0x000a5ccc), X(0x000b8350), + X(0x000cb954), X(0x000dfed7), X(0x000f53d8), X(0x0010b857), + X(0x00122c55), X(0x0013afd1), X(0x001542ca), X(0x0016e541), + X(0x00189735), X(0x001a58a7), X(0x001c2995), X(0x001e09ff), + X(0x001ff9e6), X(0x0021f948), X(0x00240826), X(0x00262680), + X(0x00285454), X(0x002a91a3), X(0x002cde6c), X(0x002f3aaf), + X(0x0031a66b), X(0x003421a0), X(0x0036ac4f), X(0x00394675), + X(0x003bf014), X(0x003ea92a), X(0x004171b7), X(0x004449bb), + X(0x00473135), X(0x004a2824), X(0x004d2e8a), X(0x00504463), + X(0x005369b2), X(0x00569e74), X(0x0059e2aa), X(0x005d3652), + X(0x0060996d), X(0x00640bf9), X(0x00678df7), X(0x006b1f66), + X(0x006ec045), X(0x00727093), X(0x00763051), X(0x0079ff7d), + X(0x007dde16), X(0x0081cc1d), X(0x0085c991), X(0x0089d671), + X(0x008df2bc), X(0x00921e71), X(0x00965991), X(0x009aa41a), + X(0x009efe0c), X(0x00a36766), X(0x00a7e028), X(0x00ac6850), + X(0x00b0ffde), X(0x00b5a6d1), X(0x00ba5d28), X(0x00bf22e4), + X(0x00c3f802), X(0x00c8dc83), X(0x00cdd065), X(0x00d2d3a8), + X(0x00d7e64a), X(0x00dd084c), X(0x00e239ac), X(0x00e77a69), + X(0x00ecca83), X(0x00f229f9), X(0x00f798ca), X(0x00fd16f5), + X(0x0102a479), X(0x01084155), X(0x010ded89), X(0x0113a913), + X(0x011973f3), X(0x011f4e27), X(0x012537af), X(0x012b308a), + X(0x013138b7), X(0x01375035), X(0x013d7702), X(0x0143ad1f), + X(0x0149f289), X(0x01504741), X(0x0156ab44), X(0x015d1e92), + X(0x0163a12a), X(0x016a330b), X(0x0170d433), X(0x017784a3), + X(0x017e4458), X(0x01851351), X(0x018bf18e), X(0x0192df0d), + X(0x0199dbcd), X(0x01a0e7cd), X(0x01a8030c), X(0x01af2d89), + X(0x01b66743), X(0x01bdb038), X(0x01c50867), X(0x01cc6fd0), + X(0x01d3e670), X(0x01db6c47), X(0x01e30153), X(0x01eaa593), + X(0x01f25907), X(0x01fa1bac), X(0x0201ed81), X(0x0209ce86), + X(0x0211beb8), X(0x0219be17), X(0x0221cca2), X(0x0229ea56), + X(0x02321733), X(0x023a5337), X(0x02429e60), X(0x024af8af), + X(0x02536220), X(0x025bdab3), X(0x02646267), X(0x026cf93a), + X(0x02759f2a), X(0x027e5436), X(0x0287185d), X(0x028feb9d), + X(0x0298cdf4), X(0x02a1bf62), X(0x02aabfe5), X(0x02b3cf7b), + X(0x02bcee23), X(0x02c61bdb), X(0x02cf58a2), X(0x02d8a475), + X(0x02e1ff55), X(0x02eb693e), X(0x02f4e230), X(0x02fe6a29), + X(0x03080127), X(0x0311a729), X(0x031b5c2d), X(0x03252031), + X(0x032ef334), X(0x0338d534), X(0x0342c630), X(0x034cc625), + X(0x0356d512), X(0x0360f2f6), X(0x036b1fce), X(0x03755b99), + X(0x037fa655), X(0x038a0001), X(0x0394689a), X(0x039ee020), + X(0x03a9668f), X(0x03b3fbe6), X(0x03bea024), X(0x03c95347), + X(0x03d4154d), X(0x03dee633), X(0x03e9c5f9), X(0x03f4b49b), + X(0x03ffb219), X(0x040abe71), X(0x0415d9a0), X(0x042103a5), + X(0x042c3c7d), X(0x04378428), X(0x0442daa2), X(0x044e3fea), + X(0x0459b3fd), X(0x046536db), X(0x0470c880), X(0x047c68eb), + X(0x0488181a), X(0x0493d60b), X(0x049fa2bc), X(0x04ab7e2a), + X(0x04b76854), X(0x04c36137), X(0x04cf68d1), X(0x04db7f21), + X(0x04e7a424), X(0x04f3d7d8), X(0x05001a3b), X(0x050c6b4a), + X(0x0518cb04), X(0x05253966), X(0x0531b66e), X(0x053e421a), + X(0x054adc68), X(0x05578555), X(0x05643cdf), X(0x05710304), + X(0x057dd7c1), X(0x058abb15), X(0x0597acfd), X(0x05a4ad76), + X(0x05b1bc7f), X(0x05beda14), X(0x05cc0635), X(0x05d940dd), + X(0x05e68a0b), X(0x05f3e1bd), X(0x060147f0), X(0x060ebca1), + X(0x061c3fcf), X(0x0629d176), X(0x06377194), X(0x06452027), + X(0x0652dd2c), X(0x0660a8a2), X(0x066e8284), X(0x067c6ad1), + X(0x068a6186), X(0x069866a1), X(0x06a67a1e), X(0x06b49bfc), + X(0x06c2cc38), X(0x06d10acf), X(0x06df57bf), X(0x06edb304), + X(0x06fc1c9d), X(0x070a9487), X(0x07191abe), X(0x0727af40), + X(0x0736520b), X(0x0745031c), X(0x0753c270), X(0x07629004), + X(0x07716bd6), X(0x078055e2), X(0x078f4e26), X(0x079e549f), + X(0x07ad694b), X(0x07bc8c26), X(0x07cbbd2e), X(0x07dafc5f), + X(0x07ea49b7), X(0x07f9a533), X(0x08090ed1), X(0x0818868c), + X(0x08280c62), X(0x0837a051), X(0x08474255), X(0x0856f26b), + X(0x0866b091), X(0x08767cc3), X(0x088656fe), X(0x08963f3f), + X(0x08a63584), X(0x08b639c8), X(0x08c64c0a), X(0x08d66c45), + X(0x08e69a77), X(0x08f6d69d), X(0x090720b3), X(0x091778b7), + X(0x0927dea5), X(0x0938527a), X(0x0948d433), X(0x095963cc), + X(0x096a0143), X(0x097aac94), X(0x098b65bb), X(0x099c2cb6), + X(0x09ad0182), X(0x09bde41a), X(0x09ced47d), X(0x09dfd2a5), + X(0x09f0de90), X(0x0a01f83b), X(0x0a131fa3), X(0x0a2454c3), + X(0x0a359798), X(0x0a46e820), X(0x0a584656), X(0x0a69b237), + X(0x0a7b2bc0), X(0x0a8cb2ec), X(0x0a9e47ba), X(0x0aafea24), + X(0x0ac19a29), X(0x0ad357c3), X(0x0ae522ef), X(0x0af6fbab), + X(0x0b08e1f1), X(0x0b1ad5c0), X(0x0b2cd712), X(0x0b3ee5e5), + X(0x0b510234), X(0x0b632bfd), X(0x0b75633b), X(0x0b87a7eb), + X(0x0b99fa08), X(0x0bac5990), X(0x0bbec67e), X(0x0bd140cf), + X(0x0be3c87e), X(0x0bf65d89), X(0x0c08ffeb), X(0x0c1bafa1), + X(0x0c2e6ca6), X(0x0c4136f6), X(0x0c540e8f), X(0x0c66f36c), + X(0x0c79e588), X(0x0c8ce4e1), X(0x0c9ff172), X(0x0cb30b37), + X(0x0cc6322c), X(0x0cd9664d), X(0x0ceca797), X(0x0cfff605), + X(0x0d135193), X(0x0d26ba3d), X(0x0d3a2fff), X(0x0d4db2d5), + X(0x0d6142ba), X(0x0d74dfac), X(0x0d8889a5), X(0x0d9c40a1), + X(0x0db0049d), X(0x0dc3d593), X(0x0dd7b380), X(0x0deb9e60), + X(0x0dff962f), X(0x0e139ae7), X(0x0e27ac85), X(0x0e3bcb05), + X(0x0e4ff662), X(0x0e642e98), X(0x0e7873a2), X(0x0e8cc57d), + X(0x0ea12423), X(0x0eb58f91), X(0x0eca07c2), X(0x0ede8cb1), + X(0x0ef31e5b), X(0x0f07bcba), X(0x0f1c67cb), X(0x0f311f88), + X(0x0f45e3ee), X(0x0f5ab4f7), X(0x0f6f92a0), X(0x0f847ce3), + X(0x0f9973bc), X(0x0fae7726), X(0x0fc3871e), X(0x0fd8a39d), + X(0x0fedcca1), X(0x10030223), X(0x1018441f), X(0x102d9291), + X(0x1042ed74), X(0x105854c3), X(0x106dc879), X(0x10834892), + X(0x1098d508), X(0x10ae6dd8), X(0x10c412fc), X(0x10d9c46f), + X(0x10ef822d), X(0x11054c30), X(0x111b2274), X(0x113104f5), + X(0x1146f3ac), X(0x115cee95), X(0x1172f5ab), X(0x118908e9), + X(0x119f284a), X(0x11b553ca), X(0x11cb8b62), X(0x11e1cf0f), + X(0x11f81ecb), X(0x120e7a90), X(0x1224e25a), X(0x123b5624), + X(0x1251d5e9), X(0x126861a3), X(0x127ef94e), X(0x12959ce3), + X(0x12ac4c5f), X(0x12c307bb), X(0x12d9cef2), X(0x12f0a200), + X(0x130780df), X(0x131e6b8a), X(0x133561fa), X(0x134c642c), + X(0x1363721a), X(0x137a8bbe), X(0x1391b113), X(0x13a8e214), + X(0x13c01eba), X(0x13d76702), X(0x13eebae5), X(0x14061a5e), + X(0x141d8567), X(0x1434fbfb), X(0x144c7e14), X(0x14640bae), + X(0x147ba4c1), X(0x14934949), X(0x14aaf941), X(0x14c2b4a2), + X(0x14da7b67), X(0x14f24d8a), X(0x150a2b06), X(0x152213d5), + X(0x153a07f1), X(0x15520755), X(0x156a11fb), X(0x158227dd), + X(0x159a48f5), X(0x15b2753d), X(0x15caacb1), X(0x15e2ef49), + X(0x15fb3d01), X(0x161395d2), X(0x162bf9b6), X(0x164468a8), + X(0x165ce2a1), X(0x1675679c), X(0x168df793), X(0x16a69280), + X(0x16bf385c), X(0x16d7e922), X(0x16f0a4cc), X(0x17096b54), + X(0x17223cb4), X(0x173b18e5), X(0x1753ffe2), X(0x176cf1a5), + X(0x1785ee27), X(0x179ef562), X(0x17b80750), X(0x17d123eb), + X(0x17ea4b2d), X(0x18037d10), X(0x181cb98d), X(0x1836009e), + X(0x184f523c), X(0x1868ae63), X(0x1882150a), X(0x189b862c), + X(0x18b501c4), X(0x18ce87c9), X(0x18e81836), X(0x1901b305), + X(0x191b582f), X(0x193507ad), X(0x194ec17a), X(0x1968858f), + X(0x198253e5), X(0x199c2c75), X(0x19b60f3a), X(0x19cffc2d), + X(0x19e9f347), X(0x1a03f482), X(0x1a1dffd7), X(0x1a381540), + X(0x1a5234b5), X(0x1a6c5e31), X(0x1a8691ac), X(0x1aa0cf21), + X(0x1abb1687), X(0x1ad567da), X(0x1aefc311), X(0x1b0a2826), + X(0x1b249712), X(0x1b3f0fd0), X(0x1b599257), X(0x1b741ea1), + X(0x1b8eb4a7), X(0x1ba95462), X(0x1bc3fdcd), X(0x1bdeb0de), + X(0x1bf96d91), X(0x1c1433dd), X(0x1c2f03bc), X(0x1c49dd27), + X(0x1c64c017), X(0x1c7fac85), X(0x1c9aa269), X(0x1cb5a1be), + X(0x1cd0aa7c), X(0x1cebbc9c), X(0x1d06d816), X(0x1d21fce4), + X(0x1d3d2aff), X(0x1d586260), X(0x1d73a2fe), X(0x1d8eecd4), + X(0x1daa3fda), X(0x1dc59c09), X(0x1de1015a), X(0x1dfc6fc5), + X(0x1e17e743), X(0x1e3367cd), X(0x1e4ef15b), X(0x1e6a83e7), + X(0x1e861f6a), X(0x1ea1c3da), X(0x1ebd7133), X(0x1ed9276b), + X(0x1ef4e67c), X(0x1f10ae5e), X(0x1f2c7f0a), X(0x1f485879), + X(0x1f643aa2), X(0x1f80257f), X(0x1f9c1908), X(0x1fb81536), + X(0x1fd41a00), X(0x1ff02761), X(0x200c3d4f), X(0x20285bc3), + X(0x204482b7), X(0x2060b221), X(0x207ce9fb), X(0x20992a3e), + X(0x20b572e0), X(0x20d1c3dc), X(0x20ee1d28), X(0x210a7ebe), + X(0x2126e895), X(0x21435aa6), X(0x215fd4ea), X(0x217c5757), + X(0x2198e1e8), X(0x21b57493), X(0x21d20f51), X(0x21eeb21b), + X(0x220b5ce7), X(0x22280fb0), X(0x2244ca6c), X(0x22618d13), + X(0x227e579f), X(0x229b2a06), X(0x22b80442), X(0x22d4e649), + X(0x22f1d015), X(0x230ec19d), X(0x232bbad9), X(0x2348bbc1), + X(0x2365c44c), X(0x2382d474), X(0x239fec30), X(0x23bd0b78), + X(0x23da3244), X(0x23f7608b), X(0x24149646), X(0x2431d36c), + X(0x244f17f5), X(0x246c63da), X(0x2489b711), X(0x24a71193), + X(0x24c47358), X(0x24e1dc57), X(0x24ff4c88), X(0x251cc3e2), + X(0x253a425e), X(0x2557c7f4), X(0x2575549a), X(0x2592e848), + X(0x25b082f7), X(0x25ce249e), X(0x25ebcd34), X(0x26097cb2), + X(0x2627330e), X(0x2644f040), X(0x2662b441), X(0x26807f07), + X(0x269e5089), X(0x26bc28c1), X(0x26da07a4), X(0x26f7ed2b), + X(0x2715d94d), X(0x2733cc02), X(0x2751c540), X(0x276fc500), + X(0x278dcb39), X(0x27abd7e2), X(0x27c9eaf3), X(0x27e80463), + X(0x28062429), X(0x28244a3e), X(0x28427697), X(0x2860a92d), + X(0x287ee1f7), X(0x289d20eb), X(0x28bb6603), X(0x28d9b134), + X(0x28f80275), X(0x291659c0), X(0x2934b709), X(0x29531a49), + X(0x29718378), X(0x298ff28b), X(0x29ae677b), X(0x29cce23e), + X(0x29eb62cb), X(0x2a09e91b), X(0x2a287523), X(0x2a4706dc), + X(0x2a659e3c), X(0x2a843b39), X(0x2aa2ddcd), X(0x2ac185ec), + X(0x2ae0338f), X(0x2afee6ad), X(0x2b1d9f3c), X(0x2b3c5d33), + X(0x2b5b208b), X(0x2b79e939), X(0x2b98b734), X(0x2bb78a74), + X(0x2bd662ef), X(0x2bf5409d), X(0x2c142374), X(0x2c330b6b), + X(0x2c51f87a), X(0x2c70ea97), X(0x2c8fe1b9), X(0x2caeddd6), + X(0x2ccddee7), X(0x2cece4e1), X(0x2d0befbb), X(0x2d2aff6d), + X(0x2d4a13ec), X(0x2d692d31), X(0x2d884b32), X(0x2da76de4), + X(0x2dc69540), X(0x2de5c13d), X(0x2e04f1d0), X(0x2e2426f0), + X(0x2e436095), X(0x2e629eb4), X(0x2e81e146), X(0x2ea1283f), + X(0x2ec07398), X(0x2edfc347), X(0x2eff1742), X(0x2f1e6f80), + X(0x2f3dcbf8), X(0x2f5d2ca0), X(0x2f7c916f), X(0x2f9bfa5c), + X(0x2fbb675d), X(0x2fdad869), X(0x2ffa4d76), X(0x3019c67b), + X(0x3039436f), X(0x3058c448), X(0x307848fc), X(0x3097d183), + X(0x30b75dd3), X(0x30d6ede2), X(0x30f681a6), X(0x31161917), + X(0x3135b42b), X(0x315552d8), X(0x3174f514), X(0x31949ad7), + X(0x31b44417), X(0x31d3f0ca), X(0x31f3a0e6), X(0x32135462), + X(0x32330b35), X(0x3252c555), X(0x327282b7), X(0x32924354), + X(0x32b20720), X(0x32d1ce13), X(0x32f19823), X(0x33116546), + X(0x33313573), X(0x3351089f), X(0x3370dec2), X(0x3390b7d1), + X(0x33b093c3), X(0x33d0728f), X(0x33f05429), X(0x3410388a), + X(0x34301fa7), X(0x34500977), X(0x346ff5ef), X(0x348fe506), + X(0x34afd6b3), X(0x34cfcaeb), X(0x34efc1a5), X(0x350fbad7), + X(0x352fb678), X(0x354fb47d), X(0x356fb4dd), X(0x358fb78e), + X(0x35afbc86), X(0x35cfc3bc), X(0x35efcd25), X(0x360fd8b8), + X(0x362fe66c), X(0x364ff636), X(0x3670080c), X(0x36901be5), + X(0x36b031b7), X(0x36d04978), X(0x36f0631e), X(0x37107ea0), + X(0x37309bf3), X(0x3750bb0e), X(0x3770dbe6), X(0x3790fe73), + X(0x37b122aa), X(0x37d14881), X(0x37f16fee), X(0x381198e8), + X(0x3831c365), X(0x3851ef5a), X(0x38721cbe), X(0x38924b87), + X(0x38b27bac), X(0x38d2ad21), X(0x38f2dfde), X(0x391313d8), + X(0x39334906), X(0x39537f5d), X(0x3973b6d4), X(0x3993ef60), + X(0x39b428f9), X(0x39d46393), X(0x39f49f25), X(0x3a14dba6), + X(0x3a35190a), X(0x3a555748), X(0x3a759657), X(0x3a95d62c), + X(0x3ab616be), X(0x3ad65801), X(0x3af699ed), X(0x3b16dc78), + X(0x3b371f97), X(0x3b576341), X(0x3b77a76c), X(0x3b97ec0d), + X(0x3bb8311b), X(0x3bd8768b), X(0x3bf8bc55), X(0x3c19026d), + X(0x3c3948ca), X(0x3c598f62), X(0x3c79d62b), X(0x3c9a1d1b), + X(0x3cba6428), X(0x3cdaab48), X(0x3cfaf271), X(0x3d1b3999), + X(0x3d3b80b6), X(0x3d5bc7be), X(0x3d7c0ea8), X(0x3d9c5569), + X(0x3dbc9bf7), X(0x3ddce248), X(0x3dfd2852), X(0x3e1d6e0c), + X(0x3e3db36c), X(0x3e5df866), X(0x3e7e3cf2), X(0x3e9e8106), + X(0x3ebec497), X(0x3edf079b), X(0x3eff4a09), X(0x3f1f8bd7), + X(0x3f3fccfa), X(0x3f600d69), X(0x3f804d1a), X(0x3fa08c02), + X(0x3fc0ca19), X(0x3fe10753), X(0x400143a7), X(0x40217f0a), + X(0x4041b974), X(0x4061f2da), X(0x40822b32), X(0x40a26272), + X(0x40c29891), X(0x40e2cd83), X(0x41030140), X(0x412333bd), + X(0x414364f1), X(0x416394d2), X(0x4183c355), X(0x41a3f070), + X(0x41c41c1b), X(0x41e4464a), X(0x42046ef4), X(0x42249610), + X(0x4244bb92), X(0x4264df72), X(0x428501a5), X(0x42a52222), + X(0x42c540de), X(0x42e55dd0), X(0x430578ed), X(0x4325922d), + X(0x4345a985), X(0x4365beeb), X(0x4385d255), X(0x43a5e3ba), + X(0x43c5f30f), X(0x43e6004b), X(0x44060b65), X(0x44261451), + X(0x44461b07), X(0x44661f7c), X(0x448621a7), X(0x44a6217d), + X(0x44c61ef6), X(0x44e61a07), X(0x450612a6), X(0x452608ca), + X(0x4545fc69), X(0x4565ed79), X(0x4585dbf1), X(0x45a5c7c6), + X(0x45c5b0ef), X(0x45e59761), X(0x46057b15), X(0x46255bfe), + X(0x46453a15), X(0x4665154f), X(0x4684eda2), X(0x46a4c305), + X(0x46c4956e), X(0x46e464d3), X(0x4704312b), X(0x4723fa6c), + X(0x4743c08d), X(0x47638382), X(0x47834344), X(0x47a2ffc9), + X(0x47c2b906), X(0x47e26ef2), X(0x48022183), X(0x4821d0b1), + X(0x48417c71), X(0x486124b9), X(0x4880c981), X(0x48a06abe), + X(0x48c00867), X(0x48dfa272), X(0x48ff38d6), X(0x491ecb8a), + X(0x493e5a84), X(0x495de5b9), X(0x497d6d22), X(0x499cf0b4), + X(0x49bc7066), X(0x49dbec2e), X(0x49fb6402), X(0x4a1ad7db), + X(0x4a3a47ad), X(0x4a59b370), X(0x4a791b1a), X(0x4a987ea1), + X(0x4ab7ddfd), X(0x4ad73924), X(0x4af6900c), X(0x4b15e2ad), + X(0x4b3530fc), X(0x4b547af1), X(0x4b73c082), X(0x4b9301a6), + X(0x4bb23e53), X(0x4bd17681), X(0x4bf0aa25), X(0x4c0fd937), + X(0x4c2f03ae), X(0x4c4e297f), X(0x4c6d4aa3), X(0x4c8c670f), + X(0x4cab7eba), X(0x4cca919c), X(0x4ce99fab), X(0x4d08a8de), + X(0x4d27ad2c), X(0x4d46ac8b), X(0x4d65a6f3), X(0x4d849c5a), + X(0x4da38cb7), X(0x4dc27802), X(0x4de15e31), X(0x4e003f3a), + X(0x4e1f1b16), X(0x4e3df1ba), X(0x4e5cc31e), X(0x4e7b8f3a), + X(0x4e9a5603), X(0x4eb91771), X(0x4ed7d37b), X(0x4ef68a18), + X(0x4f153b3f), X(0x4f33e6e7), X(0x4f528d08), X(0x4f712d97), + X(0x4f8fc88e), X(0x4fae5de1), X(0x4fcced8a), X(0x4feb777f), + X(0x5009fbb6), X(0x50287a28), X(0x5046f2cc), X(0x50656598), + X(0x5083d284), X(0x50a23988), X(0x50c09a9a), X(0x50def5b1), + X(0x50fd4ac7), X(0x511b99d0), X(0x5139e2c5), X(0x5158259e), + X(0x51766251), X(0x519498d6), X(0x51b2c925), X(0x51d0f334), + X(0x51ef16fb), X(0x520d3473), X(0x522b4b91), X(0x52495c4e), + X(0x526766a2), X(0x52856a83), X(0x52a367e9), X(0x52c15ecd), + X(0x52df4f24), X(0x52fd38e8), X(0x531b1c10), X(0x5338f892), + X(0x5356ce68), X(0x53749d89), X(0x539265eb), X(0x53b02788), + X(0x53cde257), X(0x53eb964f), X(0x54094369), X(0x5426e99c), + X(0x544488df), X(0x5462212c), X(0x547fb279), X(0x549d3cbe), + X(0x54babff4), X(0x54d83c12), X(0x54f5b110), X(0x55131ee7), + X(0x5530858d), X(0x554de4fc), X(0x556b3d2a), X(0x55888e11), + X(0x55a5d7a8), X(0x55c319e7), X(0x55e054c7), X(0x55fd883f), + X(0x561ab447), X(0x5637d8d8), X(0x5654f5ea), X(0x56720b75), + X(0x568f1971), X(0x56ac1fd7), X(0x56c91e9e), X(0x56e615c0), + X(0x57030534), X(0x571fecf2), X(0x573cccf3), X(0x5759a530), + X(0x577675a0), X(0x57933e3c), X(0x57affefd), X(0x57ccb7db), + X(0x57e968ce), X(0x580611cf), X(0x5822b2d6), X(0x583f4bdd), + X(0x585bdcdb), X(0x587865c9), X(0x5894e69f), X(0x58b15f57), + X(0x58cdcfe9), X(0x58ea384e), X(0x5906987d), X(0x5922f071), + X(0x593f4022), X(0x595b8788), X(0x5977c69c), X(0x5993fd57), + X(0x59b02bb2), X(0x59cc51a6), X(0x59e86f2c), X(0x5a04843c), + X(0x5a2090d0), X(0x5a3c94e0), X(0x5a589065), X(0x5a748359), + X(0x5a906db4), X(0x5aac4f70), X(0x5ac82884), X(0x5ae3f8ec), + X(0x5affc09f), X(0x5b1b7f97), X(0x5b3735cd), X(0x5b52e33a), + X(0x5b6e87d8), X(0x5b8a239f), X(0x5ba5b689), X(0x5bc1408f), + X(0x5bdcc1aa), X(0x5bf839d5), X(0x5c13a907), X(0x5c2f0f3b), + X(0x5c4a6c6a), X(0x5c65c08d), X(0x5c810b9e), X(0x5c9c4d97), + X(0x5cb78670), X(0x5cd2b623), X(0x5ceddcaa), X(0x5d08f9ff), + X(0x5d240e1b), X(0x5d3f18f8), X(0x5d5a1a8f), X(0x5d7512da), + X(0x5d9001d3), X(0x5daae773), X(0x5dc5c3b5), X(0x5de09692), + X(0x5dfb6004), X(0x5e162004), X(0x5e30d68d), X(0x5e4b8399), + X(0x5e662721), X(0x5e80c11f), X(0x5e9b518e), X(0x5eb5d867), + X(0x5ed055a4), X(0x5eeac940), X(0x5f053334), X(0x5f1f937b), + X(0x5f39ea0f), X(0x5f5436ea), X(0x5f6e7a06), X(0x5f88b35d), + X(0x5fa2e2e9), X(0x5fbd08a6), X(0x5fd7248d), X(0x5ff13698), + X(0x600b3ec2), X(0x60253d05), X(0x603f315b), X(0x60591bc0), + X(0x6072fc2d), X(0x608cd29e), X(0x60a69f0b), X(0x60c06171), + X(0x60da19ca), X(0x60f3c80f), X(0x610d6c3d), X(0x6127064d), + X(0x6140963a), X(0x615a1bff), X(0x61739797), X(0x618d08fc), + X(0x61a67029), X(0x61bfcd1a), X(0x61d91fc8), X(0x61f2682f), + X(0x620ba64a), X(0x6224da13), X(0x623e0386), X(0x6257229d), + X(0x62703754), X(0x628941a6), X(0x62a2418e), X(0x62bb3706), + X(0x62d4220a), X(0x62ed0296), X(0x6305d8a3), X(0x631ea42f), + X(0x63376533), X(0x63501bab), X(0x6368c793), X(0x638168e5), + X(0x6399ff9e), X(0x63b28bb8), X(0x63cb0d2f), X(0x63e383ff), + X(0x63fbf022), X(0x64145195), X(0x642ca853), X(0x6444f457), + X(0x645d359e), X(0x64756c22), X(0x648d97e0), X(0x64a5b8d3), + X(0x64bdcef6), X(0x64d5da47), X(0x64eddabf), X(0x6505d05c), + X(0x651dbb19), X(0x65359af2), X(0x654d6fe3), X(0x656539e7), + X(0x657cf8fb), X(0x6594ad1b), X(0x65ac5643), X(0x65c3f46e), + X(0x65db8799), X(0x65f30fc0), X(0x660a8ce0), X(0x6621fef3), + X(0x663965f7), X(0x6650c1e7), X(0x666812c1), X(0x667f5880), + X(0x66969320), X(0x66adc29e), X(0x66c4e6f7), X(0x66dc0026), + X(0x66f30e28), X(0x670a10fa), X(0x67210898), X(0x6737f4ff), + X(0x674ed62b), X(0x6765ac19), X(0x677c76c5), X(0x6793362c), + X(0x67a9ea4b), X(0x67c0931f), X(0x67d730a3), X(0x67edc2d6), + X(0x680449b3), X(0x681ac538), X(0x68313562), X(0x68479a2d), + X(0x685df396), X(0x6874419b), X(0x688a8438), X(0x68a0bb6a), + X(0x68b6e72e), X(0x68cd0782), X(0x68e31c63), X(0x68f925cd), + X(0x690f23be), X(0x69251633), X(0x693afd29), X(0x6950d89e), + X(0x6966a88f), X(0x697c6cf8), X(0x699225d9), X(0x69a7d32d), + X(0x69bd74f3), X(0x69d30b27), X(0x69e895c8), X(0x69fe14d2), + X(0x6a138844), X(0x6a28f01b), X(0x6a3e4c54), X(0x6a539ced), + X(0x6a68e1e4), X(0x6a7e1b37), X(0x6a9348e3), X(0x6aa86ae6), + X(0x6abd813d), X(0x6ad28be7), X(0x6ae78ae2), X(0x6afc7e2b), + X(0x6b1165c0), X(0x6b26419f), X(0x6b3b11c7), X(0x6b4fd634), + X(0x6b648ee6), X(0x6b793bda), X(0x6b8ddd0e), X(0x6ba27281), + X(0x6bb6fc31), X(0x6bcb7a1b), X(0x6bdfec3e), X(0x6bf45299), + X(0x6c08ad29), X(0x6c1cfbed), X(0x6c313ee4), X(0x6c45760a), + X(0x6c59a160), X(0x6c6dc0e4), X(0x6c81d493), X(0x6c95dc6d), + X(0x6ca9d86f), X(0x6cbdc899), X(0x6cd1acea), X(0x6ce5855f), + X(0x6cf951f7), X(0x6d0d12b1), X(0x6d20c78c), X(0x6d347087), + X(0x6d480da0), X(0x6d5b9ed6), X(0x6d6f2427), X(0x6d829d94), + X(0x6d960b1a), X(0x6da96cb9), X(0x6dbcc270), X(0x6dd00c3c), + X(0x6de34a1f), X(0x6df67c16), X(0x6e09a221), X(0x6e1cbc3f), + X(0x6e2fca6e), X(0x6e42ccaf), X(0x6e55c300), X(0x6e68ad60), + X(0x6e7b8bd0), X(0x6e8e5e4d), X(0x6ea124d8), X(0x6eb3df70), + X(0x6ec68e13), X(0x6ed930c3), X(0x6eebc77d), X(0x6efe5242), + X(0x6f10d111), X(0x6f2343e9), X(0x6f35aacb), X(0x6f4805b5), + X(0x6f5a54a8), X(0x6f6c97a2), X(0x6f7ecea4), X(0x6f90f9ae), + X(0x6fa318be), X(0x6fb52bd6), X(0x6fc732f4), X(0x6fd92e19), + X(0x6feb1d44), X(0x6ffd0076), X(0x700ed7ad), X(0x7020a2eb), + X(0x7032622f), X(0x7044157a), X(0x7055bcca), X(0x70675821), + X(0x7078e77e), X(0x708a6ae2), X(0x709be24c), X(0x70ad4dbd), + X(0x70bead36), X(0x70d000b5), X(0x70e1483d), X(0x70f283cc), + X(0x7103b363), X(0x7114d704), X(0x7125eead), X(0x7136fa60), + X(0x7147fa1c), X(0x7158ede4), X(0x7169d5b6), X(0x717ab193), + X(0x718b817d), X(0x719c4573), X(0x71acfd76), X(0x71bda988), + X(0x71ce49a8), X(0x71deddd7), X(0x71ef6617), X(0x71ffe267), + X(0x721052ca), X(0x7220b73e), X(0x72310fc6), X(0x72415c62), + X(0x72519d14), X(0x7261d1db), X(0x7271faba), X(0x728217b1), + X(0x729228c0), X(0x72a22dea), X(0x72b22730), X(0x72c21491), + X(0x72d1f611), X(0x72e1cbaf), X(0x72f1956c), X(0x7301534c), + X(0x7311054d), X(0x7320ab72), X(0x733045bc), X(0x733fd42d), + X(0x734f56c5), X(0x735ecd86), X(0x736e3872), X(0x737d9789), + X(0x738ceacf), X(0x739c3243), X(0x73ab6de7), X(0x73ba9dbe), + X(0x73c9c1c8), X(0x73d8da08), X(0x73e7e67f), X(0x73f6e72e), + X(0x7405dc17), X(0x7414c53c), X(0x7423a29f), X(0x74327442), + X(0x74413a26), X(0x744ff44d), X(0x745ea2b9), X(0x746d456c), + X(0x747bdc68), X(0x748a67ae), X(0x7498e741), X(0x74a75b23), + X(0x74b5c356), X(0x74c41fdb), X(0x74d270b6), X(0x74e0b5e7), + X(0x74eeef71), X(0x74fd1d57), X(0x750b3f9a), X(0x7519563c), + X(0x75276140), X(0x753560a8), X(0x75435477), X(0x75513cae), + X(0x755f1951), X(0x756cea60), X(0x757aafdf), X(0x758869d1), + X(0x75961837), X(0x75a3bb14), X(0x75b1526a), X(0x75bede3c), + X(0x75cc5e8d), X(0x75d9d35f), X(0x75e73cb5), X(0x75f49a91), + X(0x7601ecf6), X(0x760f33e6), X(0x761c6f65), X(0x76299f74), + X(0x7636c417), X(0x7643dd51), X(0x7650eb24), X(0x765ded93), + X(0x766ae4a0), X(0x7677d050), X(0x7684b0a4), X(0x7691859f), + X(0x769e4f45), X(0x76ab0d98), X(0x76b7c09c), X(0x76c46852), + X(0x76d104bf), X(0x76dd95e6), X(0x76ea1bc9), X(0x76f6966b), + X(0x770305d0), X(0x770f69fb), X(0x771bc2ef), X(0x772810af), + X(0x7734533e), X(0x77408aa0), X(0x774cb6d7), X(0x7758d7e8), + X(0x7764edd5), X(0x7770f8a2), X(0x777cf852), X(0x7788ece8), + X(0x7794d668), X(0x77a0b4d5), X(0x77ac8833), X(0x77b85085), + X(0x77c40dce), X(0x77cfc013), X(0x77db6756), X(0x77e7039b), + X(0x77f294e6), X(0x77fe1b3b), X(0x7809969c), X(0x7815070e), + X(0x78206c93), X(0x782bc731), X(0x783716ea), X(0x78425bc3), + X(0x784d95be), X(0x7858c4e1), X(0x7863e92d), X(0x786f02a8), + X(0x787a1156), X(0x78851539), X(0x78900e56), X(0x789afcb1), + X(0x78a5e04d), X(0x78b0b92f), X(0x78bb875b), X(0x78c64ad4), + X(0x78d1039e), X(0x78dbb1be), X(0x78e65537), X(0x78f0ee0e), + X(0x78fb7c46), X(0x7905ffe4), X(0x791078ec), X(0x791ae762), + X(0x79254b4a), X(0x792fa4a7), X(0x7939f380), X(0x794437d7), + X(0x794e71b0), X(0x7958a111), X(0x7962c5fd), X(0x796ce078), + X(0x7976f087), X(0x7980f62f), X(0x798af173), X(0x7994e258), + X(0x799ec8e2), X(0x79a8a515), X(0x79b276f7), X(0x79bc3e8b), + X(0x79c5fbd6), X(0x79cfaedc), X(0x79d957a2), X(0x79e2f62c), + X(0x79ec8a7f), X(0x79f6149f), X(0x79ff9492), X(0x7a090a5a), + X(0x7a1275fe), X(0x7a1bd781), X(0x7a252ee9), X(0x7a2e7c39), + X(0x7a37bf77), X(0x7a40f8a7), X(0x7a4a27ce), X(0x7a534cf0), + X(0x7a5c6813), X(0x7a65793b), X(0x7a6e806d), X(0x7a777dad), + X(0x7a807100), X(0x7a895a6b), X(0x7a9239f4), X(0x7a9b0f9e), + X(0x7aa3db6f), X(0x7aac9d6b), X(0x7ab55597), X(0x7abe03f9), + X(0x7ac6a895), X(0x7acf4370), X(0x7ad7d48f), X(0x7ae05bf6), + X(0x7ae8d9ac), X(0x7af14db5), X(0x7af9b815), X(0x7b0218d2), + X(0x7b0a6ff2), X(0x7b12bd78), X(0x7b1b016a), X(0x7b233bce), + X(0x7b2b6ca7), X(0x7b3393fc), X(0x7b3bb1d1), X(0x7b43c62c), + X(0x7b4bd111), X(0x7b53d286), X(0x7b5bca90), X(0x7b63b935), + X(0x7b6b9e78), X(0x7b737a61), X(0x7b7b4cf3), X(0x7b831634), + X(0x7b8ad629), X(0x7b928cd8), X(0x7b9a3a45), X(0x7ba1de77), + X(0x7ba97972), X(0x7bb10b3c), X(0x7bb893d9), X(0x7bc01350), + X(0x7bc789a6), X(0x7bcef6e0), X(0x7bd65b03), X(0x7bddb616), + X(0x7be5081c), X(0x7bec511c), X(0x7bf3911b), X(0x7bfac81f), + X(0x7c01f62c), X(0x7c091b49), X(0x7c10377b), X(0x7c174ac7), + X(0x7c1e5532), X(0x7c2556c4), X(0x7c2c4f80), X(0x7c333f6c), + X(0x7c3a268e), X(0x7c4104ec), X(0x7c47da8a), X(0x7c4ea76f), + X(0x7c556ba1), X(0x7c5c2724), X(0x7c62d9fe), X(0x7c698435), + X(0x7c7025cf), X(0x7c76bed0), X(0x7c7d4f40), X(0x7c83d723), + X(0x7c8a567f), X(0x7c90cd5a), X(0x7c973bb9), X(0x7c9da1a2), + X(0x7ca3ff1b), X(0x7caa542a), X(0x7cb0a0d3), X(0x7cb6e51e), + X(0x7cbd210f), X(0x7cc354ac), X(0x7cc97ffc), X(0x7ccfa304), + X(0x7cd5bdc9), X(0x7cdbd051), X(0x7ce1daa3), X(0x7ce7dcc3), + X(0x7cedd6b8), X(0x7cf3c888), X(0x7cf9b238), X(0x7cff93cf), + X(0x7d056d51), X(0x7d0b3ec5), X(0x7d110830), X(0x7d16c99a), + X(0x7d1c8306), X(0x7d22347c), X(0x7d27de00), X(0x7d2d7f9a), + X(0x7d33194f), X(0x7d38ab24), X(0x7d3e351f), X(0x7d43b748), + X(0x7d4931a2), X(0x7d4ea435), X(0x7d540f06), X(0x7d59721b), + X(0x7d5ecd7b), X(0x7d64212a), X(0x7d696d2f), X(0x7d6eb190), + X(0x7d73ee53), X(0x7d79237e), X(0x7d7e5117), X(0x7d837723), + X(0x7d8895a9), X(0x7d8dacae), X(0x7d92bc3a), X(0x7d97c451), + X(0x7d9cc4f9), X(0x7da1be39), X(0x7da6b017), X(0x7dab9a99), + X(0x7db07dc4), X(0x7db5599e), X(0x7dba2e2f), X(0x7dbefb7b), + X(0x7dc3c189), X(0x7dc8805e), X(0x7dcd3802), X(0x7dd1e879), + X(0x7dd691ca), X(0x7ddb33fb), X(0x7ddfcf12), X(0x7de46315), + X(0x7de8f00a), X(0x7ded75f8), X(0x7df1f4e3), X(0x7df66cd3), + X(0x7dfaddcd), X(0x7dff47d7), X(0x7e03aaf8), X(0x7e080735), + X(0x7e0c5c95), X(0x7e10ab1e), X(0x7e14f2d5), X(0x7e1933c1), + X(0x7e1d6de8), X(0x7e21a150), X(0x7e25cdff), X(0x7e29f3fc), + X(0x7e2e134c), X(0x7e322bf5), X(0x7e363dfd), X(0x7e3a496b), + X(0x7e3e4e45), X(0x7e424c90), X(0x7e464454), X(0x7e4a3595), + X(0x7e4e205a), X(0x7e5204aa), X(0x7e55e289), X(0x7e59b9ff), + X(0x7e5d8b12), X(0x7e6155c7), X(0x7e651a24), X(0x7e68d831), + X(0x7e6c8ff2), X(0x7e70416e), X(0x7e73ecac), X(0x7e7791b0), + X(0x7e7b3082), X(0x7e7ec927), X(0x7e825ba6), X(0x7e85e804), + X(0x7e896e48), X(0x7e8cee77), X(0x7e906899), X(0x7e93dcb2), + X(0x7e974aca), X(0x7e9ab2e5), X(0x7e9e150b), X(0x7ea17141), + X(0x7ea4c78e), X(0x7ea817f7), X(0x7eab6283), X(0x7eaea737), + X(0x7eb1e61a), X(0x7eb51f33), X(0x7eb85285), X(0x7ebb8019), + X(0x7ebea7f4), X(0x7ec1ca1d), X(0x7ec4e698), X(0x7ec7fd6d), + X(0x7ecb0ea1), X(0x7ece1a3a), X(0x7ed1203f), X(0x7ed420b6), + X(0x7ed71ba4), X(0x7eda110f), X(0x7edd00ff), X(0x7edfeb78), + X(0x7ee2d081), X(0x7ee5b01f), X(0x7ee88a5a), X(0x7eeb5f36), + X(0x7eee2eba), X(0x7ef0f8ed), X(0x7ef3bdd3), X(0x7ef67d73), + X(0x7ef937d3), X(0x7efbecf9), X(0x7efe9ceb), X(0x7f0147ae), + X(0x7f03ed4a), X(0x7f068dc4), X(0x7f092922), X(0x7f0bbf69), + X(0x7f0e50a1), X(0x7f10dcce), X(0x7f1363f7), X(0x7f15e622), + X(0x7f186355), X(0x7f1adb95), X(0x7f1d4ee9), X(0x7f1fbd57), + X(0x7f2226e4), X(0x7f248b96), X(0x7f26eb74), X(0x7f294683), + X(0x7f2b9cc9), X(0x7f2dee4d), X(0x7f303b13), X(0x7f328322), + X(0x7f34c680), X(0x7f370533), X(0x7f393f40), X(0x7f3b74ad), + X(0x7f3da581), X(0x7f3fd1c1), X(0x7f41f972), X(0x7f441c9c), + X(0x7f463b43), X(0x7f48556d), X(0x7f4a6b21), X(0x7f4c7c64), + X(0x7f4e893c), X(0x7f5091ae), X(0x7f5295c1), X(0x7f54957a), + X(0x7f5690e0), X(0x7f5887f7), X(0x7f5a7ac5), X(0x7f5c6951), + X(0x7f5e53a0), X(0x7f6039b8), X(0x7f621b9e), X(0x7f63f958), + X(0x7f65d2ed), X(0x7f67a861), X(0x7f6979ba), X(0x7f6b46ff), + X(0x7f6d1034), X(0x7f6ed560), X(0x7f709687), X(0x7f7253b1), + X(0x7f740ce1), X(0x7f75c21f), X(0x7f777370), X(0x7f7920d8), + X(0x7f7aca5f), X(0x7f7c7008), X(0x7f7e11db), X(0x7f7fafdd), + X(0x7f814a13), X(0x7f82e082), X(0x7f847331), X(0x7f860224), + X(0x7f878d62), X(0x7f8914f0), X(0x7f8a98d4), X(0x7f8c1912), + X(0x7f8d95b0), X(0x7f8f0eb5), X(0x7f908425), X(0x7f91f605), + X(0x7f93645c), X(0x7f94cf2f), X(0x7f963683), X(0x7f979a5d), + X(0x7f98fac4), X(0x7f9a57bb), X(0x7f9bb14a), X(0x7f9d0775), + X(0x7f9e5a41), X(0x7f9fa9b4), X(0x7fa0f5d3), X(0x7fa23ea4), + X(0x7fa3842b), X(0x7fa4c66f), X(0x7fa60575), X(0x7fa74141), + X(0x7fa879d9), X(0x7fa9af42), X(0x7faae182), X(0x7fac109e), + X(0x7fad3c9a), X(0x7fae657d), X(0x7faf8b4c), X(0x7fb0ae0b), + X(0x7fb1cdc0), X(0x7fb2ea70), X(0x7fb40420), X(0x7fb51ad5), + X(0x7fb62e95), X(0x7fb73f64), X(0x7fb84d48), X(0x7fb95846), + X(0x7fba6062), X(0x7fbb65a2), X(0x7fbc680c), X(0x7fbd67a3), + X(0x7fbe646d), X(0x7fbf5e70), X(0x7fc055af), X(0x7fc14a31), + X(0x7fc23bf9), X(0x7fc32b0d), X(0x7fc41773), X(0x7fc5012e), + X(0x7fc5e844), X(0x7fc6ccba), X(0x7fc7ae94), X(0x7fc88dd8), + X(0x7fc96a8a), X(0x7fca44af), X(0x7fcb1c4c), X(0x7fcbf167), + X(0x7fccc403), X(0x7fcd9425), X(0x7fce61d3), X(0x7fcf2d11), + X(0x7fcff5e3), X(0x7fd0bc4f), X(0x7fd1805a), X(0x7fd24207), + X(0x7fd3015c), X(0x7fd3be5d), X(0x7fd47910), X(0x7fd53178), + X(0x7fd5e79b), X(0x7fd69b7c), X(0x7fd74d21), X(0x7fd7fc8e), + X(0x7fd8a9c8), X(0x7fd954d4), X(0x7fd9fdb5), X(0x7fdaa471), + X(0x7fdb490b), X(0x7fdbeb89), X(0x7fdc8bef), X(0x7fdd2a42), + X(0x7fddc685), X(0x7fde60be), X(0x7fdef8f0), X(0x7fdf8f20), + X(0x7fe02353), X(0x7fe0b58d), X(0x7fe145d3), X(0x7fe1d428), + X(0x7fe26091), X(0x7fe2eb12), X(0x7fe373b0), X(0x7fe3fa6f), + X(0x7fe47f53), X(0x7fe50260), X(0x7fe5839b), X(0x7fe60308), + X(0x7fe680ab), X(0x7fe6fc88), X(0x7fe776a4), X(0x7fe7ef02), + X(0x7fe865a7), X(0x7fe8da97), X(0x7fe94dd6), X(0x7fe9bf68), + X(0x7fea2f51), X(0x7fea9d95), X(0x7feb0a39), X(0x7feb7540), + X(0x7febdeae), X(0x7fec4687), X(0x7fecaccf), X(0x7fed118b), + X(0x7fed74be), X(0x7fedd66c), X(0x7fee3698), X(0x7fee9548), + X(0x7feef27e), X(0x7fef4e3f), X(0x7fefa88e), X(0x7ff0016f), + X(0x7ff058e7), X(0x7ff0aef8), X(0x7ff103a6), X(0x7ff156f6), + X(0x7ff1a8eb), X(0x7ff1f988), X(0x7ff248d2), X(0x7ff296cc), + X(0x7ff2e37a), X(0x7ff32edf), X(0x7ff378ff), X(0x7ff3c1de), + X(0x7ff4097e), X(0x7ff44fe5), X(0x7ff49515), X(0x7ff4d911), + X(0x7ff51bde), X(0x7ff55d7f), X(0x7ff59df7), X(0x7ff5dd4a), + X(0x7ff61b7b), X(0x7ff6588d), X(0x7ff69485), X(0x7ff6cf65), + X(0x7ff70930), X(0x7ff741eb), X(0x7ff77998), X(0x7ff7b03b), + X(0x7ff7e5d7), X(0x7ff81a6f), X(0x7ff84e06), X(0x7ff880a1), + X(0x7ff8b241), X(0x7ff8e2ea), X(0x7ff912a0), X(0x7ff94165), + X(0x7ff96f3d), X(0x7ff99c2b), X(0x7ff9c831), X(0x7ff9f354), + X(0x7ffa1d95), X(0x7ffa46f9), X(0x7ffa6f81), X(0x7ffa9731), + X(0x7ffabe0d), X(0x7ffae416), X(0x7ffb0951), X(0x7ffb2dbf), + X(0x7ffb5164), X(0x7ffb7442), X(0x7ffb965d), X(0x7ffbb7b8), + X(0x7ffbd854), X(0x7ffbf836), X(0x7ffc175f), X(0x7ffc35d3), + X(0x7ffc5394), X(0x7ffc70a5), X(0x7ffc8d09), X(0x7ffca8c2), + X(0x7ffcc3d4), X(0x7ffcde3f), X(0x7ffcf809), X(0x7ffd1132), + X(0x7ffd29be), X(0x7ffd41ae), X(0x7ffd5907), X(0x7ffd6fc9), + X(0x7ffd85f9), X(0x7ffd9b97), X(0x7ffdb0a7), X(0x7ffdc52b), + X(0x7ffdd926), X(0x7ffdec99), X(0x7ffdff88), X(0x7ffe11f4), + X(0x7ffe23e0), X(0x7ffe354f), X(0x7ffe4642), X(0x7ffe56bc), + X(0x7ffe66bf), X(0x7ffe764e), X(0x7ffe856a), X(0x7ffe9416), + X(0x7ffea254), X(0x7ffeb026), X(0x7ffebd8e), X(0x7ffeca8f), + X(0x7ffed72a), X(0x7ffee362), X(0x7ffeef38), X(0x7ffefaaf), + X(0x7fff05c9), X(0x7fff1087), X(0x7fff1aec), X(0x7fff24f9), + X(0x7fff2eb1), X(0x7fff3816), X(0x7fff4128), X(0x7fff49eb), + X(0x7fff5260), X(0x7fff5a88), X(0x7fff6266), X(0x7fff69fc), + X(0x7fff714b), X(0x7fff7854), X(0x7fff7f1a), X(0x7fff859f), + X(0x7fff8be3), X(0x7fff91ea), X(0x7fff97b3), X(0x7fff9d41), + X(0x7fffa296), X(0x7fffa7b3), X(0x7fffac99), X(0x7fffb14b), + X(0x7fffb5c9), X(0x7fffba15), X(0x7fffbe31), X(0x7fffc21d), + X(0x7fffc5dc), X(0x7fffc96f), X(0x7fffccd8), X(0x7fffd016), + X(0x7fffd32d), X(0x7fffd61c), X(0x7fffd8e7), X(0x7fffdb8d), + X(0x7fffde0f), X(0x7fffe071), X(0x7fffe2b1), X(0x7fffe4d2), + X(0x7fffe6d5), X(0x7fffe8bb), X(0x7fffea85), X(0x7fffec34), + X(0x7fffedc9), X(0x7fffef45), X(0x7ffff0aa), X(0x7ffff1f7), + X(0x7ffff330), X(0x7ffff453), X(0x7ffff562), X(0x7ffff65f), + X(0x7ffff749), X(0x7ffff823), X(0x7ffff8ec), X(0x7ffff9a6), + X(0x7ffffa51), X(0x7ffffaee), X(0x7ffffb7e), X(0x7ffffc02), + X(0x7ffffc7a), X(0x7ffffce7), X(0x7ffffd4a), X(0x7ffffda3), + X(0x7ffffdf4), X(0x7ffffe3c), X(0x7ffffe7c), X(0x7ffffeb6), + X(0x7ffffee8), X(0x7fffff15), X(0x7fffff3c), X(0x7fffff5e), + X(0x7fffff7b), X(0x7fffff95), X(0x7fffffaa), X(0x7fffffbc), + X(0x7fffffcb), X(0x7fffffd7), X(0x7fffffe2), X(0x7fffffea), + X(0x7ffffff0), X(0x7ffffff5), X(0x7ffffff9), X(0x7ffffffb), + X(0x7ffffffd), X(0x7ffffffe), X(0x7fffffff), X(0x7fffffff), + X(0x7fffffff), X(0x7fffffff), X(0x7fffffff), X(0x7fffffff), +}; + +static const LOOKUP_T vwin8192[4096] = { + X(0x0000007c), X(0x0000045c), X(0x00000c1d), X(0x000017bd), + X(0x0000273e), X(0x00003a9f), X(0x000051e0), X(0x00006d02), + X(0x00008c03), X(0x0000aee5), X(0x0000d5a7), X(0x00010049), + X(0x00012ecb), X(0x0001612d), X(0x00019770), X(0x0001d193), + X(0x00020f96), X(0x00025178), X(0x0002973c), X(0x0002e0df), + X(0x00032e62), X(0x00037fc5), X(0x0003d509), X(0x00042e2c), + X(0x00048b30), X(0x0004ec13), X(0x000550d7), X(0x0005b97a), + X(0x000625fe), X(0x00069661), X(0x00070aa4), X(0x000782c8), + X(0x0007fecb), X(0x00087eae), X(0x00090271), X(0x00098a14), + X(0x000a1597), X(0x000aa4f9), X(0x000b383b), X(0x000bcf5d), + X(0x000c6a5f), X(0x000d0941), X(0x000dac02), X(0x000e52a3), + X(0x000efd23), X(0x000fab84), X(0x00105dc3), X(0x001113e3), + X(0x0011cde2), X(0x00128bc0), X(0x00134d7e), X(0x0014131b), + X(0x0014dc98), X(0x0015a9f4), X(0x00167b30), X(0x0017504a), + X(0x00182945), X(0x0019061e), X(0x0019e6d7), X(0x001acb6f), + X(0x001bb3e6), X(0x001ca03c), X(0x001d9071), X(0x001e8485), + X(0x001f7c79), X(0x0020784b), X(0x002177fc), X(0x00227b8c), + X(0x002382fb), X(0x00248e49), X(0x00259d76), X(0x0026b081), + X(0x0027c76b), X(0x0028e234), X(0x002a00dc), X(0x002b2361), + X(0x002c49c6), X(0x002d7409), X(0x002ea22a), X(0x002fd42a), + X(0x00310a08), X(0x003243c5), X(0x00338160), X(0x0034c2d9), + X(0x00360830), X(0x00375165), X(0x00389e78), X(0x0039ef6a), + X(0x003b4439), X(0x003c9ce6), X(0x003df971), X(0x003f59da), + X(0x0040be20), X(0x00422645), X(0x00439247), X(0x00450226), + X(0x004675e3), X(0x0047ed7e), X(0x004968f5), X(0x004ae84b), + X(0x004c6b7d), X(0x004df28d), X(0x004f7d7a), X(0x00510c44), + X(0x00529eeb), X(0x00543570), X(0x0055cfd1), X(0x00576e0f), + X(0x00591029), X(0x005ab621), X(0x005c5ff5), X(0x005e0da6), + X(0x005fbf33), X(0x0061749d), X(0x00632de4), X(0x0064eb06), + X(0x0066ac05), X(0x006870e0), X(0x006a3998), X(0x006c062b), + X(0x006dd69b), X(0x006faae6), X(0x0071830d), X(0x00735f10), + X(0x00753eef), X(0x007722a9), X(0x00790a3f), X(0x007af5b1), + X(0x007ce4fe), X(0x007ed826), X(0x0080cf29), X(0x0082ca08), + X(0x0084c8c2), X(0x0086cb57), X(0x0088d1c7), X(0x008adc11), + X(0x008cea37), X(0x008efc37), X(0x00911212), X(0x00932bc7), + X(0x00954957), X(0x00976ac2), X(0x00999006), X(0x009bb925), + X(0x009de61e), X(0x00a016f1), X(0x00a24b9e), X(0x00a48425), + X(0x00a6c086), X(0x00a900c0), X(0x00ab44d4), X(0x00ad8cc2), + X(0x00afd889), X(0x00b22829), X(0x00b47ba2), X(0x00b6d2f5), + X(0x00b92e21), X(0x00bb8d26), X(0x00bdf004), X(0x00c056ba), + X(0x00c2c149), X(0x00c52fb1), X(0x00c7a1f1), X(0x00ca180a), + X(0x00cc91fb), X(0x00cf0fc5), X(0x00d19166), X(0x00d416df), + X(0x00d6a031), X(0x00d92d5a), X(0x00dbbe5b), X(0x00de5333), + X(0x00e0ebe3), X(0x00e3886b), X(0x00e628c9), X(0x00e8ccff), + X(0x00eb750c), X(0x00ee20f0), X(0x00f0d0ab), X(0x00f3843d), + X(0x00f63ba5), X(0x00f8f6e4), X(0x00fbb5fa), X(0x00fe78e5), + X(0x01013fa7), X(0x01040a3f), X(0x0106d8ae), X(0x0109aaf2), + X(0x010c810c), X(0x010f5afb), X(0x011238c0), X(0x01151a5b), + X(0x0117ffcb), X(0x011ae910), X(0x011dd62a), X(0x0120c719), + X(0x0123bbdd), X(0x0126b476), X(0x0129b0e4), X(0x012cb126), + X(0x012fb53c), X(0x0132bd27), X(0x0135c8e6), X(0x0138d879), + X(0x013bebdf), X(0x013f031a), X(0x01421e28), X(0x01453d0a), + X(0x01485fbf), X(0x014b8648), X(0x014eb0a4), X(0x0151ded2), + X(0x015510d4), X(0x015846a8), X(0x015b8050), X(0x015ebdc9), + X(0x0161ff15), X(0x01654434), X(0x01688d24), X(0x016bd9e6), + X(0x016f2a7b), X(0x01727ee1), X(0x0175d718), X(0x01793321), + X(0x017c92fc), X(0x017ff6a7), X(0x01835e24), X(0x0186c972), + X(0x018a3890), X(0x018dab7f), X(0x0191223f), X(0x01949ccf), + X(0x01981b2f), X(0x019b9d5f), X(0x019f235f), X(0x01a2ad2f), + X(0x01a63acf), X(0x01a9cc3e), X(0x01ad617c), X(0x01b0fa8a), + X(0x01b49767), X(0x01b83813), X(0x01bbdc8d), X(0x01bf84d6), + X(0x01c330ee), X(0x01c6e0d4), X(0x01ca9488), X(0x01ce4c0b), + X(0x01d2075b), X(0x01d5c679), X(0x01d98964), X(0x01dd501d), + X(0x01e11aa3), X(0x01e4e8f6), X(0x01e8bb17), X(0x01ec9104), + X(0x01f06abd), X(0x01f44844), X(0x01f82996), X(0x01fc0eb5), + X(0x01fff7a0), X(0x0203e456), X(0x0207d4d9), X(0x020bc926), + X(0x020fc140), X(0x0213bd24), X(0x0217bcd4), X(0x021bc04e), + X(0x021fc793), X(0x0223d2a3), X(0x0227e17d), X(0x022bf421), + X(0x02300a90), X(0x023424c8), X(0x023842ca), X(0x023c6495), + X(0x02408a2a), X(0x0244b389), X(0x0248e0b0), X(0x024d11a0), + X(0x02514659), X(0x02557eda), X(0x0259bb24), X(0x025dfb35), + X(0x02623f0f), X(0x026686b1), X(0x026ad21a), X(0x026f214b), + X(0x02737443), X(0x0277cb02), X(0x027c2588), X(0x028083d5), + X(0x0284e5e9), X(0x02894bc2), X(0x028db562), X(0x029222c8), + X(0x029693f4), X(0x029b08e6), X(0x029f819d), X(0x02a3fe19), + X(0x02a87e5b), X(0x02ad0261), X(0x02b18a2c), X(0x02b615bb), + X(0x02baa50f), X(0x02bf3827), X(0x02c3cf03), X(0x02c869a3), + X(0x02cd0807), X(0x02d1aa2d), X(0x02d65017), X(0x02daf9c4), + X(0x02dfa734), X(0x02e45866), X(0x02e90d5b), X(0x02edc612), + X(0x02f2828b), X(0x02f742c6), X(0x02fc06c3), X(0x0300ce80), + X(0x030599ff), X(0x030a6940), X(0x030f3c40), X(0x03141302), + X(0x0318ed84), X(0x031dcbc6), X(0x0322adc8), X(0x0327938a), + X(0x032c7d0c), X(0x03316a4c), X(0x03365b4d), X(0x033b500c), + X(0x03404889), X(0x034544c6), X(0x034a44c0), X(0x034f4879), + X(0x03544ff0), X(0x03595b24), X(0x035e6a16), X(0x03637cc5), + X(0x03689331), X(0x036dad5a), X(0x0372cb40), X(0x0377ece2), + X(0x037d1240), X(0x03823b5a), X(0x03876830), X(0x038c98c1), + X(0x0391cd0e), X(0x03970516), X(0x039c40d8), X(0x03a18055), + X(0x03a6c38d), X(0x03ac0a7f), X(0x03b1552b), X(0x03b6a390), + X(0x03bbf5af), X(0x03c14b88), X(0x03c6a519), X(0x03cc0263), + X(0x03d16366), X(0x03d6c821), X(0x03dc3094), X(0x03e19cc0), + X(0x03e70ca2), X(0x03ec803d), X(0x03f1f78e), X(0x03f77296), + X(0x03fcf155), X(0x040273cb), X(0x0407f9f7), X(0x040d83d9), + X(0x04131170), X(0x0418a2bd), X(0x041e37c0), X(0x0423d077), + X(0x04296ce4), X(0x042f0d04), X(0x0434b0da), X(0x043a5863), + X(0x044003a0), X(0x0445b290), X(0x044b6534), X(0x04511b8b), + X(0x0456d595), X(0x045c9352), X(0x046254c1), X(0x046819e1), + X(0x046de2b4), X(0x0473af39), X(0x04797f6e), X(0x047f5355), + X(0x04852aec), X(0x048b0635), X(0x0490e52d), X(0x0496c7d6), + X(0x049cae2e), X(0x04a29836), X(0x04a885ed), X(0x04ae7753), + X(0x04b46c68), X(0x04ba652b), X(0x04c0619d), X(0x04c661bc), + X(0x04cc658a), X(0x04d26d04), X(0x04d8782c), X(0x04de8701), + X(0x04e49983), X(0x04eaafb0), X(0x04f0c98a), X(0x04f6e710), + X(0x04fd0842), X(0x05032d1e), X(0x050955a6), X(0x050f81d8), + X(0x0515b1b5), X(0x051be53d), X(0x05221c6e), X(0x05285748), + X(0x052e95cd), X(0x0534d7fa), X(0x053b1dd0), X(0x0541674e), + X(0x0547b475), X(0x054e0544), X(0x055459bb), X(0x055ab1d9), + X(0x05610d9e), X(0x05676d0a), X(0x056dd01c), X(0x057436d5), + X(0x057aa134), X(0x05810f38), X(0x058780e2), X(0x058df631), + X(0x05946f25), X(0x059aebbe), X(0x05a16bfa), X(0x05a7efdb), + X(0x05ae775f), X(0x05b50287), X(0x05bb9152), X(0x05c223c0), + X(0x05c8b9d0), X(0x05cf5382), X(0x05d5f0d6), X(0x05dc91cc), + X(0x05e33663), X(0x05e9de9c), X(0x05f08a75), X(0x05f739ee), + X(0x05fded07), X(0x0604a3c0), X(0x060b5e19), X(0x06121c11), + X(0x0618dda8), X(0x061fa2dd), X(0x06266bb1), X(0x062d3822), + X(0x06340831), X(0x063adbde), X(0x0641b328), X(0x06488e0e), + X(0x064f6c91), X(0x06564eaf), X(0x065d346a), X(0x06641dc0), + X(0x066b0ab1), X(0x0671fb3d), X(0x0678ef64), X(0x067fe724), + X(0x0686e27f), X(0x068de173), X(0x0694e400), X(0x069bea27), + X(0x06a2f3e6), X(0x06aa013d), X(0x06b1122c), X(0x06b826b3), + X(0x06bf3ed1), X(0x06c65a86), X(0x06cd79d1), X(0x06d49cb3), + X(0x06dbc32b), X(0x06e2ed38), X(0x06ea1adb), X(0x06f14c13), + X(0x06f880df), X(0x06ffb940), X(0x0706f535), X(0x070e34bd), + X(0x071577d9), X(0x071cbe88), X(0x072408c9), X(0x072b569d), + X(0x0732a802), X(0x0739fcf9), X(0x07415582), X(0x0748b19b), + X(0x07501145), X(0x0757747f), X(0x075edb49), X(0x076645a3), + X(0x076db38c), X(0x07752503), X(0x077c9a09), X(0x0784129e), + X(0x078b8ec0), X(0x07930e70), X(0x079a91ac), X(0x07a21876), + X(0x07a9a2cc), X(0x07b130ad), X(0x07b8c21b), X(0x07c05714), + X(0x07c7ef98), X(0x07cf8ba6), X(0x07d72b3f), X(0x07dece62), + X(0x07e6750e), X(0x07ee1f43), X(0x07f5cd01), X(0x07fd7e48), + X(0x08053316), X(0x080ceb6d), X(0x0814a74a), X(0x081c66af), + X(0x0824299a), X(0x082bf00c), X(0x0833ba03), X(0x083b8780), + X(0x08435882), X(0x084b2d09), X(0x08530514), X(0x085ae0a3), + X(0x0862bfb6), X(0x086aa24c), X(0x08728865), X(0x087a7201), + X(0x08825f1e), X(0x088a4fbe), X(0x089243de), X(0x089a3b80), + X(0x08a236a2), X(0x08aa3545), X(0x08b23767), X(0x08ba3d09), + X(0x08c2462a), X(0x08ca52c9), X(0x08d262e7), X(0x08da7682), + X(0x08e28d9c), X(0x08eaa832), X(0x08f2c645), X(0x08fae7d4), + X(0x09030cdf), X(0x090b3566), X(0x09136168), X(0x091b90e5), + X(0x0923c3dc), X(0x092bfa4d), X(0x09343437), X(0x093c719b), + X(0x0944b277), X(0x094cf6cc), X(0x09553e99), X(0x095d89dd), + X(0x0965d899), X(0x096e2acb), X(0x09768073), X(0x097ed991), + X(0x09873625), X(0x098f962e), X(0x0997f9ac), X(0x09a0609e), + X(0x09a8cb04), X(0x09b138dd), X(0x09b9aa29), X(0x09c21ee8), + X(0x09ca9719), X(0x09d312bc), X(0x09db91d0), X(0x09e41456), + X(0x09ec9a4b), X(0x09f523b1), X(0x09fdb087), X(0x0a0640cc), + X(0x0a0ed47f), X(0x0a176ba2), X(0x0a200632), X(0x0a28a42f), + X(0x0a31459a), X(0x0a39ea72), X(0x0a4292b5), X(0x0a4b3e65), + X(0x0a53ed80), X(0x0a5ca006), X(0x0a6555f7), X(0x0a6e0f51), + X(0x0a76cc16), X(0x0a7f8c44), X(0x0a884fda), X(0x0a9116d9), + X(0x0a99e140), X(0x0aa2af0e), X(0x0aab8043), X(0x0ab454df), + X(0x0abd2ce1), X(0x0ac60849), X(0x0acee716), X(0x0ad7c948), + X(0x0ae0aedf), X(0x0ae997d9), X(0x0af28437), X(0x0afb73f7), + X(0x0b04671b), X(0x0b0d5da0), X(0x0b165788), X(0x0b1f54d0), + X(0x0b285579), X(0x0b315983), X(0x0b3a60ec), X(0x0b436bb5), + X(0x0b4c79dd), X(0x0b558b63), X(0x0b5ea048), X(0x0b67b88a), + X(0x0b70d429), X(0x0b79f324), X(0x0b83157c), X(0x0b8c3b30), + X(0x0b95643f), X(0x0b9e90a8), X(0x0ba7c06c), X(0x0bb0f38a), + X(0x0bba2a01), X(0x0bc363d1), X(0x0bcca0f9), X(0x0bd5e17a), + X(0x0bdf2552), X(0x0be86c81), X(0x0bf1b706), X(0x0bfb04e2), + X(0x0c045613), X(0x0c0daa99), X(0x0c170274), X(0x0c205da3), + X(0x0c29bc25), X(0x0c331dfb), X(0x0c3c8323), X(0x0c45eb9e), + X(0x0c4f576a), X(0x0c58c688), X(0x0c6238f6), X(0x0c6baeb5), + X(0x0c7527c3), X(0x0c7ea421), X(0x0c8823cd), X(0x0c91a6c8), + X(0x0c9b2d10), X(0x0ca4b6a6), X(0x0cae4389), X(0x0cb7d3b8), + X(0x0cc16732), X(0x0ccafdf8), X(0x0cd49809), X(0x0cde3564), + X(0x0ce7d609), X(0x0cf179f7), X(0x0cfb212e), X(0x0d04cbad), + X(0x0d0e7974), X(0x0d182a83), X(0x0d21ded8), X(0x0d2b9673), + X(0x0d355154), X(0x0d3f0f7b), X(0x0d48d0e6), X(0x0d529595), + X(0x0d5c5d88), X(0x0d6628be), X(0x0d6ff737), X(0x0d79c8f2), + X(0x0d839dee), X(0x0d8d762c), X(0x0d9751aa), X(0x0da13068), + X(0x0dab1266), X(0x0db4f7a3), X(0x0dbee01e), X(0x0dc8cbd8), + X(0x0dd2bace), X(0x0ddcad02), X(0x0de6a272), X(0x0df09b1e), + X(0x0dfa9705), X(0x0e049627), X(0x0e0e9883), X(0x0e189e19), + X(0x0e22a6e8), X(0x0e2cb2f0), X(0x0e36c230), X(0x0e40d4a8), + X(0x0e4aea56), X(0x0e55033b), X(0x0e5f1f56), X(0x0e693ea7), + X(0x0e73612c), X(0x0e7d86e5), X(0x0e87afd3), X(0x0e91dbf3), + X(0x0e9c0b47), X(0x0ea63dcc), X(0x0eb07383), X(0x0ebaac6b), + X(0x0ec4e883), X(0x0ecf27cc), X(0x0ed96a44), X(0x0ee3afea), + X(0x0eedf8bf), X(0x0ef844c2), X(0x0f0293f2), X(0x0f0ce64e), + X(0x0f173bd6), X(0x0f21948a), X(0x0f2bf069), X(0x0f364f72), + X(0x0f40b1a5), X(0x0f4b1701), X(0x0f557f86), X(0x0f5feb32), + X(0x0f6a5a07), X(0x0f74cc02), X(0x0f7f4124), X(0x0f89b96b), + X(0x0f9434d8), X(0x0f9eb369), X(0x0fa9351e), X(0x0fb3b9f7), + X(0x0fbe41f3), X(0x0fc8cd11), X(0x0fd35b51), X(0x0fddecb2), + X(0x0fe88134), X(0x0ff318d6), X(0x0ffdb397), X(0x10085177), + X(0x1012f275), X(0x101d9691), X(0x10283dca), X(0x1032e81f), + X(0x103d9591), X(0x1048461e), X(0x1052f9c5), X(0x105db087), + X(0x10686a62), X(0x10732756), X(0x107de763), X(0x1088aa87), + X(0x109370c2), X(0x109e3a14), X(0x10a9067c), X(0x10b3d5f9), + X(0x10bea88b), X(0x10c97e31), X(0x10d456eb), X(0x10df32b8), + X(0x10ea1197), X(0x10f4f387), X(0x10ffd889), X(0x110ac09b), + X(0x1115abbe), X(0x112099ef), X(0x112b8b2f), X(0x11367f7d), + X(0x114176d9), X(0x114c7141), X(0x11576eb6), X(0x11626f36), + X(0x116d72c1), X(0x11787957), X(0x118382f6), X(0x118e8f9e), + X(0x11999f4f), X(0x11a4b208), X(0x11afc7c7), X(0x11bae08e), + X(0x11c5fc5a), X(0x11d11b2c), X(0x11dc3d02), X(0x11e761dd), + X(0x11f289ba), X(0x11fdb49b), X(0x1208e27e), X(0x12141362), + X(0x121f4748), X(0x122a7e2d), X(0x1235b812), X(0x1240f4f6), + X(0x124c34d9), X(0x125777b9), X(0x1262bd96), X(0x126e0670), + X(0x12795245), X(0x1284a115), X(0x128ff2e0), X(0x129b47a5), + X(0x12a69f63), X(0x12b1fa19), X(0x12bd57c7), X(0x12c8b86c), + X(0x12d41c08), X(0x12df829a), X(0x12eaec21), X(0x12f6589d), + X(0x1301c80c), X(0x130d3a6f), X(0x1318afc4), X(0x1324280b), + X(0x132fa344), X(0x133b216d), X(0x1346a286), X(0x1352268e), + X(0x135dad85), X(0x1369376a), X(0x1374c43c), X(0x138053fb), + X(0x138be6a5), X(0x13977c3b), X(0x13a314bc), X(0x13aeb026), + X(0x13ba4e79), X(0x13c5efb5), X(0x13d193d9), X(0x13dd3ae4), + X(0x13e8e4d6), X(0x13f491ad), X(0x1400416a), X(0x140bf40b), + X(0x1417a98f), X(0x142361f7), X(0x142f1d41), X(0x143adb6d), + X(0x14469c7a), X(0x14526067), X(0x145e2734), X(0x1469f0df), + X(0x1475bd69), X(0x14818cd0), X(0x148d5f15), X(0x14993435), + X(0x14a50c31), X(0x14b0e708), X(0x14bcc4b8), X(0x14c8a542), + X(0x14d488a5), X(0x14e06edf), X(0x14ec57f1), X(0x14f843d9), + X(0x15043297), X(0x1510242b), X(0x151c1892), X(0x15280fcd), + X(0x153409dc), X(0x154006bc), X(0x154c066e), X(0x155808f1), + X(0x15640e44), X(0x15701666), X(0x157c2157), X(0x15882f16), + X(0x15943fa2), X(0x15a052fb), X(0x15ac691f), X(0x15b8820f), + X(0x15c49dc8), X(0x15d0bc4c), X(0x15dcdd98), X(0x15e901ad), + X(0x15f52888), X(0x1601522b), X(0x160d7e93), X(0x1619adc1), + X(0x1625dfb3), X(0x16321469), X(0x163e4be2), X(0x164a861d), + X(0x1656c31a), X(0x166302d8), X(0x166f4555), X(0x167b8a92), + X(0x1687d28e), X(0x16941d47), X(0x16a06abe), X(0x16acbaf0), + X(0x16b90ddf), X(0x16c56388), X(0x16d1bbeb), X(0x16de1708), + X(0x16ea74dd), X(0x16f6d56a), X(0x170338ae), X(0x170f9ea8), + X(0x171c0758), X(0x172872bd), X(0x1734e0d6), X(0x174151a2), + X(0x174dc520), X(0x175a3b51), X(0x1766b432), X(0x17732fc4), + X(0x177fae05), X(0x178c2ef4), X(0x1798b292), X(0x17a538dd), + X(0x17b1c1d4), X(0x17be4d77), X(0x17cadbc5), X(0x17d76cbc), + X(0x17e4005e), X(0x17f096a7), X(0x17fd2f98), X(0x1809cb31), + X(0x1816696f), X(0x18230a53), X(0x182faddc), X(0x183c5408), + X(0x1848fcd8), X(0x1855a849), X(0x1862565d), X(0x186f0711), + X(0x187bba64), X(0x18887057), X(0x189528e9), X(0x18a1e418), + X(0x18aea1e3), X(0x18bb624b), X(0x18c8254e), X(0x18d4eaeb), + X(0x18e1b321), X(0x18ee7df1), X(0x18fb4b58), X(0x19081b57), + X(0x1914edec), X(0x1921c317), X(0x192e9ad6), X(0x193b7529), + X(0x19485210), X(0x19553189), X(0x19621393), X(0x196ef82e), + X(0x197bdf59), X(0x1988c913), X(0x1995b55c), X(0x19a2a432), + X(0x19af9595), X(0x19bc8983), X(0x19c97ffd), X(0x19d67900), + X(0x19e3748e), X(0x19f072a3), X(0x19fd7341), X(0x1a0a7665), + X(0x1a177c10), X(0x1a248440), X(0x1a318ef4), X(0x1a3e9c2c), + X(0x1a4babe7), X(0x1a58be24), X(0x1a65d2e2), X(0x1a72ea20), + X(0x1a8003de), X(0x1a8d201a), X(0x1a9a3ed5), X(0x1aa7600c), + X(0x1ab483bf), X(0x1ac1a9ee), X(0x1aced297), X(0x1adbfdba), + X(0x1ae92b56), X(0x1af65b69), X(0x1b038df4), X(0x1b10c2f5), + X(0x1b1dfa6b), X(0x1b2b3456), X(0x1b3870b5), X(0x1b45af87), + X(0x1b52f0ca), X(0x1b60347f), X(0x1b6d7aa4), X(0x1b7ac339), + X(0x1b880e3c), X(0x1b955bad), X(0x1ba2ab8b), X(0x1baffdd5), + X(0x1bbd528a), X(0x1bcaa9a9), X(0x1bd80332), X(0x1be55f24), + X(0x1bf2bd7d), X(0x1c001e3d), X(0x1c0d8164), X(0x1c1ae6ef), + X(0x1c284edf), X(0x1c35b932), X(0x1c4325e7), X(0x1c5094fe), + X(0x1c5e0677), X(0x1c6b7a4f), X(0x1c78f086), X(0x1c86691b), + X(0x1c93e40d), X(0x1ca1615c), X(0x1caee107), X(0x1cbc630c), + X(0x1cc9e76b), X(0x1cd76e23), X(0x1ce4f733), X(0x1cf2829a), + X(0x1d001057), X(0x1d0da06a), X(0x1d1b32d1), X(0x1d28c78c), + X(0x1d365e9a), X(0x1d43f7f9), X(0x1d5193a9), X(0x1d5f31aa), + X(0x1d6cd1f9), X(0x1d7a7497), X(0x1d881982), X(0x1d95c0ba), + X(0x1da36a3d), X(0x1db1160a), X(0x1dbec422), X(0x1dcc7482), + X(0x1dda272b), X(0x1de7dc1a), X(0x1df59350), X(0x1e034ccb), + X(0x1e11088a), X(0x1e1ec68c), X(0x1e2c86d1), X(0x1e3a4958), + X(0x1e480e20), X(0x1e55d527), X(0x1e639e6d), X(0x1e7169f1), + X(0x1e7f37b2), X(0x1e8d07b0), X(0x1e9ad9e8), X(0x1ea8ae5b), + X(0x1eb68507), X(0x1ec45dec), X(0x1ed23908), X(0x1ee0165b), + X(0x1eedf5e4), X(0x1efbd7a1), X(0x1f09bb92), X(0x1f17a1b6), + X(0x1f258a0d), X(0x1f337494), X(0x1f41614b), X(0x1f4f5032), + X(0x1f5d4147), X(0x1f6b3489), X(0x1f7929f7), X(0x1f872192), + X(0x1f951b56), X(0x1fa31744), X(0x1fb1155b), X(0x1fbf159a), + X(0x1fcd17ff), X(0x1fdb1c8b), X(0x1fe9233b), X(0x1ff72c0f), + X(0x20053706), X(0x20134420), X(0x2021535a), X(0x202f64b4), + X(0x203d782e), X(0x204b8dc6), X(0x2059a57c), X(0x2067bf4e), + X(0x2075db3b), X(0x2083f943), X(0x20921964), X(0x20a03b9e), + X(0x20ae5fef), X(0x20bc8657), X(0x20caaed5), X(0x20d8d967), + X(0x20e7060e), X(0x20f534c7), X(0x21036592), X(0x2111986e), + X(0x211fcd59), X(0x212e0454), X(0x213c3d5d), X(0x214a7873), + X(0x2158b594), X(0x2166f4c1), X(0x217535f8), X(0x21837938), + X(0x2191be81), X(0x21a005d0), X(0x21ae4f26), X(0x21bc9a81), + X(0x21cae7e0), X(0x21d93743), X(0x21e788a8), X(0x21f5dc0e), + X(0x22043174), X(0x221288da), X(0x2220e23e), X(0x222f3da0), + X(0x223d9afe), X(0x224bfa58), X(0x225a5bac), X(0x2268bef9), + X(0x2277243f), X(0x22858b7d), X(0x2293f4b0), X(0x22a25fda), + X(0x22b0ccf8), X(0x22bf3c09), X(0x22cdad0d), X(0x22dc2002), + X(0x22ea94e8), X(0x22f90bbe), X(0x23078482), X(0x2315ff33), + X(0x23247bd1), X(0x2332fa5b), X(0x23417acf), X(0x234ffd2c), + X(0x235e8173), X(0x236d07a0), X(0x237b8fb4), X(0x238a19ae), + X(0x2398a58c), X(0x23a7334d), X(0x23b5c2f1), X(0x23c45477), + X(0x23d2e7dd), X(0x23e17d22), X(0x23f01446), X(0x23fead47), + X(0x240d4825), X(0x241be4dd), X(0x242a8371), X(0x243923dd), + X(0x2447c622), X(0x24566a3e), X(0x24651031), X(0x2473b7f8), + X(0x24826194), X(0x24910d03), X(0x249fba44), X(0x24ae6957), + X(0x24bd1a39), X(0x24cbccea), X(0x24da816a), X(0x24e937b7), + X(0x24f7efcf), X(0x2506a9b3), X(0x25156560), X(0x252422d6), + X(0x2532e215), X(0x2541a31a), X(0x255065e4), X(0x255f2a74), + X(0x256df0c7), X(0x257cb8dd), X(0x258b82b4), X(0x259a4e4c), + X(0x25a91ba4), X(0x25b7eaba), X(0x25c6bb8e), X(0x25d58e1e), + X(0x25e46269), X(0x25f3386e), X(0x2602102d), X(0x2610e9a4), + X(0x261fc4d3), X(0x262ea1b7), X(0x263d8050), X(0x264c609e), + X(0x265b429e), X(0x266a2650), X(0x26790bb3), X(0x2687f2c6), + X(0x2696db88), X(0x26a5c5f7), X(0x26b4b213), X(0x26c39fda), + X(0x26d28f4c), X(0x26e18067), X(0x26f0732b), X(0x26ff6796), + X(0x270e5da7), X(0x271d555d), X(0x272c4eb7), X(0x273b49b5), + X(0x274a4654), X(0x27594495), X(0x27684475), X(0x277745f4), + X(0x27864910), X(0x27954dc9), X(0x27a4541e), X(0x27b35c0d), + X(0x27c26596), X(0x27d170b7), X(0x27e07d6f), X(0x27ef8bbd), + X(0x27fe9ba0), X(0x280dad18), X(0x281cc022), X(0x282bd4be), + X(0x283aeaeb), X(0x284a02a7), X(0x28591bf2), X(0x286836cb), + X(0x28775330), X(0x28867120), X(0x2895909b), X(0x28a4b19e), + X(0x28b3d42a), X(0x28c2f83d), X(0x28d21dd5), X(0x28e144f3), + X(0x28f06d94), X(0x28ff97b8), X(0x290ec35d), X(0x291df082), + X(0x292d1f27), X(0x293c4f4a), X(0x294b80eb), X(0x295ab407), + X(0x2969e89e), X(0x29791eaf), X(0x29885639), X(0x29978f3b), + X(0x29a6c9b3), X(0x29b605a0), X(0x29c54302), X(0x29d481d7), + X(0x29e3c21e), X(0x29f303d6), X(0x2a0246fd), X(0x2a118b94), + X(0x2a20d198), X(0x2a301909), X(0x2a3f61e6), X(0x2a4eac2c), + X(0x2a5df7dc), X(0x2a6d44f4), X(0x2a7c9374), X(0x2a8be359), + X(0x2a9b34a2), X(0x2aaa8750), X(0x2ab9db60), X(0x2ac930d1), + X(0x2ad887a3), X(0x2ae7dfd3), X(0x2af73962), X(0x2b06944e), + X(0x2b15f096), X(0x2b254e38), X(0x2b34ad34), X(0x2b440d89), + X(0x2b536f34), X(0x2b62d236), X(0x2b72368d), X(0x2b819c38), + X(0x2b910336), X(0x2ba06b86), X(0x2bafd526), X(0x2bbf4015), + X(0x2bceac53), X(0x2bde19de), X(0x2bed88b5), X(0x2bfcf8d7), + X(0x2c0c6a43), X(0x2c1bdcf7), X(0x2c2b50f3), X(0x2c3ac635), + X(0x2c4a3cbd), X(0x2c59b488), X(0x2c692d97), X(0x2c78a7e7), + X(0x2c882378), X(0x2c97a049), X(0x2ca71e58), X(0x2cb69da4), + X(0x2cc61e2c), X(0x2cd59ff0), X(0x2ce522ed), X(0x2cf4a723), + X(0x2d042c90), X(0x2d13b334), X(0x2d233b0d), X(0x2d32c41a), + X(0x2d424e5a), X(0x2d51d9cc), X(0x2d61666e), X(0x2d70f440), + X(0x2d808340), X(0x2d90136e), X(0x2d9fa4c7), X(0x2daf374c), + X(0x2dbecafa), X(0x2dce5fd1), X(0x2dddf5cf), X(0x2ded8cf4), + X(0x2dfd253d), X(0x2e0cbeab), X(0x2e1c593b), X(0x2e2bf4ed), + X(0x2e3b91c0), X(0x2e4b2fb1), X(0x2e5acec1), X(0x2e6a6eee), + X(0x2e7a1037), X(0x2e89b29b), X(0x2e995618), X(0x2ea8faad), + X(0x2eb8a05a), X(0x2ec8471c), X(0x2ed7eef4), X(0x2ee797df), + X(0x2ef741dc), X(0x2f06eceb), X(0x2f16990a), X(0x2f264639), + X(0x2f35f475), X(0x2f45a3bd), X(0x2f555412), X(0x2f650570), + X(0x2f74b7d8), X(0x2f846b48), X(0x2f941fbe), X(0x2fa3d53a), + X(0x2fb38bbb), X(0x2fc3433f), X(0x2fd2fbc5), X(0x2fe2b54c), + X(0x2ff26fd3), X(0x30022b58), X(0x3011e7db), X(0x3021a55a), + X(0x303163d4), X(0x30412348), X(0x3050e3b5), X(0x3060a519), + X(0x30706773), X(0x30802ac3), X(0x308fef06), X(0x309fb43d), + X(0x30af7a65), X(0x30bf417d), X(0x30cf0985), X(0x30ded27a), + X(0x30ee9c5d), X(0x30fe672b), X(0x310e32e3), X(0x311dff85), + X(0x312dcd0f), X(0x313d9b80), X(0x314d6ad7), X(0x315d3b12), + X(0x316d0c30), X(0x317cde31), X(0x318cb113), X(0x319c84d4), + X(0x31ac5974), X(0x31bc2ef1), X(0x31cc054b), X(0x31dbdc7f), + X(0x31ebb48e), X(0x31fb8d74), X(0x320b6733), X(0x321b41c7), + X(0x322b1d31), X(0x323af96e), X(0x324ad67e), X(0x325ab45f), + X(0x326a9311), X(0x327a7291), X(0x328a52e0), X(0x329a33fb), + X(0x32aa15e1), X(0x32b9f892), X(0x32c9dc0c), X(0x32d9c04d), + X(0x32e9a555), X(0x32f98b22), X(0x330971b4), X(0x33195909), + X(0x3329411f), X(0x333929f6), X(0x3349138c), X(0x3358fde1), + X(0x3368e8f2), X(0x3378d4c0), X(0x3388c147), X(0x3398ae89), + X(0x33a89c82), X(0x33b88b32), X(0x33c87a98), X(0x33d86ab2), + X(0x33e85b80), X(0x33f84d00), X(0x34083f30), X(0x34183210), + X(0x3428259f), X(0x343819db), X(0x34480ec3), X(0x34580455), + X(0x3467fa92), X(0x3477f176), X(0x3487e902), X(0x3497e134), + X(0x34a7da0a), X(0x34b7d384), X(0x34c7cda0), X(0x34d7c85e), + X(0x34e7c3bb), X(0x34f7bfb7), X(0x3507bc50), X(0x3517b985), + X(0x3527b756), X(0x3537b5c0), X(0x3547b4c3), X(0x3557b45d), + X(0x3567b48d), X(0x3577b552), X(0x3587b6aa), X(0x3597b895), + X(0x35a7bb12), X(0x35b7be1e), X(0x35c7c1b9), X(0x35d7c5e1), + X(0x35e7ca96), X(0x35f7cfd6), X(0x3607d5a0), X(0x3617dbf3), + X(0x3627e2cd), X(0x3637ea2d), X(0x3647f212), X(0x3657fa7b), + X(0x36680366), X(0x36780cd2), X(0x368816bf), X(0x3698212b), + X(0x36a82c14), X(0x36b83779), X(0x36c8435a), X(0x36d84fb4), + X(0x36e85c88), X(0x36f869d2), X(0x37087793), X(0x371885c9), + X(0x37289473), X(0x3738a38f), X(0x3748b31d), X(0x3758c31a), + X(0x3768d387), X(0x3778e461), X(0x3788f5a7), X(0x37990759), + X(0x37a91975), X(0x37b92bf9), X(0x37c93ee4), X(0x37d95236), + X(0x37e965ed), X(0x37f97a08), X(0x38098e85), X(0x3819a363), + X(0x3829b8a2), X(0x3839ce3f), X(0x3849e43a), X(0x3859fa91), + X(0x386a1143), X(0x387a284f), X(0x388a3fb4), X(0x389a5770), + X(0x38aa6f83), X(0x38ba87ea), X(0x38caa0a5), X(0x38dab9b2), + X(0x38ead311), X(0x38faecbf), X(0x390b06bc), X(0x391b2107), + X(0x392b3b9e), X(0x393b5680), X(0x394b71ac), X(0x395b8d20), + X(0x396ba8dc), X(0x397bc4dd), X(0x398be124), X(0x399bfdae), + X(0x39ac1a7a), X(0x39bc3788), X(0x39cc54d5), X(0x39dc7261), + X(0x39ec902a), X(0x39fcae2f), X(0x3a0ccc70), X(0x3a1ceaea), + X(0x3a2d099c), X(0x3a3d2885), X(0x3a4d47a5), X(0x3a5d66f9), + X(0x3a6d8680), X(0x3a7da63a), X(0x3a8dc625), X(0x3a9de63f), + X(0x3aae0688), X(0x3abe26fe), X(0x3ace47a0), X(0x3ade686d), + X(0x3aee8963), X(0x3afeaa82), X(0x3b0ecbc7), X(0x3b1eed32), + X(0x3b2f0ec2), X(0x3b3f3075), X(0x3b4f524a), X(0x3b5f7440), + X(0x3b6f9656), X(0x3b7fb889), X(0x3b8fdada), X(0x3b9ffd46), + X(0x3bb01fce), X(0x3bc0426e), X(0x3bd06526), X(0x3be087f6), + X(0x3bf0aada), X(0x3c00cdd4), X(0x3c10f0e0), X(0x3c2113fe), + X(0x3c31372d), X(0x3c415a6b), X(0x3c517db7), X(0x3c61a110), + X(0x3c71c475), X(0x3c81e7e4), X(0x3c920b5c), X(0x3ca22edc), + X(0x3cb25262), X(0x3cc275ee), X(0x3cd2997e), X(0x3ce2bd11), + X(0x3cf2e0a6), X(0x3d03043b), X(0x3d1327cf), X(0x3d234b61), + X(0x3d336ef0), X(0x3d43927a), X(0x3d53b5ff), X(0x3d63d97c), + X(0x3d73fcf1), X(0x3d84205c), X(0x3d9443bd), X(0x3da46711), + X(0x3db48a58), X(0x3dc4ad91), X(0x3dd4d0ba), X(0x3de4f3d1), + X(0x3df516d7), X(0x3e0539c9), X(0x3e155ca6), X(0x3e257f6d), + X(0x3e35a21d), X(0x3e45c4b4), X(0x3e55e731), X(0x3e660994), + X(0x3e762bda), X(0x3e864e03), X(0x3e96700d), X(0x3ea691f7), + X(0x3eb6b3bf), X(0x3ec6d565), X(0x3ed6f6e8), X(0x3ee71845), + X(0x3ef7397c), X(0x3f075a8c), X(0x3f177b73), X(0x3f279c30), + X(0x3f37bcc2), X(0x3f47dd27), X(0x3f57fd5f), X(0x3f681d68), + X(0x3f783d40), X(0x3f885ce7), X(0x3f987c5c), X(0x3fa89b9c), + X(0x3fb8baa7), X(0x3fc8d97c), X(0x3fd8f819), X(0x3fe9167e), + X(0x3ff934a8), X(0x40095296), X(0x40197049), X(0x40298dbd), + X(0x4039aaf2), X(0x4049c7e7), X(0x4059e49a), X(0x406a010a), + X(0x407a1d36), X(0x408a391d), X(0x409a54bd), X(0x40aa7015), + X(0x40ba8b25), X(0x40caa5ea), X(0x40dac063), X(0x40eada90), + X(0x40faf46e), X(0x410b0dfe), X(0x411b273d), X(0x412b402a), + X(0x413b58c4), X(0x414b710a), X(0x415b88fa), X(0x416ba093), + X(0x417bb7d5), X(0x418bcebe), X(0x419be54c), X(0x41abfb7e), + X(0x41bc1153), X(0x41cc26ca), X(0x41dc3be2), X(0x41ec5099), + X(0x41fc64ef), X(0x420c78e1), X(0x421c8c6f), X(0x422c9f97), + X(0x423cb258), X(0x424cc4b2), X(0x425cd6a2), X(0x426ce827), + X(0x427cf941), X(0x428d09ee), X(0x429d1a2c), X(0x42ad29fb), + X(0x42bd3959), X(0x42cd4846), X(0x42dd56bf), X(0x42ed64c3), + X(0x42fd7252), X(0x430d7f6a), X(0x431d8c0a), X(0x432d9831), + X(0x433da3dd), X(0x434daf0d), X(0x435db9c0), X(0x436dc3f5), + X(0x437dcdab), X(0x438dd6df), X(0x439ddf92), X(0x43ade7c1), + X(0x43bdef6c), X(0x43cdf691), X(0x43ddfd2f), X(0x43ee0345), + X(0x43fe08d2), X(0x440e0dd4), X(0x441e124b), X(0x442e1634), + X(0x443e198f), X(0x444e1c5a), X(0x445e1e95), X(0x446e203e), + X(0x447e2153), X(0x448e21d5), X(0x449e21c0), X(0x44ae2115), + X(0x44be1fd1), X(0x44ce1df4), X(0x44de1b7d), X(0x44ee186a), + X(0x44fe14ba), X(0x450e106b), X(0x451e0b7e), X(0x452e05ef), + X(0x453dffbf), X(0x454df8eb), X(0x455df173), X(0x456de956), + X(0x457de092), X(0x458dd726), X(0x459dcd10), X(0x45adc251), + X(0x45bdb6e5), X(0x45cdaacd), X(0x45dd9e06), X(0x45ed9091), + X(0x45fd826a), X(0x460d7392), X(0x461d6407), X(0x462d53c8), + X(0x463d42d4), X(0x464d3129), X(0x465d1ec6), X(0x466d0baa), + X(0x467cf7d3), X(0x468ce342), X(0x469ccdf3), X(0x46acb7e7), + X(0x46bca11c), X(0x46cc8990), X(0x46dc7143), X(0x46ec5833), + X(0x46fc3e5f), X(0x470c23c6), X(0x471c0867), X(0x472bec40), + X(0x473bcf50), X(0x474bb196), X(0x475b9311), X(0x476b73c0), + X(0x477b53a1), X(0x478b32b4), X(0x479b10f6), X(0x47aaee67), + X(0x47bacb06), X(0x47caa6d1), X(0x47da81c7), X(0x47ea5be7), + X(0x47fa3530), X(0x480a0da1), X(0x4819e537), X(0x4829bbf3), + X(0x483991d3), X(0x484966d6), X(0x48593afb), X(0x48690e3f), + X(0x4878e0a3), X(0x4888b225), X(0x489882c4), X(0x48a8527e), + X(0x48b82153), X(0x48c7ef41), X(0x48d7bc47), X(0x48e78863), + X(0x48f75396), X(0x49071ddc), X(0x4916e736), X(0x4926afa2), + X(0x4936771f), X(0x49463dac), X(0x49560347), X(0x4965c7ef), + X(0x49758ba4), X(0x49854e63), X(0x4995102c), X(0x49a4d0fe), + X(0x49b490d7), X(0x49c44fb6), X(0x49d40d9a), X(0x49e3ca82), + X(0x49f3866c), X(0x4a034159), X(0x4a12fb45), X(0x4a22b430), + X(0x4a326c19), X(0x4a4222ff), X(0x4a51d8e1), X(0x4a618dbd), + X(0x4a714192), X(0x4a80f45f), X(0x4a90a623), X(0x4aa056dd), + X(0x4ab0068b), X(0x4abfb52c), X(0x4acf62c0), X(0x4adf0f44), + X(0x4aeebab9), X(0x4afe651c), X(0x4b0e0e6c), X(0x4b1db6a9), + X(0x4b2d5dd1), X(0x4b3d03e2), X(0x4b4ca8dd), X(0x4b5c4cbf), + X(0x4b6bef88), X(0x4b7b9136), X(0x4b8b31c8), X(0x4b9ad13d), + X(0x4baa6f93), X(0x4bba0ccb), X(0x4bc9a8e2), X(0x4bd943d7), + X(0x4be8dda9), X(0x4bf87658), X(0x4c080de1), X(0x4c17a444), + X(0x4c27397f), X(0x4c36cd92), X(0x4c46607b), X(0x4c55f239), + X(0x4c6582cb), X(0x4c75122f), X(0x4c84a065), X(0x4c942d6c), + X(0x4ca3b942), X(0x4cb343e6), X(0x4cc2cd57), X(0x4cd25594), + X(0x4ce1dc9c), X(0x4cf1626d), X(0x4d00e707), X(0x4d106a68), + X(0x4d1fec8f), X(0x4d2f6d7a), X(0x4d3eed2a), X(0x4d4e6b9d), + X(0x4d5de8d1), X(0x4d6d64c5), X(0x4d7cdf79), X(0x4d8c58eb), + X(0x4d9bd11a), X(0x4dab4804), X(0x4dbabdaa), X(0x4dca3209), + X(0x4dd9a520), X(0x4de916ef), X(0x4df88774), X(0x4e07f6ae), + X(0x4e17649c), X(0x4e26d13c), X(0x4e363c8f), X(0x4e45a692), + X(0x4e550f44), X(0x4e6476a4), X(0x4e73dcb2), X(0x4e83416c), + X(0x4e92a4d1), X(0x4ea206df), X(0x4eb16796), X(0x4ec0c6f5), + X(0x4ed024fa), X(0x4edf81a5), X(0x4eeedcf3), X(0x4efe36e5), + X(0x4f0d8f79), X(0x4f1ce6ad), X(0x4f2c3c82), X(0x4f3b90f4), + X(0x4f4ae405), X(0x4f5a35b1), X(0x4f6985fa), X(0x4f78d4dc), + X(0x4f882257), X(0x4f976e6a), X(0x4fa6b914), X(0x4fb60254), + X(0x4fc54a28), X(0x4fd49090), X(0x4fe3d58b), X(0x4ff31917), + X(0x50025b33), X(0x50119bde), X(0x5020db17), X(0x503018dd), + X(0x503f552f), X(0x504e900b), X(0x505dc971), X(0x506d0160), + X(0x507c37d7), X(0x508b6cd3), X(0x509aa055), X(0x50a9d25b), + X(0x50b902e4), X(0x50c831ef), X(0x50d75f7b), X(0x50e68b87), + X(0x50f5b612), X(0x5104df1a), X(0x5114069f), X(0x51232ca0), + X(0x5132511a), X(0x5141740f), X(0x5150957b), X(0x515fb55f), + X(0x516ed3b8), X(0x517df087), X(0x518d0bca), X(0x519c257f), + X(0x51ab3da7), X(0x51ba543f), X(0x51c96947), X(0x51d87cbd), + X(0x51e78ea1), X(0x51f69ef1), X(0x5205adad), X(0x5214bad3), + X(0x5223c662), X(0x5232d05a), X(0x5241d8b9), X(0x5250df7d), + X(0x525fe4a7), X(0x526ee835), X(0x527dea26), X(0x528cea78), + X(0x529be92c), X(0x52aae63f), X(0x52b9e1b0), X(0x52c8db80), + X(0x52d7d3ac), X(0x52e6ca33), X(0x52f5bf15), X(0x5304b251), + X(0x5313a3e5), X(0x532293d0), X(0x53318212), X(0x53406ea8), + X(0x534f5993), X(0x535e42d2), X(0x536d2a62), X(0x537c1043), + X(0x538af475), X(0x5399d6f6), X(0x53a8b7c4), X(0x53b796e0), + X(0x53c67447), X(0x53d54ffa), X(0x53e429f6), X(0x53f3023b), + X(0x5401d8c8), X(0x5410ad9c), X(0x541f80b5), X(0x542e5213), + X(0x543d21b5), X(0x544bef9a), X(0x545abbc0), X(0x54698627), + X(0x54784ece), X(0x548715b3), X(0x5495dad6), X(0x54a49e35), + X(0x54b35fd0), X(0x54c21fa6), X(0x54d0ddb5), X(0x54df99fd), + X(0x54ee547c), X(0x54fd0d32), X(0x550bc41d), X(0x551a793d), + X(0x55292c91), X(0x5537de16), X(0x55468dce), X(0x55553bb6), + X(0x5563e7cd), X(0x55729213), X(0x55813a87), X(0x558fe127), + X(0x559e85f2), X(0x55ad28e9), X(0x55bbca08), X(0x55ca6950), + X(0x55d906c0), X(0x55e7a257), X(0x55f63c13), X(0x5604d3f4), + X(0x561369f8), X(0x5621fe1f), X(0x56309067), X(0x563f20d1), + X(0x564daf5a), X(0x565c3c02), X(0x566ac6c7), X(0x56794faa), + X(0x5687d6a8), X(0x56965bc1), X(0x56a4def4), X(0x56b36040), + X(0x56c1dfa4), X(0x56d05d1f), X(0x56ded8af), X(0x56ed5255), + X(0x56fbca0f), X(0x570a3fdc), X(0x5718b3bc), X(0x572725ac), + X(0x573595ad), X(0x574403bd), X(0x57526fdb), X(0x5760da07), + X(0x576f423f), X(0x577da883), X(0x578c0cd1), X(0x579a6f29), + X(0x57a8cf8a), X(0x57b72df2), X(0x57c58a61), X(0x57d3e4d6), + X(0x57e23d50), X(0x57f093cd), X(0x57fee84e), X(0x580d3ad1), + X(0x581b8b54), X(0x5829d9d8), X(0x5838265c), X(0x584670dd), + X(0x5854b95c), X(0x5862ffd8), X(0x5871444f), X(0x587f86c1), + X(0x588dc72c), X(0x589c0591), X(0x58aa41ed), X(0x58b87c40), + X(0x58c6b489), X(0x58d4eac7), X(0x58e31ef9), X(0x58f1511f), + X(0x58ff8137), X(0x590daf40), X(0x591bdb3a), X(0x592a0524), + X(0x59382cfc), X(0x594652c2), X(0x59547675), X(0x59629815), + X(0x5970b79f), X(0x597ed513), X(0x598cf071), X(0x599b09b7), + X(0x59a920e5), X(0x59b735f9), X(0x59c548f4), X(0x59d359d2), + X(0x59e16895), X(0x59ef753b), X(0x59fd7fc4), X(0x5a0b882d), + X(0x5a198e77), X(0x5a2792a0), X(0x5a3594a9), X(0x5a43948e), + X(0x5a519251), X(0x5a5f8df0), X(0x5a6d876a), X(0x5a7b7ebe), + X(0x5a8973ec), X(0x5a9766f2), X(0x5aa557d0), X(0x5ab34685), + X(0x5ac1330f), X(0x5acf1d6f), X(0x5add05a3), X(0x5aeaebaa), + X(0x5af8cf84), X(0x5b06b12f), X(0x5b1490ab), X(0x5b226df7), + X(0x5b304912), X(0x5b3e21fc), X(0x5b4bf8b2), X(0x5b59cd35), + X(0x5b679f84), X(0x5b756f9e), X(0x5b833d82), X(0x5b91092e), + X(0x5b9ed2a3), X(0x5bac99e0), X(0x5bba5ee3), X(0x5bc821ac), + X(0x5bd5e23a), X(0x5be3a08c), X(0x5bf15ca1), X(0x5bff1679), + X(0x5c0cce12), X(0x5c1a836c), X(0x5c283686), X(0x5c35e760), + X(0x5c4395f7), X(0x5c51424c), X(0x5c5eec5e), X(0x5c6c942b), + X(0x5c7a39b4), X(0x5c87dcf7), X(0x5c957df3), X(0x5ca31ca8), + X(0x5cb0b915), X(0x5cbe5338), X(0x5ccbeb12), X(0x5cd980a1), + X(0x5ce713e5), X(0x5cf4a4dd), X(0x5d023387), X(0x5d0fbfe4), + X(0x5d1d49f2), X(0x5d2ad1b1), X(0x5d38571f), X(0x5d45da3c), + X(0x5d535b08), X(0x5d60d981), X(0x5d6e55a7), X(0x5d7bcf78), + X(0x5d8946f5), X(0x5d96bc1c), X(0x5da42eec), X(0x5db19f65), + X(0x5dbf0d86), X(0x5dcc794e), X(0x5dd9e2bd), X(0x5de749d1), + X(0x5df4ae8a), X(0x5e0210e7), X(0x5e0f70e7), X(0x5e1cce8a), + X(0x5e2a29ce), X(0x5e3782b4), X(0x5e44d93a), X(0x5e522d5f), + X(0x5e5f7f23), X(0x5e6cce85), X(0x5e7a1b85), X(0x5e876620), + X(0x5e94ae58), X(0x5ea1f42a), X(0x5eaf3797), X(0x5ebc789d), + X(0x5ec9b73c), X(0x5ed6f372), X(0x5ee42d41), X(0x5ef164a5), + X(0x5efe999f), X(0x5f0bcc2f), X(0x5f18fc52), X(0x5f262a09), + X(0x5f335553), X(0x5f407e2f), X(0x5f4da49d), X(0x5f5ac89b), + X(0x5f67ea29), X(0x5f750946), X(0x5f8225f2), X(0x5f8f402b), + X(0x5f9c57f2), X(0x5fa96d44), X(0x5fb68023), X(0x5fc3908c), + X(0x5fd09e7f), X(0x5fdda9fc), X(0x5feab302), X(0x5ff7b990), + X(0x6004bda5), X(0x6011bf40), X(0x601ebe62), X(0x602bbb09), + X(0x6038b534), X(0x6045ace4), X(0x6052a216), X(0x605f94cb), + X(0x606c8502), X(0x607972b9), X(0x60865df2), X(0x609346aa), + X(0x60a02ce1), X(0x60ad1096), X(0x60b9f1c9), X(0x60c6d079), + X(0x60d3aca5), X(0x60e0864d), X(0x60ed5d70), X(0x60fa320d), + X(0x61070424), X(0x6113d3b4), X(0x6120a0bc), X(0x612d6b3c), + X(0x613a3332), X(0x6146f89f), X(0x6153bb82), X(0x61607bd9), + X(0x616d39a5), X(0x6179f4e5), X(0x6186ad98), X(0x619363bd), + X(0x61a01753), X(0x61acc85b), X(0x61b976d3), X(0x61c622bc), + X(0x61d2cc13), X(0x61df72d8), X(0x61ec170c), X(0x61f8b8ad), + X(0x620557ba), X(0x6211f434), X(0x621e8e18), X(0x622b2568), + X(0x6237ba21), X(0x62444c44), X(0x6250dbd0), X(0x625d68c4), + X(0x6269f320), X(0x62767ae2), X(0x6283000b), X(0x628f829a), + X(0x629c028e), X(0x62a87fe6), X(0x62b4faa2), X(0x62c172c2), + X(0x62cde844), X(0x62da5b29), X(0x62e6cb6e), X(0x62f33915), + X(0x62ffa41c), X(0x630c0c83), X(0x63187248), X(0x6324d56d), + X(0x633135ef), X(0x633d93ce), X(0x6349ef0b), X(0x635647a3), + X(0x63629d97), X(0x636ef0e6), X(0x637b418f), X(0x63878f92), + X(0x6393daef), X(0x63a023a4), X(0x63ac69b1), X(0x63b8ad15), + X(0x63c4edd1), X(0x63d12be3), X(0x63dd674b), X(0x63e9a008), + X(0x63f5d61a), X(0x64020980), X(0x640e3a39), X(0x641a6846), + X(0x642693a5), X(0x6432bc56), X(0x643ee258), X(0x644b05ab), + X(0x6457264e), X(0x64634441), X(0x646f5f83), X(0x647b7814), + X(0x64878df3), X(0x6493a120), X(0x649fb199), X(0x64abbf5f), + X(0x64b7ca71), X(0x64c3d2ce), X(0x64cfd877), X(0x64dbdb69), + X(0x64e7dba6), X(0x64f3d92b), X(0x64ffd3fa), X(0x650bcc11), + X(0x6517c16f), X(0x6523b415), X(0x652fa402), X(0x653b9134), + X(0x65477bad), X(0x6553636a), X(0x655f486d), X(0x656b2ab3), + X(0x65770a3d), X(0x6582e70a), X(0x658ec11a), X(0x659a986d), + X(0x65a66d00), X(0x65b23ed5), X(0x65be0deb), X(0x65c9da41), + X(0x65d5a3d7), X(0x65e16aac), X(0x65ed2ebf), X(0x65f8f011), + X(0x6604aea1), X(0x66106a6e), X(0x661c2377), X(0x6627d9be), + X(0x66338d40), X(0x663f3dfd), X(0x664aebf5), X(0x66569728), + X(0x66623f95), X(0x666de53b), X(0x6679881b), X(0x66852833), + X(0x6690c583), X(0x669c600b), X(0x66a7f7ca), X(0x66b38cc0), + X(0x66bf1eec), X(0x66caae4f), X(0x66d63ae6), X(0x66e1c4b3), + X(0x66ed4bb4), X(0x66f8cfea), X(0x67045153), X(0x670fcfef), + X(0x671b4bbe), X(0x6726c4bf), X(0x67323af3), X(0x673dae58), + X(0x67491eee), X(0x67548cb5), X(0x675ff7ab), X(0x676b5fd2), + X(0x6776c528), X(0x678227ad), X(0x678d8761), X(0x6798e443), + X(0x67a43e52), X(0x67af958f), X(0x67bae9f9), X(0x67c63b8f), + X(0x67d18a52), X(0x67dcd640), X(0x67e81f59), X(0x67f3659d), + X(0x67fea90c), X(0x6809e9a5), X(0x68152768), X(0x68206254), + X(0x682b9a68), X(0x6836cfa6), X(0x6842020b), X(0x684d3199), + X(0x68585e4d), X(0x68638829), X(0x686eaf2b), X(0x6879d354), + X(0x6884f4a2), X(0x68901316), X(0x689b2eb0), X(0x68a6476d), + X(0x68b15d50), X(0x68bc7056), X(0x68c78080), X(0x68d28dcd), + X(0x68dd983e), X(0x68e89fd0), X(0x68f3a486), X(0x68fea65d), + X(0x6909a555), X(0x6914a16f), X(0x691f9aa9), X(0x692a9104), + X(0x69358480), X(0x6940751b), X(0x694b62d5), X(0x69564daf), + X(0x696135a7), X(0x696c1abe), X(0x6976fcf3), X(0x6981dc46), + X(0x698cb8b6), X(0x69979243), X(0x69a268ed), X(0x69ad3cb4), + X(0x69b80d97), X(0x69c2db96), X(0x69cda6b0), X(0x69d86ee5), + X(0x69e33436), X(0x69edf6a1), X(0x69f8b626), X(0x6a0372c5), + X(0x6a0e2c7e), X(0x6a18e350), X(0x6a23973c), X(0x6a2e4840), + X(0x6a38f65d), X(0x6a43a191), X(0x6a4e49de), X(0x6a58ef42), + X(0x6a6391be), X(0x6a6e3151), X(0x6a78cdfa), X(0x6a8367ba), + X(0x6a8dfe90), X(0x6a98927c), X(0x6aa3237d), X(0x6aadb194), + X(0x6ab83cc0), X(0x6ac2c500), X(0x6acd4a55), X(0x6ad7ccbf), + X(0x6ae24c3c), X(0x6aecc8cd), X(0x6af74271), X(0x6b01b929), + X(0x6b0c2cf4), X(0x6b169dd1), X(0x6b210bc1), X(0x6b2b76c2), + X(0x6b35ded6), X(0x6b4043fc), X(0x6b4aa632), X(0x6b55057a), + X(0x6b5f61d3), X(0x6b69bb3d), X(0x6b7411b7), X(0x6b7e6541), + X(0x6b88b5db), X(0x6b930385), X(0x6b9d4e3f), X(0x6ba79607), + X(0x6bb1dadf), X(0x6bbc1cc6), X(0x6bc65bbb), X(0x6bd097bf), + X(0x6bdad0d0), X(0x6be506f0), X(0x6bef3a1d), X(0x6bf96a58), + X(0x6c0397a0), X(0x6c0dc1f5), X(0x6c17e957), X(0x6c220dc6), + X(0x6c2c2f41), X(0x6c364dc9), X(0x6c40695c), X(0x6c4a81fc), + X(0x6c5497a7), X(0x6c5eaa5d), X(0x6c68ba1f), X(0x6c72c6eb), + X(0x6c7cd0c3), X(0x6c86d7a6), X(0x6c90db92), X(0x6c9adc8a), + X(0x6ca4da8b), X(0x6caed596), X(0x6cb8cdab), X(0x6cc2c2ca), + X(0x6cccb4f2), X(0x6cd6a424), X(0x6ce0905e), X(0x6cea79a1), + X(0x6cf45fee), X(0x6cfe4342), X(0x6d0823a0), X(0x6d120105), + X(0x6d1bdb73), X(0x6d25b2e8), X(0x6d2f8765), X(0x6d3958ea), + X(0x6d432777), X(0x6d4cf30a), X(0x6d56bba5), X(0x6d608147), + X(0x6d6a43f0), X(0x6d7403a0), X(0x6d7dc056), X(0x6d877a13), + X(0x6d9130d6), X(0x6d9ae4a0), X(0x6da4956f), X(0x6dae4345), + X(0x6db7ee20), X(0x6dc19601), X(0x6dcb3ae7), X(0x6dd4dcd3), + X(0x6dde7bc4), X(0x6de817bb), X(0x6df1b0b6), X(0x6dfb46b7), + X(0x6e04d9bc), X(0x6e0e69c7), X(0x6e17f6d5), X(0x6e2180e9), + X(0x6e2b0801), X(0x6e348c1d), X(0x6e3e0d3d), X(0x6e478b62), + X(0x6e51068a), X(0x6e5a7eb7), X(0x6e63f3e7), X(0x6e6d661b), + X(0x6e76d552), X(0x6e80418e), X(0x6e89aacc), X(0x6e93110f), + X(0x6e9c7454), X(0x6ea5d49d), X(0x6eaf31e9), X(0x6eb88c37), + X(0x6ec1e389), X(0x6ecb37de), X(0x6ed48936), X(0x6eddd790), + X(0x6ee722ee), X(0x6ef06b4d), X(0x6ef9b0b0), X(0x6f02f315), + X(0x6f0c327c), X(0x6f156ee6), X(0x6f1ea852), X(0x6f27dec1), + X(0x6f311232), X(0x6f3a42a5), X(0x6f43701a), X(0x6f4c9a91), + X(0x6f55c20a), X(0x6f5ee686), X(0x6f680803), X(0x6f712682), + X(0x6f7a4203), X(0x6f835a86), X(0x6f8c700b), X(0x6f958291), + X(0x6f9e921a), X(0x6fa79ea4), X(0x6fb0a830), X(0x6fb9aebd), + X(0x6fc2b24c), X(0x6fcbb2dd), X(0x6fd4b06f), X(0x6fddab03), + X(0x6fe6a299), X(0x6fef9730), X(0x6ff888c9), X(0x70017763), + X(0x700a62ff), X(0x70134b9c), X(0x701c313b), X(0x702513dc), + X(0x702df37e), X(0x7036d021), X(0x703fa9c6), X(0x7048806d), + X(0x70515415), X(0x705a24bf), X(0x7062f26b), X(0x706bbd17), + X(0x707484c6), X(0x707d4976), X(0x70860b28), X(0x708ec9dc), + X(0x70978591), X(0x70a03e48), X(0x70a8f400), X(0x70b1a6bb), + X(0x70ba5677), X(0x70c30335), X(0x70cbacf5), X(0x70d453b6), + X(0x70dcf77a), X(0x70e59840), X(0x70ee3607), X(0x70f6d0d1), + X(0x70ff689d), X(0x7107fd6b), X(0x71108f3b), X(0x71191e0d), + X(0x7121a9e2), X(0x712a32b9), X(0x7132b892), X(0x713b3b6e), + X(0x7143bb4c), X(0x714c382d), X(0x7154b211), X(0x715d28f7), + X(0x71659ce0), X(0x716e0dcc), X(0x71767bbb), X(0x717ee6ac), + X(0x71874ea1), X(0x718fb399), X(0x71981594), X(0x71a07493), + X(0x71a8d094), X(0x71b1299a), X(0x71b97fa2), X(0x71c1d2af), + X(0x71ca22bf), X(0x71d26fd2), X(0x71dab9ea), X(0x71e30106), + X(0x71eb4526), X(0x71f3864a), X(0x71fbc472), X(0x7203ff9e), + X(0x720c37cf), X(0x72146d05), X(0x721c9f3f), X(0x7224ce7e), + X(0x722cfac2), X(0x7235240b), X(0x723d4a59), X(0x72456dad), + X(0x724d8e05), X(0x7255ab63), X(0x725dc5c7), X(0x7265dd31), + X(0x726df1a0), X(0x72760315), X(0x727e1191), X(0x72861d12), + X(0x728e259a), X(0x72962b28), X(0x729e2dbd), X(0x72a62d59), + X(0x72ae29fc), X(0x72b623a5), X(0x72be1a56), X(0x72c60e0e), + X(0x72cdfece), X(0x72d5ec95), X(0x72ddd764), X(0x72e5bf3b), + X(0x72eda41a), X(0x72f58601), X(0x72fd64f1), X(0x730540e9), + X(0x730d19e9), X(0x7314eff3), X(0x731cc305), X(0x73249321), + X(0x732c6046), X(0x73342a75), X(0x733bf1ad), X(0x7343b5ef), + X(0x734b773b), X(0x73533591), X(0x735af0f2), X(0x7362a95d), + X(0x736a5ed3), X(0x73721153), X(0x7379c0df), X(0x73816d76), + X(0x73891719), X(0x7390bdc7), X(0x73986181), X(0x73a00247), + X(0x73a7a01a), X(0x73af3af8), X(0x73b6d2e4), X(0x73be67dc), + X(0x73c5f9e1), X(0x73cd88f3), X(0x73d51513), X(0x73dc9e40), + X(0x73e4247c), X(0x73eba7c5), X(0x73f3281c), X(0x73faa582), + X(0x74021ff7), X(0x7409977b), X(0x74110c0d), X(0x74187daf), + X(0x741fec61), X(0x74275822), X(0x742ec0f3), X(0x743626d5), + X(0x743d89c7), X(0x7444e9c9), X(0x744c46dd), X(0x7453a101), + X(0x745af837), X(0x74624c7f), X(0x74699dd8), X(0x7470ec44), + X(0x747837c2), X(0x747f8052), X(0x7486c5f5), X(0x748e08ac), + X(0x74954875), X(0x749c8552), X(0x74a3bf43), X(0x74aaf648), + X(0x74b22a62), X(0x74b95b90), X(0x74c089d2), X(0x74c7b52a), + X(0x74cedd97), X(0x74d6031a), X(0x74dd25b2), X(0x74e44561), + X(0x74eb6226), X(0x74f27c02), X(0x74f992f5), X(0x7500a6ff), + X(0x7507b820), X(0x750ec659), X(0x7515d1aa), X(0x751cda14), + X(0x7523df96), X(0x752ae231), X(0x7531e1e5), X(0x7538deb2), + X(0x753fd89a), X(0x7546cf9b), X(0x754dc3b7), X(0x7554b4ed), + X(0x755ba33e), X(0x75628eaa), X(0x75697732), X(0x75705cd5), + X(0x75773f95), X(0x757e1f71), X(0x7584fc6a), X(0x758bd67f), + X(0x7592adb2), X(0x75998203), X(0x75a05371), X(0x75a721fe), + X(0x75adeda9), X(0x75b4b673), X(0x75bb7c5c), X(0x75c23f65), + X(0x75c8ff8d), X(0x75cfbcd6), X(0x75d6773f), X(0x75dd2ec8), + X(0x75e3e373), X(0x75ea953f), X(0x75f1442d), X(0x75f7f03d), + X(0x75fe996f), X(0x76053fc5), X(0x760be33d), X(0x761283d8), + X(0x76192197), X(0x761fbc7b), X(0x76265482), X(0x762ce9af), + X(0x76337c01), X(0x763a0b78), X(0x76409814), X(0x764721d7), + X(0x764da8c1), X(0x76542cd1), X(0x765aae08), X(0x76612c67), + X(0x7667a7ee), X(0x766e209d), X(0x76749675), X(0x767b0975), + X(0x7681799f), X(0x7687e6f3), X(0x768e5170), X(0x7694b918), + X(0x769b1deb), X(0x76a17fe9), X(0x76a7df13), X(0x76ae3b68), + X(0x76b494ea), X(0x76baeb98), X(0x76c13f74), X(0x76c7907c), + X(0x76cddeb3), X(0x76d42a18), X(0x76da72ab), X(0x76e0b86d), + X(0x76e6fb5e), X(0x76ed3b7f), X(0x76f378d0), X(0x76f9b352), + X(0x76ffeb05), X(0x77061fe8), X(0x770c51fe), X(0x77128145), + X(0x7718adbf), X(0x771ed76c), X(0x7724fe4c), X(0x772b225f), + X(0x773143a7), X(0x77376223), X(0x773d7dd3), X(0x774396ba), + X(0x7749acd5), X(0x774fc027), X(0x7755d0af), X(0x775bde6f), + X(0x7761e965), X(0x7767f193), X(0x776df6fa), X(0x7773f998), + X(0x7779f970), X(0x777ff681), X(0x7785f0cd), X(0x778be852), + X(0x7791dd12), X(0x7797cf0d), X(0x779dbe43), X(0x77a3aab6), + X(0x77a99465), X(0x77af7b50), X(0x77b55f79), X(0x77bb40e0), + X(0x77c11f85), X(0x77c6fb68), X(0x77ccd48a), X(0x77d2aaec), + X(0x77d87e8d), X(0x77de4f6f), X(0x77e41d92), X(0x77e9e8f5), + X(0x77efb19b), X(0x77f57782), X(0x77fb3aad), X(0x7800fb1a), + X(0x7806b8ca), X(0x780c73bf), X(0x78122bf7), X(0x7817e175), + X(0x781d9438), X(0x78234440), X(0x7828f18f), X(0x782e9c25), + X(0x78344401), X(0x7839e925), X(0x783f8b92), X(0x78452b46), + X(0x784ac844), X(0x7850628b), X(0x7855fa1c), X(0x785b8ef8), + X(0x7861211e), X(0x7866b090), X(0x786c3d4d), X(0x7871c757), + X(0x78774ead), X(0x787cd351), X(0x78825543), X(0x7887d483), + X(0x788d5111), X(0x7892caef), X(0x7898421c), X(0x789db69a), + X(0x78a32868), X(0x78a89787), X(0x78ae03f8), X(0x78b36dbb), + X(0x78b8d4d1), X(0x78be393a), X(0x78c39af6), X(0x78c8fa06), + X(0x78ce566c), X(0x78d3b026), X(0x78d90736), X(0x78de5b9c), + X(0x78e3ad58), X(0x78e8fc6c), X(0x78ee48d7), X(0x78f3929b), + X(0x78f8d9b7), X(0x78fe1e2c), X(0x79035ffb), X(0x79089f24), + X(0x790ddba8), X(0x79131587), X(0x79184cc2), X(0x791d8159), + X(0x7922b34d), X(0x7927e29e), X(0x792d0f4d), X(0x7932395a), + X(0x793760c6), X(0x793c8591), X(0x7941a7bd), X(0x7946c749), + X(0x794be435), X(0x7950fe84), X(0x79561634), X(0x795b2b47), + X(0x79603dbc), X(0x79654d96), X(0x796a5ad4), X(0x796f6576), + X(0x79746d7e), X(0x797972eb), X(0x797e75bf), X(0x798375f9), + X(0x7988739b), X(0x798d6ea5), X(0x79926717), X(0x79975cf2), + X(0x799c5037), X(0x79a140e6), X(0x79a62f00), X(0x79ab1a85), + X(0x79b00376), X(0x79b4e9d3), X(0x79b9cd9d), X(0x79beaed4), + X(0x79c38d79), X(0x79c8698d), X(0x79cd4310), X(0x79d21a03), + X(0x79d6ee66), X(0x79dbc03a), X(0x79e08f7f), X(0x79e55c36), + X(0x79ea265f), X(0x79eeedfc), X(0x79f3b30c), X(0x79f87590), + X(0x79fd3589), X(0x7a01f2f7), X(0x7a06addc), X(0x7a0b6636), + X(0x7a101c08), X(0x7a14cf52), X(0x7a198013), X(0x7a1e2e4d), + X(0x7a22da01), X(0x7a27832f), X(0x7a2c29d7), X(0x7a30cdfa), + X(0x7a356f99), X(0x7a3a0eb4), X(0x7a3eab4c), X(0x7a434561), + X(0x7a47dcf5), X(0x7a4c7207), X(0x7a510498), X(0x7a5594a9), + X(0x7a5a223a), X(0x7a5ead4d), X(0x7a6335e0), X(0x7a67bbf6), + X(0x7a6c3f8f), X(0x7a70c0ab), X(0x7a753f4b), X(0x7a79bb6f), + X(0x7a7e3519), X(0x7a82ac48), X(0x7a8720fe), X(0x7a8b933b), + X(0x7a9002ff), X(0x7a94704b), X(0x7a98db20), X(0x7a9d437e), + X(0x7aa1a967), X(0x7aa60cd9), X(0x7aaa6dd7), X(0x7aaecc61), + X(0x7ab32877), X(0x7ab7821b), X(0x7abbd94b), X(0x7ac02e0a), + X(0x7ac48058), X(0x7ac8d035), X(0x7acd1da3), X(0x7ad168a1), + X(0x7ad5b130), X(0x7ad9f751), X(0x7ade3b05), X(0x7ae27c4c), + X(0x7ae6bb27), X(0x7aeaf796), X(0x7aef319a), X(0x7af36934), + X(0x7af79e64), X(0x7afbd12c), X(0x7b00018a), X(0x7b042f81), + X(0x7b085b10), X(0x7b0c8439), X(0x7b10aafc), X(0x7b14cf5a), + X(0x7b18f153), X(0x7b1d10e8), X(0x7b212e1a), X(0x7b2548e9), + X(0x7b296155), X(0x7b2d7761), X(0x7b318b0b), X(0x7b359c55), + X(0x7b39ab3f), X(0x7b3db7cb), X(0x7b41c1f8), X(0x7b45c9c8), + X(0x7b49cf3b), X(0x7b4dd251), X(0x7b51d30b), X(0x7b55d16b), + X(0x7b59cd70), X(0x7b5dc71b), X(0x7b61be6d), X(0x7b65b366), + X(0x7b69a608), X(0x7b6d9653), X(0x7b718447), X(0x7b756fe5), + X(0x7b79592e), X(0x7b7d4022), X(0x7b8124c3), X(0x7b850710), + X(0x7b88e70a), X(0x7b8cc4b3), X(0x7b90a00a), X(0x7b947911), + X(0x7b984fc8), X(0x7b9c242f), X(0x7b9ff648), X(0x7ba3c612), + X(0x7ba79390), X(0x7bab5ec1), X(0x7baf27a5), X(0x7bb2ee3f), + X(0x7bb6b28e), X(0x7bba7493), X(0x7bbe344e), X(0x7bc1f1c1), + X(0x7bc5acec), X(0x7bc965cf), X(0x7bcd1c6c), X(0x7bd0d0c3), + X(0x7bd482d4), X(0x7bd832a1), X(0x7bdbe02a), X(0x7bdf8b70), + X(0x7be33473), X(0x7be6db34), X(0x7bea7fb4), X(0x7bee21f4), + X(0x7bf1c1f3), X(0x7bf55fb3), X(0x7bf8fb35), X(0x7bfc9479), + X(0x7c002b7f), X(0x7c03c04a), X(0x7c0752d8), X(0x7c0ae32b), + X(0x7c0e7144), X(0x7c11fd23), X(0x7c1586c9), X(0x7c190e36), + X(0x7c1c936c), X(0x7c20166b), X(0x7c239733), X(0x7c2715c6), + X(0x7c2a9224), X(0x7c2e0c4e), X(0x7c318444), X(0x7c34fa07), + X(0x7c386d98), X(0x7c3bdef8), X(0x7c3f4e26), X(0x7c42bb25), + X(0x7c4625f4), X(0x7c498e95), X(0x7c4cf507), X(0x7c50594c), + X(0x7c53bb65), X(0x7c571b51), X(0x7c5a7913), X(0x7c5dd4aa), + X(0x7c612e17), X(0x7c64855b), X(0x7c67da76), X(0x7c6b2d6a), + X(0x7c6e7e37), X(0x7c71ccdd), X(0x7c75195e), X(0x7c7863ba), + X(0x7c7babf1), X(0x7c7ef206), X(0x7c8235f7), X(0x7c8577c6), + X(0x7c88b774), X(0x7c8bf502), X(0x7c8f306f), X(0x7c9269bd), + X(0x7c95a0ec), X(0x7c98d5fe), X(0x7c9c08f2), X(0x7c9f39cb), + X(0x7ca26887), X(0x7ca59528), X(0x7ca8bfb0), X(0x7cabe81d), + X(0x7caf0e72), X(0x7cb232af), X(0x7cb554d4), X(0x7cb874e2), + X(0x7cbb92db), X(0x7cbeaebe), X(0x7cc1c88d), X(0x7cc4e047), + X(0x7cc7f5ef), X(0x7ccb0984), X(0x7cce1b08), X(0x7cd12a7b), + X(0x7cd437dd), X(0x7cd74330), X(0x7cda4c74), X(0x7cdd53aa), + X(0x7ce058d3), X(0x7ce35bef), X(0x7ce65cff), X(0x7ce95c04), + X(0x7cec58ff), X(0x7cef53f0), X(0x7cf24cd7), X(0x7cf543b7), + X(0x7cf8388f), X(0x7cfb2b60), X(0x7cfe1c2b), X(0x7d010af1), + X(0x7d03f7b2), X(0x7d06e26f), X(0x7d09cb29), X(0x7d0cb1e0), + X(0x7d0f9696), X(0x7d12794b), X(0x7d1559ff), X(0x7d1838b4), + X(0x7d1b156a), X(0x7d1df022), X(0x7d20c8dd), X(0x7d239f9b), + X(0x7d26745e), X(0x7d294725), X(0x7d2c17f1), X(0x7d2ee6c4), + X(0x7d31b39f), X(0x7d347e81), X(0x7d37476b), X(0x7d3a0e5f), + X(0x7d3cd35d), X(0x7d3f9665), X(0x7d425779), X(0x7d451699), + X(0x7d47d3c6), X(0x7d4a8f01), X(0x7d4d484b), X(0x7d4fffa3), + X(0x7d52b50c), X(0x7d556885), X(0x7d581a0f), X(0x7d5ac9ac), + X(0x7d5d775c), X(0x7d60231f), X(0x7d62ccf6), X(0x7d6574e3), + X(0x7d681ae6), X(0x7d6abeff), X(0x7d6d612f), X(0x7d700178), + X(0x7d729fd9), X(0x7d753c54), X(0x7d77d6e9), X(0x7d7a6f9a), + X(0x7d7d0666), X(0x7d7f9b4f), X(0x7d822e55), X(0x7d84bf79), + X(0x7d874ebc), X(0x7d89dc1e), X(0x7d8c67a1), X(0x7d8ef144), + X(0x7d91790a), X(0x7d93fef2), X(0x7d9682fd), X(0x7d99052d), + X(0x7d9b8581), X(0x7d9e03fb), X(0x7da0809b), X(0x7da2fb62), + X(0x7da57451), X(0x7da7eb68), X(0x7daa60a8), X(0x7dacd413), + X(0x7daf45a9), X(0x7db1b56a), X(0x7db42357), X(0x7db68f71), + X(0x7db8f9b9), X(0x7dbb6230), X(0x7dbdc8d6), X(0x7dc02dac), + X(0x7dc290b3), X(0x7dc4f1eb), X(0x7dc75156), X(0x7dc9aef4), + X(0x7dcc0ac5), X(0x7dce64cc), X(0x7dd0bd07), X(0x7dd31379), + X(0x7dd56821), X(0x7dd7bb01), X(0x7dda0c1a), X(0x7ddc5b6b), + X(0x7ddea8f7), X(0x7de0f4bd), X(0x7de33ebe), X(0x7de586fc), + X(0x7de7cd76), X(0x7dea122e), X(0x7dec5525), X(0x7dee965a), + X(0x7df0d5d0), X(0x7df31386), X(0x7df54f7e), X(0x7df789b8), + X(0x7df9c235), X(0x7dfbf8f5), X(0x7dfe2dfa), X(0x7e006145), + X(0x7e0292d5), X(0x7e04c2ac), X(0x7e06f0cb), X(0x7e091d32), + X(0x7e0b47e1), X(0x7e0d70db), X(0x7e0f981f), X(0x7e11bdaf), + X(0x7e13e18a), X(0x7e1603b3), X(0x7e182429), X(0x7e1a42ed), + X(0x7e1c6001), X(0x7e1e7b64), X(0x7e209518), X(0x7e22ad1d), + X(0x7e24c375), X(0x7e26d81f), X(0x7e28eb1d), X(0x7e2afc70), + X(0x7e2d0c17), X(0x7e2f1a15), X(0x7e31266a), X(0x7e333115), + X(0x7e353a1a), X(0x7e374177), X(0x7e39472e), X(0x7e3b4b3f), + X(0x7e3d4dac), X(0x7e3f4e75), X(0x7e414d9a), X(0x7e434b1e), + X(0x7e4546ff), X(0x7e474140), X(0x7e4939e0), X(0x7e4b30e2), + X(0x7e4d2644), X(0x7e4f1a09), X(0x7e510c30), X(0x7e52fcbc), + X(0x7e54ebab), X(0x7e56d900), X(0x7e58c4bb), X(0x7e5aaedd), + X(0x7e5c9766), X(0x7e5e7e57), X(0x7e6063b2), X(0x7e624776), + X(0x7e6429a5), X(0x7e660a3f), X(0x7e67e945), X(0x7e69c6b8), + X(0x7e6ba299), X(0x7e6d7ce7), X(0x7e6f55a5), X(0x7e712cd3), + X(0x7e730272), X(0x7e74d682), X(0x7e76a904), X(0x7e7879f9), + X(0x7e7a4962), X(0x7e7c173f), X(0x7e7de392), X(0x7e7fae5a), + X(0x7e817799), X(0x7e833f50), X(0x7e85057f), X(0x7e86ca27), + X(0x7e888d49), X(0x7e8a4ee5), X(0x7e8c0efd), X(0x7e8dcd91), + X(0x7e8f8aa1), X(0x7e914630), X(0x7e93003c), X(0x7e94b8c8), + X(0x7e966fd4), X(0x7e982560), X(0x7e99d96e), X(0x7e9b8bfe), + X(0x7e9d3d10), X(0x7e9eeca7), X(0x7ea09ac2), X(0x7ea24762), + X(0x7ea3f288), X(0x7ea59c35), X(0x7ea7446a), X(0x7ea8eb27), + X(0x7eaa906c), X(0x7eac343c), X(0x7eadd696), X(0x7eaf777b), + X(0x7eb116ed), X(0x7eb2b4eb), X(0x7eb45177), X(0x7eb5ec91), + X(0x7eb7863b), X(0x7eb91e74), X(0x7ebab53e), X(0x7ebc4a99), + X(0x7ebdde87), X(0x7ebf7107), X(0x7ec1021b), X(0x7ec291c3), + X(0x7ec42001), X(0x7ec5acd5), X(0x7ec7383f), X(0x7ec8c241), + X(0x7eca4adb), X(0x7ecbd20d), X(0x7ecd57da), X(0x7ecedc41), + X(0x7ed05f44), X(0x7ed1e0e2), X(0x7ed3611d), X(0x7ed4dff6), + X(0x7ed65d6d), X(0x7ed7d983), X(0x7ed95438), X(0x7edacd8f), + X(0x7edc4586), X(0x7eddbc20), X(0x7edf315c), X(0x7ee0a53c), + X(0x7ee217c1), X(0x7ee388ea), X(0x7ee4f8b9), X(0x7ee6672f), + X(0x7ee7d44c), X(0x7ee94012), X(0x7eeaaa80), X(0x7eec1397), + X(0x7eed7b59), X(0x7eeee1c6), X(0x7ef046df), X(0x7ef1aaa5), + X(0x7ef30d18), X(0x7ef46e39), X(0x7ef5ce09), X(0x7ef72c88), + X(0x7ef889b8), X(0x7ef9e599), X(0x7efb402c), X(0x7efc9972), + X(0x7efdf16b), X(0x7eff4818), X(0x7f009d79), X(0x7f01f191), + X(0x7f03445f), X(0x7f0495e4), X(0x7f05e620), X(0x7f073516), + X(0x7f0882c5), X(0x7f09cf2d), X(0x7f0b1a51), X(0x7f0c6430), + X(0x7f0daccc), X(0x7f0ef425), X(0x7f103a3b), X(0x7f117f11), + X(0x7f12c2a5), X(0x7f1404fa), X(0x7f15460f), X(0x7f1685e6), + X(0x7f17c47f), X(0x7f1901db), X(0x7f1a3dfb), X(0x7f1b78e0), + X(0x7f1cb28a), X(0x7f1deafa), X(0x7f1f2231), X(0x7f20582f), + X(0x7f218cf5), X(0x7f22c085), X(0x7f23f2de), X(0x7f252401), + X(0x7f2653f0), X(0x7f2782ab), X(0x7f28b032), X(0x7f29dc87), + X(0x7f2b07aa), X(0x7f2c319c), X(0x7f2d5a5e), X(0x7f2e81f0), + X(0x7f2fa853), X(0x7f30cd88), X(0x7f31f18f), X(0x7f33146a), + X(0x7f343619), X(0x7f35569c), X(0x7f3675f6), X(0x7f379425), + X(0x7f38b12c), X(0x7f39cd0a), X(0x7f3ae7c0), X(0x7f3c0150), + X(0x7f3d19ba), X(0x7f3e30fe), X(0x7f3f471e), X(0x7f405c1a), + X(0x7f416ff3), X(0x7f4282a9), X(0x7f43943e), X(0x7f44a4b2), + X(0x7f45b405), X(0x7f46c239), X(0x7f47cf4e), X(0x7f48db45), + X(0x7f49e61f), X(0x7f4aefdc), X(0x7f4bf87e), X(0x7f4d0004), + X(0x7f4e0670), X(0x7f4f0bc2), X(0x7f500ffb), X(0x7f51131c), + X(0x7f521525), X(0x7f531618), X(0x7f5415f4), X(0x7f5514bb), + X(0x7f56126e), X(0x7f570f0c), X(0x7f580a98), X(0x7f590511), + X(0x7f59fe78), X(0x7f5af6ce), X(0x7f5bee14), X(0x7f5ce44a), + X(0x7f5dd972), X(0x7f5ecd8b), X(0x7f5fc097), X(0x7f60b296), + X(0x7f61a389), X(0x7f629370), X(0x7f63824e), X(0x7f647021), + X(0x7f655ceb), X(0x7f6648ad), X(0x7f673367), X(0x7f681d19), + X(0x7f6905c6), X(0x7f69ed6d), X(0x7f6ad40f), X(0x7f6bb9ad), + X(0x7f6c9e48), X(0x7f6d81e0), X(0x7f6e6475), X(0x7f6f460a), + X(0x7f70269d), X(0x7f710631), X(0x7f71e4c6), X(0x7f72c25c), + X(0x7f739ef4), X(0x7f747a8f), X(0x7f75552e), X(0x7f762ed1), + X(0x7f770779), X(0x7f77df27), X(0x7f78b5db), X(0x7f798b97), + X(0x7f7a605a), X(0x7f7b3425), X(0x7f7c06fa), X(0x7f7cd8d9), + X(0x7f7da9c2), X(0x7f7e79b7), X(0x7f7f48b8), X(0x7f8016c5), + X(0x7f80e3e0), X(0x7f81b009), X(0x7f827b40), X(0x7f834588), + X(0x7f840edf), X(0x7f84d747), X(0x7f859ec1), X(0x7f86654d), + X(0x7f872aec), X(0x7f87ef9e), X(0x7f88b365), X(0x7f897641), + X(0x7f8a3832), X(0x7f8af93a), X(0x7f8bb959), X(0x7f8c7890), + X(0x7f8d36df), X(0x7f8df448), X(0x7f8eb0ca), X(0x7f8f6c67), + X(0x7f90271e), X(0x7f90e0f2), X(0x7f9199e2), X(0x7f9251f0), + X(0x7f93091b), X(0x7f93bf65), X(0x7f9474ce), X(0x7f952958), + X(0x7f95dd01), X(0x7f968fcd), X(0x7f9741ba), X(0x7f97f2ca), + X(0x7f98a2fd), X(0x7f995254), X(0x7f9a00d0), X(0x7f9aae71), + X(0x7f9b5b38), X(0x7f9c0726), X(0x7f9cb23b), X(0x7f9d5c78), + X(0x7f9e05de), X(0x7f9eae6e), X(0x7f9f5627), X(0x7f9ffd0b), + X(0x7fa0a31b), X(0x7fa14856), X(0x7fa1ecbf), X(0x7fa29054), + X(0x7fa33318), X(0x7fa3d50b), X(0x7fa4762c), X(0x7fa5167e), + X(0x7fa5b601), X(0x7fa654b5), X(0x7fa6f29b), X(0x7fa78fb3), + X(0x7fa82bff), X(0x7fa8c77f), X(0x7fa96234), X(0x7fa9fc1e), + X(0x7faa953e), X(0x7fab2d94), X(0x7fabc522), X(0x7fac5be8), + X(0x7facf1e6), X(0x7fad871d), X(0x7fae1b8f), X(0x7faeaf3b), + X(0x7faf4222), X(0x7fafd445), X(0x7fb065a4), X(0x7fb0f641), + X(0x7fb1861b), X(0x7fb21534), X(0x7fb2a38c), X(0x7fb33124), + X(0x7fb3bdfb), X(0x7fb44a14), X(0x7fb4d56f), X(0x7fb5600c), + X(0x7fb5e9ec), X(0x7fb6730f), X(0x7fb6fb76), X(0x7fb78323), + X(0x7fb80a15), X(0x7fb8904d), X(0x7fb915cc), X(0x7fb99a92), + X(0x7fba1ea0), X(0x7fbaa1f7), X(0x7fbb2497), X(0x7fbba681), + X(0x7fbc27b5), X(0x7fbca835), X(0x7fbd2801), X(0x7fbda719), + X(0x7fbe257e), X(0x7fbea331), X(0x7fbf2032), X(0x7fbf9c82), + X(0x7fc01821), X(0x7fc09311), X(0x7fc10d52), X(0x7fc186e4), + X(0x7fc1ffc8), X(0x7fc277ff), X(0x7fc2ef89), X(0x7fc36667), + X(0x7fc3dc9a), X(0x7fc45221), X(0x7fc4c6ff), X(0x7fc53b33), + X(0x7fc5aebe), X(0x7fc621a0), X(0x7fc693db), X(0x7fc7056f), + X(0x7fc7765c), X(0x7fc7e6a3), X(0x7fc85645), X(0x7fc8c542), + X(0x7fc9339b), X(0x7fc9a150), X(0x7fca0e63), X(0x7fca7ad3), + X(0x7fcae6a2), X(0x7fcb51cf), X(0x7fcbbc5c), X(0x7fcc2649), + X(0x7fcc8f97), X(0x7fccf846), X(0x7fcd6058), X(0x7fcdc7cb), + X(0x7fce2ea2), X(0x7fce94dd), X(0x7fcefa7b), X(0x7fcf5f7f), + X(0x7fcfc3e8), X(0x7fd027b7), X(0x7fd08aed), X(0x7fd0ed8b), + X(0x7fd14f90), X(0x7fd1b0fd), X(0x7fd211d4), X(0x7fd27214), + X(0x7fd2d1bf), X(0x7fd330d4), X(0x7fd38f55), X(0x7fd3ed41), + X(0x7fd44a9a), X(0x7fd4a761), X(0x7fd50395), X(0x7fd55f37), + X(0x7fd5ba48), X(0x7fd614c9), X(0x7fd66eba), X(0x7fd6c81b), + X(0x7fd720ed), X(0x7fd77932), X(0x7fd7d0e8), X(0x7fd82812), + X(0x7fd87eae), X(0x7fd8d4bf), X(0x7fd92a45), X(0x7fd97f40), + X(0x7fd9d3b0), X(0x7fda2797), X(0x7fda7af5), X(0x7fdacdca), + X(0x7fdb2018), X(0x7fdb71dd), X(0x7fdbc31c), X(0x7fdc13d5), + X(0x7fdc6408), X(0x7fdcb3b6), X(0x7fdd02df), X(0x7fdd5184), + X(0x7fdd9fa5), X(0x7fdded44), X(0x7fde3a60), X(0x7fde86fb), + X(0x7fded314), X(0x7fdf1eac), X(0x7fdf69c4), X(0x7fdfb45d), + X(0x7fdffe76), X(0x7fe04811), X(0x7fe0912e), X(0x7fe0d9ce), + X(0x7fe121f0), X(0x7fe16996), X(0x7fe1b0c1), X(0x7fe1f770), + X(0x7fe23da4), X(0x7fe2835f), X(0x7fe2c89f), X(0x7fe30d67), + X(0x7fe351b5), X(0x7fe3958c), X(0x7fe3d8ec), X(0x7fe41bd4), + X(0x7fe45e46), X(0x7fe4a042), X(0x7fe4e1c8), X(0x7fe522da), + X(0x7fe56378), X(0x7fe5a3a1), X(0x7fe5e358), X(0x7fe6229b), + X(0x7fe6616d), X(0x7fe69fcc), X(0x7fe6ddbb), X(0x7fe71b39), + X(0x7fe75847), X(0x7fe794e5), X(0x7fe7d114), X(0x7fe80cd5), + X(0x7fe84827), X(0x7fe8830c), X(0x7fe8bd84), X(0x7fe8f78f), + X(0x7fe9312f), X(0x7fe96a62), X(0x7fe9a32b), X(0x7fe9db8a), + X(0x7fea137e), X(0x7fea4b09), X(0x7fea822b), X(0x7feab8e5), + X(0x7feaef37), X(0x7feb2521), X(0x7feb5aa4), X(0x7feb8fc1), + X(0x7febc478), X(0x7febf8ca), X(0x7fec2cb6), X(0x7fec603e), + X(0x7fec9363), X(0x7fecc623), X(0x7fecf881), X(0x7fed2a7c), + X(0x7fed5c16), X(0x7fed8d4e), X(0x7fedbe24), X(0x7fedee9b), + X(0x7fee1eb1), X(0x7fee4e68), X(0x7fee7dc0), X(0x7feeacb9), + X(0x7feedb54), X(0x7fef0991), X(0x7fef3771), X(0x7fef64f5), + X(0x7fef921d), X(0x7fefbee8), X(0x7fefeb59), X(0x7ff0176f), + X(0x7ff0432a), X(0x7ff06e8c), X(0x7ff09995), X(0x7ff0c444), + X(0x7ff0ee9c), X(0x7ff1189b), X(0x7ff14243), X(0x7ff16b94), + X(0x7ff1948e), X(0x7ff1bd32), X(0x7ff1e581), X(0x7ff20d7b), + X(0x7ff2351f), X(0x7ff25c70), X(0x7ff2836d), X(0x7ff2aa17), + X(0x7ff2d06d), X(0x7ff2f672), X(0x7ff31c24), X(0x7ff34185), + X(0x7ff36695), X(0x7ff38b55), X(0x7ff3afc4), X(0x7ff3d3e4), + X(0x7ff3f7b4), X(0x7ff41b35), X(0x7ff43e69), X(0x7ff4614e), + X(0x7ff483e6), X(0x7ff4a631), X(0x7ff4c82f), X(0x7ff4e9e1), + X(0x7ff50b47), X(0x7ff52c62), X(0x7ff54d33), X(0x7ff56db9), + X(0x7ff58df5), X(0x7ff5ade7), X(0x7ff5cd90), X(0x7ff5ecf1), + X(0x7ff60c09), X(0x7ff62ada), X(0x7ff64963), X(0x7ff667a5), + X(0x7ff685a1), X(0x7ff6a357), X(0x7ff6c0c7), X(0x7ff6ddf1), + X(0x7ff6fad7), X(0x7ff71778), X(0x7ff733d6), X(0x7ff74fef), + X(0x7ff76bc6), X(0x7ff78759), X(0x7ff7a2ab), X(0x7ff7bdba), + X(0x7ff7d888), X(0x7ff7f315), X(0x7ff80d61), X(0x7ff8276c), + X(0x7ff84138), X(0x7ff85ac4), X(0x7ff87412), X(0x7ff88d20), + X(0x7ff8a5f0), X(0x7ff8be82), X(0x7ff8d6d7), X(0x7ff8eeef), + X(0x7ff906c9), X(0x7ff91e68), X(0x7ff935cb), X(0x7ff94cf2), + X(0x7ff963dd), X(0x7ff97a8f), X(0x7ff99105), X(0x7ff9a742), + X(0x7ff9bd45), X(0x7ff9d30f), X(0x7ff9e8a0), X(0x7ff9fdf9), + X(0x7ffa131a), X(0x7ffa2803), X(0x7ffa3cb4), X(0x7ffa512f), + X(0x7ffa6573), X(0x7ffa7981), X(0x7ffa8d59), X(0x7ffaa0fc), + X(0x7ffab46a), X(0x7ffac7a3), X(0x7ffadaa8), X(0x7ffaed78), + X(0x7ffb0015), X(0x7ffb127f), X(0x7ffb24b6), X(0x7ffb36bb), + X(0x7ffb488d), X(0x7ffb5a2e), X(0x7ffb6b9d), X(0x7ffb7cdb), + X(0x7ffb8de9), X(0x7ffb9ec6), X(0x7ffbaf73), X(0x7ffbbff1), + X(0x7ffbd03f), X(0x7ffbe05e), X(0x7ffbf04f), X(0x7ffc0012), + X(0x7ffc0fa6), X(0x7ffc1f0d), X(0x7ffc2e47), X(0x7ffc3d54), + X(0x7ffc4c35), X(0x7ffc5ae9), X(0x7ffc6971), X(0x7ffc77ce), + X(0x7ffc8600), X(0x7ffc9407), X(0x7ffca1e4), X(0x7ffcaf96), + X(0x7ffcbd1f), X(0x7ffcca7e), X(0x7ffcd7b4), X(0x7ffce4c1), + X(0x7ffcf1a5), X(0x7ffcfe62), X(0x7ffd0af6), X(0x7ffd1763), + X(0x7ffd23a9), X(0x7ffd2fc8), X(0x7ffd3bc1), X(0x7ffd4793), + X(0x7ffd533f), X(0x7ffd5ec5), X(0x7ffd6a27), X(0x7ffd7563), + X(0x7ffd807a), X(0x7ffd8b6e), X(0x7ffd963d), X(0x7ffda0e8), + X(0x7ffdab70), X(0x7ffdb5d5), X(0x7ffdc017), X(0x7ffdca36), + X(0x7ffdd434), X(0x7ffdde0f), X(0x7ffde7c9), X(0x7ffdf161), + X(0x7ffdfad8), X(0x7ffe042f), X(0x7ffe0d65), X(0x7ffe167b), + X(0x7ffe1f71), X(0x7ffe2848), X(0x7ffe30ff), X(0x7ffe3997), + X(0x7ffe4211), X(0x7ffe4a6c), X(0x7ffe52a9), X(0x7ffe5ac8), + X(0x7ffe62c9), X(0x7ffe6aae), X(0x7ffe7275), X(0x7ffe7a1f), + X(0x7ffe81ad), X(0x7ffe891f), X(0x7ffe9075), X(0x7ffe97b0), + X(0x7ffe9ece), X(0x7ffea5d2), X(0x7ffeacbb), X(0x7ffeb38a), + X(0x7ffeba3e), X(0x7ffec0d8), X(0x7ffec758), X(0x7ffecdbf), + X(0x7ffed40d), X(0x7ffeda41), X(0x7ffee05d), X(0x7ffee660), + X(0x7ffeec4b), X(0x7ffef21f), X(0x7ffef7da), X(0x7ffefd7e), + X(0x7fff030b), X(0x7fff0881), X(0x7fff0de0), X(0x7fff1328), + X(0x7fff185b), X(0x7fff1d77), X(0x7fff227e), X(0x7fff276f), + X(0x7fff2c4b), X(0x7fff3112), X(0x7fff35c4), X(0x7fff3a62), + X(0x7fff3eeb), X(0x7fff4360), X(0x7fff47c2), X(0x7fff4c0f), + X(0x7fff504a), X(0x7fff5471), X(0x7fff5885), X(0x7fff5c87), + X(0x7fff6076), X(0x7fff6452), X(0x7fff681d), X(0x7fff6bd6), + X(0x7fff6f7d), X(0x7fff7313), X(0x7fff7698), X(0x7fff7a0c), + X(0x7fff7d6f), X(0x7fff80c2), X(0x7fff8404), X(0x7fff8736), + X(0x7fff8a58), X(0x7fff8d6b), X(0x7fff906e), X(0x7fff9362), + X(0x7fff9646), X(0x7fff991c), X(0x7fff9be3), X(0x7fff9e9c), + X(0x7fffa146), X(0x7fffa3e2), X(0x7fffa671), X(0x7fffa8f1), + X(0x7fffab65), X(0x7fffadca), X(0x7fffb023), X(0x7fffb26f), + X(0x7fffb4ae), X(0x7fffb6e0), X(0x7fffb906), X(0x7fffbb20), + X(0x7fffbd2e), X(0x7fffbf30), X(0x7fffc126), X(0x7fffc311), + X(0x7fffc4f1), X(0x7fffc6c5), X(0x7fffc88f), X(0x7fffca4d), + X(0x7fffcc01), X(0x7fffcdab), X(0x7fffcf4a), X(0x7fffd0e0), + X(0x7fffd26b), X(0x7fffd3ec), X(0x7fffd564), X(0x7fffd6d2), + X(0x7fffd838), X(0x7fffd993), X(0x7fffdae6), X(0x7fffdc31), + X(0x7fffdd72), X(0x7fffdeab), X(0x7fffdfdb), X(0x7fffe104), + X(0x7fffe224), X(0x7fffe33c), X(0x7fffe44d), X(0x7fffe556), + X(0x7fffe657), X(0x7fffe751), X(0x7fffe844), X(0x7fffe930), + X(0x7fffea15), X(0x7fffeaf3), X(0x7fffebca), X(0x7fffec9b), + X(0x7fffed66), X(0x7fffee2a), X(0x7fffeee8), X(0x7fffefa0), + X(0x7ffff053), X(0x7ffff0ff), X(0x7ffff1a6), X(0x7ffff247), + X(0x7ffff2e4), X(0x7ffff37a), X(0x7ffff40c), X(0x7ffff499), + X(0x7ffff520), X(0x7ffff5a3), X(0x7ffff621), X(0x7ffff69b), + X(0x7ffff710), X(0x7ffff781), X(0x7ffff7ee), X(0x7ffff857), + X(0x7ffff8bb), X(0x7ffff91c), X(0x7ffff979), X(0x7ffff9d2), + X(0x7ffffa27), X(0x7ffffa79), X(0x7ffffac8), X(0x7ffffb13), + X(0x7ffffb5b), X(0x7ffffba0), X(0x7ffffbe2), X(0x7ffffc21), + X(0x7ffffc5d), X(0x7ffffc96), X(0x7ffffccd), X(0x7ffffd01), + X(0x7ffffd32), X(0x7ffffd61), X(0x7ffffd8e), X(0x7ffffdb8), + X(0x7ffffde0), X(0x7ffffe07), X(0x7ffffe2b), X(0x7ffffe4d), + X(0x7ffffe6d), X(0x7ffffe8b), X(0x7ffffea8), X(0x7ffffec3), + X(0x7ffffedc), X(0x7ffffef4), X(0x7fffff0a), X(0x7fffff1f), + X(0x7fffff33), X(0x7fffff45), X(0x7fffff56), X(0x7fffff66), + X(0x7fffff75), X(0x7fffff82), X(0x7fffff8f), X(0x7fffff9a), + X(0x7fffffa5), X(0x7fffffaf), X(0x7fffffb8), X(0x7fffffc0), + X(0x7fffffc8), X(0x7fffffce), X(0x7fffffd5), X(0x7fffffda), + X(0x7fffffdf), X(0x7fffffe4), X(0x7fffffe8), X(0x7fffffeb), + X(0x7fffffef), X(0x7ffffff1), X(0x7ffffff4), X(0x7ffffff6), + X(0x7ffffff8), X(0x7ffffff9), X(0x7ffffffb), X(0x7ffffffc), + X(0x7ffffffd), X(0x7ffffffd), X(0x7ffffffe), X(0x7fffffff), + X(0x7fffffff), X(0x7fffffff), X(0x7fffffff), X(0x7fffffff), + X(0x7fffffff), X(0x7fffffff), X(0x7fffffff), X(0x7fffffff), + X(0x7fffffff), X(0x7fffffff), X(0x7fffffff), X(0x7fffffff), +}; + diff --git a/sdcard/3ds/ctruLua/config/keyboard.cfg b/sdcard/3ds/ctruLua/config/keyboard.cfg new file mode 100644 index 0000000..fda1efe --- /dev/null +++ b/sdcard/3ds/ctruLua/config/keyboard.cfg @@ -0,0 +1,40 @@ +keyWidth, keyHeight = 25, 25 + +layout = { + ["default"] = { + { "&", "é", "\"", "'", "(", "-", "è", "_", "ç", "à", ")", "=", "Bks" }, + { "a", "z", "e", "r", "t", "y", "u", "i", "o", "p", "^", "$", "Ent" }, + { "q", "s", "d", "f", "g", "h", "j", "k", "l", "m", "ù", "*", "Ent" }, + { "Shift", "<", "w", "x", "c", "v", "b", "n", ",", ";", ":", "!", "Tab" }, + { "SLck", ">", "+", "/", " ", " ", " ", " ", " ", "{", "}", ".", "Sym" } + }, + ["Shift"] = { + { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "°", "+", "Bks" }, + { "A", "Z", "E", "R", "T", "Y", "U", "I", "O", "P", "¨", "£", "Ent" }, + { "Q", "S", "D", "F", "G", "H", "J", "K", "L", "M", "%", "µ", "Ent" }, + { "Shift", ">", "W", "X", "C", "V", "B", "N", "?", ".", "/", "§", "Tab" }, + { "SLck", "~", "#", "[", " ", " ", " ", " ", " ", "]", "|", "@", "Sym" } + }, + ["Sym"] = { + { "²", "~", "#", "{", "[", "|", "`", "\\", "^", "@", "]", "}", "Bks" }, + { "a", "z", "€", "r", "t", "y", "u", "i", "o", "p", "", "¤", "Ent" }, + { "q", "s", "d", "f", "g", "h", "j", "k", "l", "m", "", "", "Ent" }, + { "Shift", "", "w", "x", "c", "v", "b", "n", "", "", "", "", "Tab" }, + { "SLck", "", "", "", " ", " ", " ", " ", " ", "", "", "", "Sym" } + }, +} + +alias = { + ["Tab"] = "\t", + ["Ent"] = "\n", + ["Bks"] = "\b" +} + +sticky = { + ["SLck"] = "Shift" +} + +keys = { + ["l"] = "Shift", + ["r"] = "Shift" +} \ No newline at end of file diff --git a/sdcard/3ds/ctruLua/editor/color.lua b/sdcard/3ds/ctruLua/editor/color.lua index e29506a..ed32152 100644 --- a/sdcard/3ds/ctruLua/editor/color.lua +++ b/sdcard/3ds/ctruLua/editor/color.lua @@ -1,16 +1,18 @@ +local hex = require("ctr.gfx.color").hex + -- Colors based on the Monokai theme return { -- General - ["background"] = 0x272822FF, - ["cursor"] = 0xF8F8F0FF, - ["default"] = 0xF8F8F2FF, + ["background"] = hex(0x272822FF), + ["cursor"] = hex(0xF8F8F0FF), + ["default"] = hex(0xF8F8F2FF), -- Syntax - ["comment"] = 0x75715EFF, - ["string"] = 0xE6DB74FF, - ["constant.numeric"] = 0xAE81FFFF, - ["constant.language"] = 0xAE81FFFF, - ["keyword.control"] = 0xF92672FF, - ["keyword.operator"] = 0xF92672FF, - ["support.function"] = 0x66D9EFFF -} \ No newline at end of file + ["comment"] = hex(0x75715EFF), + ["string"] = hex(0xE6DB74FF), + ["constant.numeric"] = hex(0xAE81FFFF), + ["constant.language"] = hex(0xAE81FFFF), + ["keyword.control"] = hex(0xF92672FF), + ["keyword.operator"] = hex(0xF92672FF), + ["support.function"] = hex(0x66D9EFFF) +} diff --git a/sdcard/3ds/ctruLua/editor/main.lua b/sdcard/3ds/ctruLua/editor/main.lua index ec14bad..e247583 100644 --- a/sdcard/3ds/ctruLua/editor/main.lua +++ b/sdcard/3ds/ctruLua/editor/main.lua @@ -3,20 +3,24 @@ local hid = require("ctr.hid") local gfx = require("ctr.gfx") -- Open libs -local keyboard = dofile("sdmc:/3ds/ctruLua/keyboard.lua") -local openfile = dofile("sdmc:/3ds/ctruLua/openfile.lua") +local keyboard = require("keyboard") +local filepicker = require("filepicker") local color = dofile("color.lua") local syntax = dofile("syntax.lua") -- Load data -local font = gfx.font.load("VeraMono.ttf") +local font = gfx.font.load(ctr.root .. "resources/VeraMono.ttf") -- Open file -local path, status = openfile("Choose a file to edit", "/3ds/ctruLua/", nil, "any") -if not path then return end +local path, binding, mode, key = filepicker(nil, {__default = { + a = {filepicker.openFile, "Open"}, + y = {filepicker.newFile, "New File"} + } +}) +if not mode then return end local lineEnding local lines = {} -if status == "exist" then +if mode == "open" then for line in io.lines(path, "L") do if not lineEnding then lineEnding = line:match("([\n\r]+)$") end table.insert(lines, line:match("^(.-)[\n\r]*$")) @@ -31,26 +35,79 @@ local coloredLines = syntax(lines, color) -- Variables local lineHeight = 10 +local fontSize = 9 local cursorX, cursorY = 1, 1 local scrollX, scrollY = 0, 0 +local fileModified = false -- Helper functions local function displayedText(text) - return text:gsub("\t", " ") + return text:gsub("\t", " "), nil +end +local function drawTop(eye) + -- Depth multiplicator. Multiply by a positive and add to x to add depth; multiply by a negative and add to x to go out of the screen. + local function d(mul) return math.floor(mul * hid.pos3d() * eye) end + + -- Lines + local sI = math.floor(scrollY / lineHeight) + if sI < 1 then sI = 1 end + + local eI = math.ceil((scrollY + gfx.TOP_HEIGHT) / lineHeight) + if eI > #lines then eI = #lines end + + for i = sI, eI, 1 do + local x = -scrollX + local y = -scrollY+ (i-1)*lineHeight + + for _,colored in ipairs(coloredLines[i]) do + local str = displayedText(colored[1]) + gfx.text(x + d(#(lines[i]:match("^%s+") or "")*3), y, str, fontSize, colored[2]) + x = x + font:width(str) + end + end + + -- Cursor + local curline = lines[cursorY] + gfx.rectangle(-scrollX+ font:width(displayedText(curline:sub(1, (utf8.offset(curline, cursorX) or 0)-1))) + d(#(curline:match("^%s+") or "")*3), + -scrollY+ (cursorY-1)*lineHeight, 1, lineHeight, 0, color.cursor) end -- Set defaults -gfx.set3D(false) +gfx.set3D(true) gfx.color.setDefault(color.default) gfx.color.setBackground(color.background) gfx.font.setDefault(font) +gfx.font.setSize(fontSize) while ctr.run() do hid.read() local keys = hid.keys() -- Keys input - if keys.down.start then return end + if keys.down.start then + local exit = not fileModified + if fileModified then + while ctr.run() do + hid.read() + local keys = hid.keys() + if keys.down.b then + exit = false + break + elseif keys.down.a then + exit = true + break + end + gfx.start(gfx.TOP) + gfx.text(3, 3, "The file was modified but not saved!") + gfx.text(3, 3 + lineHeight, "Are you sure you want to exit without saving?") + gfx.text(3, 3 + lineHeight*2, "Press A to exit and discard the modified file") + gfx.text(3, 3 + lineHeight*3, "Press B to return to the editor") + gfx.stop() + gfx.render() + end + end + if exit then break end + end if keys.down.dRight then cursorX = cursorX + 1 @@ -86,31 +143,32 @@ while ctr.run() do if not file then local t = os.time() repeat - gfx.startFrame(gfx.GFX_TOP) + gfx.start(gfx.TOP) gfx.text(3, 3, "Can't open file in write mode") - gfx.endFrame() + gfx.stop() gfx.render() until t + 5 < os.time() else for i = 1, #lines, 1 do file:write(lines[i]..lineEnding) - gfx.startFrame(gfx.GFX_TOP) - gfx.rectangle(0, 0, math.ceil(i/#lines*gfx.TOP_WIDTH), gfx.TOP_HEIGHT, 0, 0xFFFFFFFF) - gfx.color.setDefault(color.background) - gfx.text(gfx.TOP_WIDTH/2, gfx.TOP_HEIGHT/2, math.ceil(i/#lines*100).."%") - gfx.color.setDefault(color.default) - gfx.endFrame() + gfx.start(gfx.TOP) + gfx.rectangle(0, 0, math.ceil(i/#lines*gfx.TOP_WIDTH), gfx.TOP_HEIGHT, 0, 0xFFFFFFFF) + gfx.color.setDefault(color.background) + gfx.text(gfx.TOP_WIDTH/2, gfx.TOP_HEIGHT/2, math.ceil(i/#lines*100).."%") + gfx.color.setDefault(color.default) + gfx.stop() gfx.render() end file:flush() file:close() + fileModified = false end end -- Keyboard input local input = keyboard.read() if input then - if input == "BACK" then + if input == "\b" then if cursorX > utf8.len(lines[cursorY])+1 then cursorX = utf8.len(lines[cursorY])+1 end if cursorX > 1 then lines[cursorY] = lines[cursorY]:sub(1, utf8.offset(lines[cursorY], cursorX-1)-1).. @@ -120,64 +178,56 @@ while ctr.run() do cursorX, cursorY = utf8.len(lines[cursorY-1])+1, cursorY - 1 lines[cursorY] = lines[cursorY]..lines[cursorY+1] table.remove(lines, cursorY+1) + table.remove(coloredLines, cursorY+1) end + + coloredLines[cursorY] = syntax(lines[cursorY], color) + elseif input == "\n" then local newline = lines[cursorY]:sub(utf8.offset(lines[cursorY], cursorX), -1) local whitespace = lines[cursorY]:match("^%s+") if whitespace then newline = whitespace .. newline end lines[cursorY] = lines[cursorY]:sub(1, utf8.offset(lines[cursorY], cursorX)-1) + coloredLines[cursorY] = syntax(lines[cursorY], color) table.insert(lines, cursorY + 1, newline) + table.insert(coloredLines, cursorY + 1, syntax(newline, color)) cursorX, cursorY = whitespace and #whitespace+1 or 1, cursorY + 1 + else lines[cursorY] = lines[cursorY]:sub(1, utf8.offset(lines[cursorY], cursorX)-1)..input.. lines[cursorY]:sub(utf8.offset(lines[cursorY], cursorX), -1) + coloredLines[cursorY] = syntax(lines[cursorY], color) cursorX = cursorX + 1 end + fileModified = true end -- Draw - gfx.startFrame(gfx.GFX_TOP) + local is3D = hid.pos3d() > 0 - -- Lines - local sI = math.floor(scrollY / lineHeight) - if sI < 1 then sI = 1 end - - local eI = math.ceil((scrollY + gfx.TOP_HEIGHT) / lineHeight) - if eI > #lines then eI = #lines end - - for i = sI, eI, 1 do - local x = -scrollX - local y = -scrollY+ (i-1)*lineHeight + gfx.start(gfx.TOP, gfx.LEFT) + drawTop(is3D and 0 or -1) + gfx.stop() - for _,colored in ipairs(coloredLines[i]) do - local str = displayedText(colored[1]) - - gfx.color.setDefault(colored[2]) - gfx.text(x, y, str) - gfx.color.setDefault(color.default) - - x = x + font:width(str) - end - end - - -- Cursor - local curline = lines[cursorY] - gfx.rectangle(-scrollX+ font:width(displayedText(curline:sub(1, (utf8.offset(curline, cursorX) or 0)-1))), - -scrollY+ (cursorY-1)*lineHeight, 1, lineHeight, 0, color.cursor) - - gfx.endFrame() + if is3D then + gfx.start(gfx.TOP, gfx.RIGHT) + drawTop(1) + gfx.stop() + end - gfx.startFrame(gfx.GFX_BOTTOM) + gfx.start(gfx.BOTTOM) gfx.text(3, 3, "FPS: "..math.ceil(gfx.getFPS())) + gfx.text(3, 3 + lineHeight, "Press select to save.") + gfx.text(3, 3 + lineHeight*2, "Press start to exit.") - keyboard.draw(5, 115) + keyboard.draw(4, 115) - gfx.endFrame() + gfx.stop() gfx.render() end -font:unload() \ No newline at end of file +font:unload() diff --git a/sdcard/3ds/ctruLua/editor/syntax.lua b/sdcard/3ds/ctruLua/editor/syntax.lua index bebe3f5..c6845af 100644 --- a/sdcard/3ds/ctruLua/editor/syntax.lua +++ b/sdcard/3ds/ctruLua/editor/syntax.lua @@ -50,7 +50,7 @@ local syntax = { return function(lines, color) local ret = {} - for _,line in ipairs(lines) do + for _, line in ipairs(type(lines) == "table" and lines or {lines}) do local colored = { { line, color.default } } for _, patterns in ipairs(syntax) do @@ -86,5 +86,5 @@ return function(lines, color) table.insert(ret, colored) end - return ret -end \ No newline at end of file + return type(lines) == "table" and ret or ret[1] +end diff --git a/sdcard/3ds/ctruLua/examples/audio/audio.lua b/sdcard/3ds/ctruLua/examples/audio/audio.lua new file mode 100644 index 0000000..34dead2 --- /dev/null +++ b/sdcard/3ds/ctruLua/examples/audio/audio.lua @@ -0,0 +1,54 @@ +local ctr = require("ctr") +local hid = require("ctr.hid") +local gfx = require("ctr.gfx") +local audio = require("ctr.audio") + +local test = assert(audio.load("test.wav")) -- Load audio file + +local channel = -1 +local speed = 1 +local leftBalance = 0.5 + +while true do + hid.read() + local keys = hid.keys() + if keys.down.start then break end + + if keys.down.a then + channel = test:play() -- Play audio (an audio can be played multiple times at the same time) + end + + if keys.down.up then + speed = speed + 0.01 + test:speed(speed) -- Set the audio object default speed, will affect the next time it is played + audio.speed(nil, speed) -- Set the speed of all the currently playing channels + end + if keys.down.down then + speed = speed - 0.01 + test:speed(speed) -- See above + audio.speed(nil, speed) + end + + if keys.down.left then + leftBalance = leftBalance + 0.1 + test:mix(1-leftBalance, leftBalance) -- Set the audio mix: left speaker will be at leftBalance% and right speaker 1-leftBalance%. + -- Like with test:speed(), it won't affect the currently playing audios but the nexts test:play() will have theses mix paramters. + audio.mix(nil, leftBalance, 1-leftBalance) -- Set the mix of all currently playing channels + end + if keys.down.right then + leftBalance = leftBalance - 0.1 + test:mix(1-leftBalance, leftBalance) -- See above + audio.mix(nil, leftBalance, 1-leftBalance) + end + + gfx.start(gfx.TOP) + gfx.text(5, 5, "Audio test! "..tostring(test:time()).."/"..tostring(test:duration()).."s") + gfx.text(5, 25, "Last audio played on channel "..tostring(channel)) + gfx.text(5, 65, "Speed: "..(speed*100).."% - Left balance: "..(leftBalance*100).."%") + gfx.stop() + + audio.update() + gfx.render() +end + +test:unload() -- Unload audio file \ No newline at end of file diff --git a/sdcard/3ds/ctruLua/examples/audio/test.wav b/sdcard/3ds/ctruLua/examples/audio/test.wav new file mode 100644 index 0000000..3a71ee6 Binary files /dev/null and b/sdcard/3ds/ctruLua/examples/audio/test.wav differ diff --git a/sdcard/3ds/ctruLua/examples/cfgu/cfgu.lua b/sdcard/3ds/ctruLua/examples/cfgu/cfgu.lua new file mode 100644 index 0000000..3ca851a --- /dev/null +++ b/sdcard/3ds/ctruLua/examples/cfgu/cfgu.lua @@ -0,0 +1,57 @@ +local ctr = require("ctr") +local gfx = require("ctr.gfx") +local hid = require("ctr.hid") +local cfgu = require("ctr.cfgu") + +local regions = { + [cfgu.REGION_JPN] = "Japan", + [cfgu.REGION_USA] = "America", + [cfgu.REGION_EUR] = "Europe", + [cfgu.REGION_AUS] = "Australia", + [cfgu.REGION_CHN] = "China", + [cfgu.REGION_KOR] = "Korea", + [cfgu.REGION_TWN] = "Taiwan" +} + +local languages = { + [cfgu.LANGUAGE_JP] = "Japanese", + [cfgu.LANGUAGE_EN] = "English", + [cfgu.LANGUAGE_FR] = "French", + [cfgu.LANGUAGE_DE] = "Deutch", + [cfgu.LANGUAGE_IT] = "Italian", + [cfgu.LANGUAGE_ES] = "Spanish", + [cfgu.LANGUAGE_ZH] = "Chinese", + [cfgu.LANGUAGE_KO] = "Korean", + [cfgu.LANGUAGE_NL] = "Dutch", + [cfgu.LANGUAGE_PT] = "Portuguese", + [cfgu.LANGUAGE_RU] = "Russian", + [cfgu.LANGUAGE_TW] = "Taiwanese" +} + +local models = { + [cfgu.MODEL_3DS] = "3DS", + [cfgu.MODEL_3DSXL] = "3DS XL", + [cfgu.MODEL_N3DS] = "New 3DS", + [cfgu.MODEL_2DS] = "2DS", + [cfgu.MODEL_N3DSXL] = "New 3DS XL" +} + +cfgu.init() +while ctr.run() do + hid.read() + keys = hid.keys() + if keys.down.start then break end + + gfx.start(gfx.BOTTOM) + gfx.text(2, 2, "CFGU example") + gfx.text(2, 20, "Region: "..regions[cfgu.getRegion()]) + gfx.text(2, 30, "Model: "..models[cfgu.getModel()]) + gfx.text(2, 40, "Language: "..languages[cfgu.getLanguage()]) + gfx.text(2, 50, "Username: "..cfgu.getUsername()) + local m,d = cfgu.getBirthday() + gfx.text(2, 60, "Birthday: "..d.."/"..m) + gfx.text(2, 70, "0 Hash: "..cfgu.genHash(0)) + gfx.stop() + + gfx.render() +end diff --git a/sdcard/3ds/ctruLua/examples/example.lua b/sdcard/3ds/ctruLua/examples/example.lua index 13298ce..67ed406 100644 --- a/sdcard/3ds/ctruLua/examples/example.lua +++ b/sdcard/3ds/ctruLua/examples/example.lua @@ -8,8 +8,9 @@ local dMul = 1 local angle = 0 -local texture1 = gfx.texture.load("sdmc:/3ds/ctruLua/icon.png"); +local texture1 = gfx.texture.load(ctr.root.."icon.png"); if not texture1 then error("Giants ducks came from another planet") end +local tWidth, tHeight = texture1:getSize() gfx.color.setBackground(gfx.color.RGBA8(200, 200, 200)) gfx.set3D(true) @@ -21,7 +22,7 @@ local function drawStuffIn3D(eye) -- 3D stuff local function d(depth) return math.ceil(eye * depth * dMul) end - gfx.color.setDefault(0x00FFFFFF) + gfx.color.setDefault(0xFFFFFF00) gfx.rectangle(240 + d(10), 150, 120, 10) gfx.point(10 + d(6), 20, 0xFF0000FF) @@ -29,7 +30,7 @@ local function drawStuffIn3D(eye) gfx.color.setDefault(0xFF0000FF) gfx.rectangle(x + d(10*math.sin(ctr.time()/500)), y, 20, 20, angle) - gfx.line(50 + d(-6), 50, 75 + d(4), 96, gfx.color.RGBA8(52, 10, 65)) + gfx.line(50 + d(-6), 50, 75 + d(4), 96, 1, gfx.color.RGBA8(52, 10, 65)) gfx.circle(125 + d(-8), 125, 16) end @@ -47,32 +48,32 @@ while ctr.run() do dMul = hid.pos3d() - gfx.startFrame(gfx.GFX_TOP, gfx.GFX_LEFT) + gfx.start(gfx.TOP, gfx.LEFT) drawStuffIn3D(-1) - gfx.endFrame() + gfx.stop() - gfx.startFrame(gfx.GFX_TOP, gfx.GFX_RIGHT) + gfx.start(gfx.TOP, gfx.RIGHT) drawStuffIn3D(1) - gfx.endFrame() + gfx.stop() - gfx.startFrame(gfx.GFX_BOTTOM) + gfx.start(gfx.BOTTOM) gfx.color.setDefault(gfx.color.RGBA8(0, 0, 0)) gfx.text(5, 5, "FPS: "..math.ceil(gfx.getFPS())) gfx.text(5, 17, "Hello world, from Lua ! éàçù", 20, gfx.color.RGBA8(0, 0, 0)) gfx.text(5, 50, "Time: "..os.date()) - texture1:draw(280, 80, angle); + texture1:draw(280, 80, angle, tWidth/2, tHeight/2); local cx, cy = hid.circle() gfx.rectangle(40, 90, 60, 60, 0, 0xDDDDDDFF) - gfx.circle(70 + math.ceil(cx/156 * 30), 120 - math.ceil(cy/156 * 30), 10, 0x000000FF) + gfx.circle(70 + math.ceil(cx/156 * 30), 120 - math.ceil(cy/156 * 30), 10, 0xFF000000) - gfx.endFrame() + gfx.stop() angle = angle + 0.05 if angle > 2*math.pi then angle = angle - 2*math.pi end diff --git a/sdcard/3ds/ctruLua/tests/httpc.lua b/sdcard/3ds/ctruLua/examples/httpc/httpc.lua similarity index 55% rename from sdcard/3ds/ctruLua/tests/httpc.lua rename to sdcard/3ds/ctruLua/examples/httpc/httpc.lua index f7d707b..2f45f22 100644 --- a/sdcard/3ds/ctruLua/tests/httpc.lua +++ b/sdcard/3ds/ctruLua/examples/httpc/httpc.lua @@ -4,12 +4,12 @@ local hid = require("ctr.hid") local httpc = require("ctr.httpc") local err = 0 - ---assert(httpc.init()) +local addr = "https://wtfismyip.com/text" +local dls = 0 local context = assert(httpc.context()) -assert(context:open("http://firew0lf.github.io/")) +assert(context:open(addr)) assert(context:beginRequest()) local data = assert(context:downloadData()) @@ -19,19 +19,24 @@ while ctr.run() do keys = hid.keys() if keys.held.start then break end if keys.down.b then - assert(context:open("http://firew0lf.github.io/")) + assert(context:open(addr)) assert(context:beginRequest()) data = assert(context:downloadData()) - data = (data.."!") + dls = dls + 1 end - gfx.startFrame(gfx.GFX_TOP) + gfx.start(gfx.TOP) gfx.text(0, 0, data) - gfx.endFrame() + gfx.text(0, 20, "Downloaded "..dls.." times.") + gfx.stop() + + gfx.start(gfx.BOTTOM) + gfx.text(2, 2, "HTTP Contexts example") + gfx.text(2, 20, "The data is downloaded from '"..addr.."'.") + gfx.text(2, 30, "Press [B] to redownload.") + gfx.stop() gfx.render() end - context:close() ---httpc.shutdown() diff --git a/sdcard/3ds/ctruLua/examples/map/map.csv b/sdcard/3ds/ctruLua/examples/map/map.csv new file mode 100644 index 0000000..6035e4c --- /dev/null +++ b/sdcard/3ds/ctruLua/examples/map/map.csv @@ -0,0 +1,6 @@ +0,0,0,0,0,0 +0,1,1,1,1,0 +0,1,3,2,1,0 +0,1,2,3,1,0 +0,1,1,1,1,0 +0,0,0,0,0,0 diff --git a/sdcard/3ds/ctruLua/examples/map/map.lua b/sdcard/3ds/ctruLua/examples/map/map.lua new file mode 100644 index 0000000..835c6d6 --- /dev/null +++ b/sdcard/3ds/ctruLua/examples/map/map.lua @@ -0,0 +1,49 @@ +local ctr = require("ctr") +local gfx = require("ctr.gfx") +local map = require("ctr.gfx.map") +local texture = require("ctr.gfx.texture") +local hid = require("ctr.hid") + +local tileset = assert(texture.load("tileset.png")) +local map = assert(map.load("map.csv", tileset, 16, 16)) + +local x,y = 0,0 +local s = 0 + +while ctr.run() do + hid.read() + local keys = hid.keys() + if keys.down.start then break end + if keys.held.up then + y = y - 1 + elseif keys.held.down then + y = y + 1 + end + if keys.held.left then + x = x - 1 + elseif keys.held.right then + x = x + 1 + end + if keys.held.r then + s = s + 1 + map:setSpace(s,s) + elseif keys.held.l then + s = s - 1 + map:setSpace(s,s) + end + + gfx.start(gfx.TOP) + map:draw(x,y) + gfx.stop() + + gfx.start(gfx.BOTTOM) + gfx.text(2, 2, "Map example") + gfx.text(2, 20, "Press L (-) and R (+) to change the space between the tiles") + gfx.text(2, 30, "Move the map with the D-pad or the C-pad") + gfx.stop() + + gfx.render() +end + +map:unload() +tileset:unload() diff --git a/sdcard/3ds/ctruLua/examples/map/tileset.png b/sdcard/3ds/ctruLua/examples/map/tileset.png new file mode 100644 index 0000000..65c40e5 Binary files /dev/null and b/sdcard/3ds/ctruLua/examples/map/tileset.png differ diff --git a/sdcard/3ds/ctruLua/examples/ptm/ptm.lua b/sdcard/3ds/ctruLua/examples/ptm/ptm.lua new file mode 100644 index 0000000..4420c3c --- /dev/null +++ b/sdcard/3ds/ctruLua/examples/ptm/ptm.lua @@ -0,0 +1,21 @@ +local ctr = require("ctr") +local gfx = require("ctr.gfx") +local hid = require("ctr.hid") +local ptm = require("ctr.ptm") + +while ctr.run() do + hid.read() + local keys = hid.keys() + if keys.down.start then break end + + gfx.start(gfx.TOP) + gfx.text(2, 2, "PTM example") + local level = ptm.getBatteryLevel() + gfx.text(2, 20, "Battery level: ["..string.rep("|", level)..string.rep(" ", 5-level).."]") + gfx.text(2, 30, "Charging: "..((ptm.getBatteryChargeState() and "Yes") or "No")) + gfx.text(2, 40, "You walked: "..ptm.getTotalStepCount().." steps") + gfx.text(2, 50, "Counting: "..((ptm.getPedometerState() and "Yes") or "No")) + gfx.stop() + + gfx.render() +end diff --git a/sdcard/3ds/ctruLua/examples/qtm/qtm.lua b/sdcard/3ds/ctruLua/examples/qtm/qtm.lua new file mode 100644 index 0000000..f4948ff --- /dev/null +++ b/sdcard/3ds/ctruLua/examples/qtm/qtm.lua @@ -0,0 +1,48 @@ +local ctr = require("ctr") +local hid = require("ctr.hid") +local gfx = require("ctr.gfx") +local qtm = require("ctr.qtm") + +qtm.init() + +if not qtm.checkInitialized() then + while ctr.run() do + hid.read() + if hid.keys().down.start then + break + end + gfx.start(gfx.TOP) + gfx.text(2, 2, "Couldn't initialize the QTM module.") + gfx.text(2, 12, "You need a New 3DS in order to use this.") + gfx.stop() + gfx.render() + end + return +end + +while ctr.run() do + hid.read() + local keys = hid.keys() + if keys.down.start then break end + + local infos = qtm.getHeadtrackingInfo() + + gfx.start(gfx.TOP) + if infos:checkHeadFullyDetected() then + for i=1, 4 do + gfx.point(infos:convertCoordToScreen(i, 400, 240)) + end + end + gfx.stop() + + gfx.start(gfx.BOTTOM) + gfx.text(0, 0, "QTM example") + for i=1, 4 do + local x,y = infos[i] + gfx.text(0, 10*i, i..": "..x..";"..y) + end + gfx.stop() + + gfx.render() +end + diff --git a/sdcard/3ds/ctruLua/keyboard.lua b/sdcard/3ds/ctruLua/keyboard.lua deleted file mode 100644 index e97b9c5..0000000 --- a/sdcard/3ds/ctruLua/keyboard.lua +++ /dev/null @@ -1,106 +0,0 @@ -local hid = require("ctr.hid") -local gfx = require("ctr.gfx") - --- Options -local keyWidth, keyHeight = 25, 25 -local layout = { - ["default"] = { - { "&", "é", "\"", "'", "(", "-", "è", "_", "ç", "à", ")", "=", "Back" }, - { "a", "z", "e", "r", "t", "y", "u", "i", "o", "p", "^", "$", "Enter" }, - { "q", "s", "d", "f", "g", "h", "j", "k", "l", "m", "ù", "*", "Enter" }, - { "Shift", "<", "w", "x", "c", "v", "b", "n", ",", ";", ":", "!", "Tab" }, - { "CpLck", ">", "+", "/", " ", " ", " ", " ", " ", "{", "}", ".", "AltGr" } - }, - ["Shift"] = { - { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "°", "+", "Back" }, - { "A", "Z", "E", "R", "T", "Y", "U", "I", "O", "P", "¨", "£", "Enter" }, - { "Q", "S", "D", "F", "G", "H", "J", "K", "L", "M", "%", "µ", "Enter" }, - { "Shift", ">", "W", "X", "C", "V", "B", "N", "?", ".", "/", "§", "Tab" }, - { "CpLck", "~", "#", "[", " ", " ", " ", " ", " ", "]", "|", "@", "AltGr" } - }, - ["AltGr"] = { - { "²", "~", "#", "{", "[", "|", "`", "\\", "^", "@", "]", "}", "Back" }, - { "a", "z", "€", "r", "t", "y", "u", "i", "o", "p", "", "¤", "Enter" }, - { "q", "s", "d", "f", "g", "h", "j", "k", "l", "m", "", "", "Enter" }, - { "Shift", "", "w", "x", "c", "v", "b", "n", "", "", "", "", "Tab" }, - { "CpLck", "", "", "", " ", " ", " ", " ", " ", "", "", "", "AltGr" } - }, -} -local alias = { - ["Tab"] = "\t", - ["Enter"] = "\n", - ["Back"] = "BACK" -} -local sticky = { - ["CpLck"] = "Shift" -} -local keys = { - ["l"] = "Shift", - ["r"] = "Shift" -} - --- Variables -local currentModifier = { "default", "sticky" } -local buffer = "" - -return { - draw = function(x, y) - local hidKeys = hid.keys() - - local xTouch, yTouch - if hidKeys.down.touch then xTouch, yTouch = hid.touch() end - - for key, modifier in pairs(keys) do - if hidKeys.down[key] then - currentModifier = { modifier, "key" } - elseif hidKeys.up[key] and currentModifier[2] == "key" and currentModifier[1] == modifier then - currentModifier = { "default", "sticky" } - end - end - - for row, rowKeys in pairs(layout[currentModifier[1]]) do - for column, key in pairs(rowKeys) do - local xKey, yKey = x + (column-1)*(keyWidth-1), y + (row-1)*(keyHeight-1) - - gfx.rectangle(xKey, yKey, keyWidth, keyHeight, 0, 0xFFFFFFFF) - gfx.rectangle(xKey + 1, yKey + 1, keyWidth - 2, keyHeight - 2, 0, 0x000000FF) - gfx.text(xKey + 2, yKey + 2, key) - - if xTouch then - if xTouch > xKey and xTouch < xKey + keyWidth then - if yTouch > yKey and yTouch < yKey + keyHeight then - gfx.rectangle(xKey, yKey, keyWidth, keyHeight, 0, 0xFFFFFFDD) - - local k = alias[key] or key - if sticky[k] and layout[sticky[k]] then - if currentModifier[1] == sticky[k] and currentModifier[2] == "sticky" then - currentModifier = { "default", "sticky" } - else - currentModifier = { sticky[k], "sticky" } - end - elseif layout[k] then - if currentModifier[1] == k and currentModifier[2] == "normal" then - currentModifier = { "default", "sticky" } - else - currentModifier = { k, "normal" } - end - else - buffer = buffer .. k - if currentModifier[1] ~= "default" and currentModifier[2] == "normal" then - currentModifier = { "default", "sticky" } - end - end - end - end - end - end - end - end, - - read = function() - local ret = buffer - buffer = "" - - return ret ~= "" and ret or nil - end -} \ No newline at end of file diff --git a/sdcard/3ds/ctruLua/libs/filepicker.lua b/sdcard/3ds/ctruLua/libs/filepicker.lua new file mode 100644 index 0000000..da4760d --- /dev/null +++ b/sdcard/3ds/ctruLua/libs/filepicker.lua @@ -0,0 +1,318 @@ +local ctr = require('ctr') +local keyboard = require('keyboard') + +local gfx = ctr.gfx + +local externalConfig + +local function gfxPrepare() + local old = {gfx.get3D(), gfx.color.getDefault(), gfx.color.getBackground(), + gfx.font.getDefault(), gfx.font.getSize()} + + local mono = gfx.font.load(ctr.root .. "resources/VeraMono.ttf") + + gfx.set3D(false) + gfx.color.setDefault(0xFFFDFDFD) + gfx.color.setBackground(0xFF333333) + gfx.font.setDefault(mono) + gfx.font.setSize(12) + + return old +end + +local function gfxRestore(state) + gfx.set3D(state[1]) + gfx.color.setDefault(state[2]) + gfx.color.setBackground(state[3]) + gfx.font.setDefault(state[4]) + gfx.font.setSize(state[5]) +end + +local function systemBindings(bindings) + bindings.__default.up = { + function(_, selected, ...) + if selected.inList > 1 then + selected.inList = selected.inList - 1 + if selected.inList == selected.offset then + selected.offset = selected.offset - 1 + end + end + end + } + + bindings.__default.down = { + function(externalConfig, selected, ...) + if selected.inList < #externalConfig.fileList then + selected.inList = selected.inList + 1 + if selected.inList - selected.offset >= 16 then + selected.offset = selected.offset + 1 + end + end + end + } + + bindings.__default.left = { + function(_, selected, ...) + selected.inList, selected.offset = 1, 0 + end + } + + bindings.__default.right = { + function(externalConfig, selected, ...) + selected.inList = #externalConfig.fileList + if #externalConfig.fileList > 15 then + selected.offset = #externalConfig.fileList - 16 + end + end + } +end + +local function getFileList(workingDirectory) + local fileList = ctr.fs.list(workingDirectory) + + if workingDirectory ~= "/" and workingDirectory ~= "sdmc:/" then + table.insert(fileList, {name = "..", isDirectory = true}) + end + + -- Stealy stealing code from original openfile.lua + table.sort(fileList, function(i, j) + if i.isDirectory and not j.isDirectory then + return true + elseif i.isDirectory == j.isDirectory then + return string.lower(i.name) < string.lower(j.name) + end + end) + + return fileList +end + +local function getBinding(selectedFile, bindings) + if selectedFile.isDirectory then + return bindings.__directory, "__directory" + end + for pattern, values in pairs(bindings) do + if selectedFile.name:match(pattern) then + return values, pattern + end + end + return bindings.__default, "__default" +end + +local function drawBottom(externalConfig, workingDirectoryScroll, selected) + local workingDirectory = externalConfig.workingDirectory + local bindings = externalConfig.bindings + local selectedFile = externalConfig.fileList[selected.inList] + gfx.start(gfx.BOTTOM) + gfx.rectangle(0, 0, gfx.BOTTOM_WIDTH, 16, 0, 0xFF0000B3) + gfx.text(1 - workingDirectoryScroll.value, 0, workingDirectory) + if gfx.font.getDefault():width(workingDirectory) > gfx.BOTTOM_WIDTH - 2 then + workingDirectoryScroll.value = workingDirectoryScroll.value + workingDirectoryScroll.phase + if workingDirectoryScroll.value == (gfx.BOTTOM_WIDTH - 2) - gfx.font.getDefault():width(workingDirectory) or + workingDirectoryScroll.value == 0 then + workingDirectoryScroll.phase = - workingDirectoryScroll.phase + end + end + + gfx.text(1, 15, selectedFile.name, 12) + if not selectedFile.isDirectory then + gfx.text(1, 45, tostring(selectedFile.size) .. "B", 12, 0xFF727272) + end + + local binding, pattern = getBinding(selectedFile, bindings) + if selectedFile.isDirectory then + gfx.text(1, 30, bindings.__directory.__name, 12, 0xFF727272) + else + gfx.text(1, 30, binding.__name, 12, 0xFF727272) + end + + local bindingNames = { + {"start", "Start"}, {"select", "Select"}, + {"x", "X"}, {"y", "Y"}, + {"b", "B"}, {"a", "A"}, + {"r", "R"}, {"l", "L"}, + {"zr", "ZR"}, {"zl", "ZL"}, + {"cstickDown", "C Down"}, {"cstickUp", "C Up"}, + {"cstickRight", "C Right"}, {"cstickLeft", "C Left"} + } + + local j = 0 + + for i, v in ipairs(bindingNames) do + if binding[v[1]] and binding[v[1]][2] then + j = j + 1 + gfx.text(1, gfx.BOTTOM_HEIGHT - 15*j, v[2] .. ": " .. binding[v[1]][2]) + end + end + + externalConfig.callbacks.drawBottom(externalConfig, selected) + gfx.stop() +end + +local function drawTop(externalConfig, selected) + gfx.start(gfx.TOP) + gfx.rectangle(0, (selected.inList-selected.offset-1)*15, gfx.TOP_WIDTH, 16, 0, 0xFF0000B9) + local over = #externalConfig.fileList - selected.offset >= 16 and 16 or #externalConfig.fileList - selected.offset + for i=selected.offset+1, selected.offset+over do + local color = externalConfig.fileList[i].isDirectory and 0xFF727272 or 0xFFFDFDFD + gfx.text(1, (i-selected.offset-1)*15+1, externalConfig.fileList[i].name or "", 12, color) + end + externalConfig.callbacks.drawTop(externalConfig, selected) + gfx.stop() +end + +local function eventHandler(externalConfig, selected) + externalConfig.callbacks.eventHandler(externalConfig, selected) + ctr.hid.read() + local state = ctr.hid.keys() + local binding, pattern = getBinding(externalConfig.fileList[selected.inList], externalConfig.bindings) + for k, v in pairs(binding) do + if k ~= "__name" and state.down[k] then + local a, b, c, key = v[1](externalConfig, selected, pattern, k) + if key then return a, b, c, key + else return end + end + end + for k, v in pairs(externalConfig.bindings.__default) do + if k ~= "__name" and state.down[k] then + local a, b, c, key = v[1](externalConfig, selected, pattern, k) + if key then return a, b, c, key + else break end + end + end +end + +local function nothing(externalConfig, selected, bindingName, bindingKey) + -- externalConfig = {workingDirectory=string, bindings=table, callbacks=table, additionalArguments=table, fileList=table} + -- selected = {file=string, inList=number, offset=number} + -- bindings = {__default/__directory/[regex] = {__name, [keyName] = {(handlingFunction), (name)}}} + -- callbacks = {drawTop, drawBottom, eventHandler} +end + +local function changeDirectory(externalConfig, selected, bindingName, bindingKey) + if externalConfig.fileList[selected.inList].isDirectory then + if externalConfig.fileList[selected.inList].name == ".." then + externalConfig.workingDirectory = externalConfig.workingDirectory:gsub("[^/]+/$", "") + else + externalConfig.workingDirectory = externalConfig.workingDirectory .. externalConfig.fileList[selected.inList].name .. "/" + end + externalConfig.fileList = getFileList(externalConfig.workingDirectory) + selected.inList, selected.offset = 1, 0 + end +end + +local function newFile(externalConfig, selected, bindingName, bindingKey) + local name = "" + while ctr.run() do + gfx.start(gfx.BOTTOM) + gfx.rectangle(0, 0, gfx.BOTTOM_WIDTH, 16, 0, 0xFF0000B3) + gfx.text(1, 0, externalConfig.workingDirectory) + keyboard.draw(4, 115) + gfx.stop() + + gfx.start(gfx.TOP) + gfx.rectangle(0, 0, gfx.TOP_WIDTH, 16, 0, 0xFF0000B3) + gfx.text(1, 0, "Creating new file") + gfx.rectangle(4, gfx.TOP_HEIGHT // 2 - 15, gfx.TOP_WIDTH - 8, 30, 0, 0xFF727272) + gfx.text(5, gfx.TOP_HEIGHT // 2 - 6, name, 12) + gfx.stop() + gfx.render() + + local char = (keyboard.read() or ""):gsub("[\t%/%?%<%>%\\%:%*%|%”%^]", "") + ctr.hid.read() + local keys = ctr.hid.keys() + + if char ~= "" and char ~= "\b" and char ~= "\n" then + name = name .. char + elseif char ~= "" and char == "\b" then + name = name:sub(1, (utf8.offset(name, -1) or 0)-1) + elseif (char ~= "" and char == "\n" or keys.down.a) and name ~= "" then + local b, p = getBinding({name=name}, externalConfig.bindings) + return externalConfig.workingDirectory .. name, p, "new", b + elseif keys.down.b then + break + end + end +end + +local function openFile(externalConfig, selected, bindingName, bindingKey) + return externalConfig.workingDirectory .. externalConfig.fileList[selected.inList].name, + bindingName, "open", bindingKey +end + +local function filePicker(workingDirectory, bindings, callbacks, ...) + -- Argument sanitization + local additionalArguments = { ... } + workingDirectory = workingDirectory or ctr.fs.getDirectory() + bindings = bindings or {} + callbacks = callbacks or {} + for _, v in ipairs({"drawTop", "drawBottom", "eventHandler"}) do + if not callbacks[v] then + callbacks[v] = function(...) end + end + end + + if workingDirectory:sub(utf8.offset(workingDirectory, -1) or -1) ~= "/" then + workingDirectory = workingDirectory .. "/" + end + + -- Default Bindings + bindings.__default = bindings.__default or {} + bindings.__default.__name = bindings.__default.__name or "File" + bindings.__default.x = bindings.__default.x or { + function(externalConfig, ...) + return externalConfig.workingDirectory, "__directory", nil, "x" + end, "Quit" + } + + bindings.__directory = bindings.__directory or {} + bindings.__directory.__name = bindings.__directory.__name or "Directory" + bindings.__directory.a = bindings.__directory.a or { + changeDirectory, "Open" + } + + local movementKeys = { + "up" , "down" , "left" , "right" , + "cpadUp", "cpadDown", "cpadLeft", "cpadRight", + "dUp" , "dDown" , "dLeft" , "dRight" + } + + for k, v in pairs(bindings) do + if k ~= "__default" then + setmetatable(bindings[k], {__index = bindings.__default}) + end + + for _, w in ipairs(movementKeys) do + if v[w] then bindings[k][w] = nil end + end + end + + systemBindings(bindings) + + -- Other Initialization + local selected = {inList = 1, offset = 0} + local workingDirectoryScroll = { value = 0, phase = -1 } + local gfxState = gfxPrepare() + + -- Main Loop + externalConfig = {workingDirectory=workingDirectory, bindings=bindings, + callbacks=callbacks, additionalArguments=additionalArguments, + fileList=getFileList(workingDirectory)} + while ctr.run() do + drawBottom(externalConfig, workingDirectoryScroll, selected) + drawTop(externalConfig, selected) + gfx.render() + + local file, binding, mode, key = eventHandler(externalConfig, selected) + + if key then + gfxRestore(gfxState) + return file, binding, mode, key + end + end +end + +local returnTable = {filePicker = filePicker, openFile = openFile, + newFile = newFile, changeDirectory = changeDirectory} +setmetatable(returnTable, {__call = function(self, ...) return self.filePicker(...) end}) + +return returnTable \ No newline at end of file diff --git a/sdcard/3ds/ctruLua/libs/keyboard.lua b/sdcard/3ds/ctruLua/libs/keyboard.lua new file mode 100644 index 0000000..e220779 --- /dev/null +++ b/sdcard/3ds/ctruLua/libs/keyboard.lua @@ -0,0 +1,74 @@ +local ctr = require("ctr") +local hid = require("ctr.hid") +local gfx = require("ctr.gfx") +local hex = gfx.color.hex + +-- Options +local config = {} +loadfile(ctr.root .. "config/keyboard.cfg", nil, config)() + +-- Variables +local currentModifier = { "default", "sticky" } +local buffer = "" + +return { + draw = function(x, y) + local hidKeys = hid.keys() + + local xTouch, yTouch + if hidKeys.down.touch then xTouch, yTouch = hid.touch() end + + for key, modifier in pairs(config.keys) do + if hidKeys.down[key] then + currentModifier = { modifier, "key" } + elseif hidKeys.up[key] and currentModifier[2] == "key" and currentModifier[1] == modifier then + currentModifier = { "default", "sticky" } + end + end + + for row, rowKeys in pairs(config.layout[currentModifier[1]]) do + for column, key in pairs(rowKeys) do + local xKey, yKey = x + (column-1)*(config.keyWidth-1), y + (row-1)*(config.keyHeight-1) + + gfx.rectangle(xKey, yKey, config.keyWidth, config.keyHeight, 0, hex(0xFFFFFFFF)) + gfx.rectangle(xKey + 1, yKey + 1, config.keyWidth - 2, config.keyHeight - 2, 0, hex(0x000000FF)) + gfx.text(xKey + 2, yKey + 2, key) + + if xTouch then + if xTouch > xKey and xTouch < xKey + config.keyWidth then + if yTouch > yKey and yTouch < yKey + config.keyHeight then + gfx.rectangle(xKey, yKey, config.keyWidth, config.keyHeight, 0, hex(0xDDFFFFFF)) + + local k = config.alias[key] or key + if config.sticky[k] and config.layout[config.sticky[k]] then + if currentModifier[1] == config.sticky[k] and currentModifier[2] == "sticky" then + currentModifier = { "default", "sticky" } + else + currentModifier = { config.sticky[k], "sticky" } + end + elseif config.layout[k] then + if currentModifier[1] == k and currentModifier[2] == "normal" then + currentModifier = { "default", "sticky" } + else + currentModifier = { k, "normal" } + end + else + buffer = buffer .. k + if currentModifier[1] ~= "default" and currentModifier[2] == "normal" then + currentModifier = { "default", "sticky" } + end + end + end + end + end + end + end + end, + + read = function() + local ret = buffer + buffer = "" + + return ret ~= "" and ret or nil + end +} diff --git a/sdcard/3ds/ctruLua/libs/sprite.lua b/sdcard/3ds/ctruLua/libs/sprite.lua index aec1995..7e82555 100644 --- a/sdcard/3ds/ctruLua/libs/sprite.lua +++ b/sdcard/3ds/ctruLua/libs/sprite.lua @@ -26,7 +26,7 @@ local function draw(self, x, y, rad) local tsx, tsy = self.texture:getSize() local sx, sy = getBox(tsx, tsy, frame, self.frameSizeX, self.frameSizeY) - self.texture:drawPart(x, y, sx, sy, self.frameSizeX, self.frameSizeY, rad) + self.texture:drawPart(x, y, sx, sy, self.frameSizeX, self.frameSizeY, rad, self.offsetX, self.offsetY) return frame end @@ -52,20 +52,28 @@ local function resetTimer(self) self.frameTimer = ctr.time() end +local function setOffset(self, x, y) + self.offsetX = x or 0 + self.offsetY = y or self.offsetX +end + -- Sprite object constructor function mod.new(texture, fsx, fsy) return { texture = texture, frameSizeX = fsx, frameSizeY = fsy, + offsetX = 0, + offsetY = 0, animations = {}, currentAnimation = 0, currentFrame = 1, - frameTimer = 0, + frameTimer = ctr.time(), draw = draw, addAnimation = addAnimation, setAnimation = setAnimation, + setOffset = setOffset, resetTimer = resetTimer, } end diff --git a/sdcard/3ds/ctruLua/main.lua b/sdcard/3ds/ctruLua/main.lua index 560a7f6..a574487 100644 --- a/sdcard/3ds/ctruLua/main.lua +++ b/sdcard/3ds/ctruLua/main.lua @@ -1,10 +1,55 @@ -local fs = require("ctr.fs") +local ctr = require("ctr") +local fs = require("ctr.fs") +local gfx = require("ctr.gfx") -repeat - fs.setDirectory("sdmc:/3ds/ctruLua") - local file = dofile("openfile.lua")("Choose a Lua file to execute", "/3ds/ctruLua/", ".lua", "exist") - if file then - fs.setDirectory(file:match("^(.-)[^/]*$")) - dofile(file) +-- Set up path +local ldir = ctr.root.."libs/" +package.path = package.path..";".. ldir.."?.lua;".. ldir.."?/init.lua" +local filepicker = require("filepicker") + +-- Erroring +local function displayError(err, trace) + gfx.set3D(false) + gfx.color.setBackground(0xFF0000B3) + gfx.color.setDefault(0xFFFDFDFD) + gfx.font.setSize(12) + gfx.font.setDefault(gfx.font.load(ctr.root .. "resources/VeraMono.ttf")) + gfx.disableConsole() + + while ctr.run() do + gfx.start(gfx.BOTTOM) + gfx.text(1, 1, "An error has occured.") + gfx.wrappedText(1, 30, err, gfx.BOTTOM_WIDTH-2) + gfx.text(1, gfx.BOTTOM_HEIGHT-15, "Press Start to continue.") + gfx.stop() + gfx.start(gfx.TOP) + gfx.wrappedText(2, 6, trace, gfx.TOP_WIDTH - 2) + gfx.stop() + + gfx.render() + ctr.hid.read() + if ctr.hid.keys().down.start then break end end -until not file \ No newline at end of file +end + +-- Main loop +while ctr.run() do + gfx.set3D(false) + gfx.font.setDefault() + gfx.color.setDefault(0xFFFDFDFD) + gfx.color.setBackground(0xFF333333) + local file, ext, mode, key = filepicker(ctr.root, { + ["%.lua$"] = { + a = {filepicker.openFile, "Run"}, + __name = "Lua Script" + } + }) + if mode then + fs.setDirectory(file:match("^(.-)[^/]*$")) + xpcall(dofile, function(err) displayError(err, debug.traceback()) end, file) + else + break + end +end + +error("Main process has exited.\nPlease reboot.\nPressing Start does not work yet.") diff --git a/sdcard/3ds/ctruLua/openfile.lua b/sdcard/3ds/ctruLua/openfile.lua deleted file mode 100644 index 32a924e..0000000 --- a/sdcard/3ds/ctruLua/openfile.lua +++ /dev/null @@ -1,142 +0,0 @@ ---- Open a file explorer to select a file. --- string title: title of the file explorer. --- string curdir: the directory to initially open the file explorer in. --- string exts: the file extensions the user can select, separated by ";". If nil, all extensions are accepted. --- string type: "exist" to select an existing file, "new" to select an non-existing file or "any" to select a existing --- or non-existing file name. If nil, defaults to "exist". --- returns string: the file the user has selected, or nil if the explorer was closed without selecting a file. --- string: "exist" if the file exist or "new" if it doesn't -return function(title, curdir, exts, type) - -- Open libs - local ctr = require("ctr") - local gfx = require("ctr.gfx") - - local keyboard = dofile("sdmc:/3ds/ctruLua/keyboard.lua") - - -- Arguments - local type = type or "exist" - - -- Variables - local sel = 1 - local scroll = 0 - local files = ctr.fs.list(curdir) - if curdir ~= "/" then table.insert(files, 1, { name = "..", isDirectory = true }) end - local newFileName = "" - - local ret = nil - - -- Remember and set defaults - local was3D = gfx.get3D() - local wasDefault = gfx.color.getDefault() - local wasBackground = gfx.color.getBackground() - local wasFont = gfx.font.getDefault() - gfx.set3D(false) - gfx.color.setDefault(0xFFFFFFFF) - gfx.color.setBackground(0x000000FF) - gfx.font.setDefault() - - while ctr.run() do - ctr.hid.read() - local keys = ctr.hid.keys() - if keys.down.start then break end - - -- Keys input - if keys.down.down and sel < #files then - sel = sel + 1 - if sel > scroll + 14 then scroll = scroll + 1 end - elseif keys.down.up and sel > 1 then - sel = sel - 1 - if sel <= scroll then scroll = scroll - 1 end - end - - if keys.down.a then - local f = files[sel] - - if f.isDirectory then - if f.name == ".." then curdir = curdir:gsub("[^/]+/$", "") - else curdir = curdir..f.name.."/" end - - sel = 1 - scroll = 0 - files = ctr.fs.list(curdir) - - if curdir ~= "/" then - table.insert(files, 1, { name = "..", isDirectory = true }) - end - elseif type == "exist" or type == "any" then - if exts then - for ext in (exts..";"):gmatch("[^;]+") do - if f.name:match("%..+$") == ext then - ret = { curdir..f.name, "exist" } - break - end - end - else - ret = { curdir..f.name, "exist" } - end - if ret then break end - end - end - - -- Keyboard input - if type == "new" or type == "any" then - local input = keyboard.read() - if input then - if input == "BACK" then - newFileName = newFileName:sub(1, (utf8.offset(newFileName, -1) or 0)-1) - elseif input == "\n" then - local fileStatus = "new" - local f = io.open(curdir..newFileName) - if f then fileStatus = "exist" f:close() end - ret = { curdir..newFileName, fileStatus } - break - else - newFileName = newFileName..input - end - end - end - - -- Draw - gfx.startFrame(gfx.GFX_TOP) - - gfx.rectangle(0, 10+(sel-scroll)*15, gfx.TOP_WIDTH, 15, 0, gfx.color.RGBA8(0, 0, 200)) - - for i = scroll+1, scroll+14, 1 do - local f = files[i] - if not f then break end - local name = f.isDirectory and "["..f.name.."]" or f.name.." ("..f.fileSize.."b)" - if not f.isHidden then gfx.text(5, 12+(i-scroll)*15, name) end - end - - gfx.rectangle(0, 0, gfx.TOP_WIDTH, 25, 0, gfx.color.RGBA8(200, 200, 200)) - gfx.text(3, 3, curdir, 13, gfx.color.RGBA8(0, 0, 0)) - - gfx.endFrame() - - gfx.startFrame(gfx.GFX_BOTTOM) - - gfx.text(5, 5, title) - gfx.text(5, 20, "Accepted file extensions: "..(exts or "all")) - - if type == "new" or type == "any" then - gfx.text(5, 90, newFileName) - keyboard.draw(5, 115) - end - - gfx.endFrame() - - gfx.render() - end - - -- Reset defaults - gfx.set3D(was3D) - gfx.color.setDefault(wasDefault) - gfx.color.setBackground(wasBackground) - gfx.font.setDefault(wasFont) - - if ret then - return table.unpack(ret) - else - return ret - end -end diff --git a/sdcard/3ds/ctruLua/editor/VeraMono.ttf b/sdcard/3ds/ctruLua/resources/VeraMono.ttf similarity index 100% rename from sdcard/3ds/ctruLua/editor/VeraMono.ttf rename to sdcard/3ds/ctruLua/resources/VeraMono.ttf diff --git a/source/apt.c b/source/apt.c new file mode 100644 index 0000000..6f2f28c --- /dev/null +++ b/source/apt.c @@ -0,0 +1,359 @@ +/*** +The `apt` module. +Used to manage the applets and application status. +@module ctr.apt +@usage local apt = require("ctr.apt") +*/ + +#include + +#include <3ds/types.h> +#include <3ds/services/apt.h> + +#include +#include + +/*** +Set the app status. +@function setStatus +@tparam integer status the new app status +*/ +static int apt_setStatus(lua_State *L) { + APT_AppStatus status = luaL_checkinteger(L, 1); + + aptSetStatus(status); + + return 0; +} + +/*** +Get the app status. +@function getStatus +@treturn integer the app status +*/ +static int apt_getStatus(lua_State *L) { + APT_AppStatus status = aptGetStatus(); + + lua_pushinteger(L, status); + + return 1; +} + +/*** +Return to the Home menu. +@function returnToMenu +*/ +static int apt_returnToMenu(lua_State *L) { + aptReturnToMenu(); + + return 0; +} + +/*** +Get the power status. +@function getStatusPower +@treturn boolean true if the power button has been pressed +*/ +static int apt_getStatusPower(lua_State *L) { + u32 status = aptGetStatusPower(); + + lua_pushboolean(L, status); + + return 1; +} + +/*** +Set the power status. +@function setStatusPower +@tparam boolean status new power status +*/ +static int apt_setStatusPower(lua_State *L) { + u32 status = lua_toboolean(L, 1); + + aptSetStatusPower(status); + + return 0; +} + +/*** +Signal that the application is ready for sleeping. +@function signalReadyForSleep +*/ +static int apt_signalReadyForSleep(lua_State *L) { + aptSignalReadyForSleep(); + + return 0; +} + +/*** +Return the Home menu AppID. +@function getMenuAppID +@treturn number the AppID +*/ +static int apt_getMenuAppID(lua_State *L) { + lua_pushinteger(L, aptGetMenuAppID()); + + return 1; +} + +/*** +Allow or not the system to enter sleep mode. +@function setSleepAllowed +@tparam boolean allowed `true` to allow, `false` to disallow +*/ +static int apt_setSleepAllowed(lua_State *L) { + bool allowed = lua_toboolean(L, 1); + + aptSetSleepAllowed(allowed); + + return 0; +} + +/*** +Check if sleep mode is allowed. +@function isSleepAllowed +@treturn boolean `true` is allowed, false if not. +*/ +static int apt_isSleepAllowed(lua_State *L) { + lua_pushboolean(L, aptIsSleepAllowed()); + + return 1; +} + +/*** +Checks whether the system is a New 3DS. +@function isNew3DS +@treturn boolean `true` if it's a New3DS, false otherwise +*/ +static int apt_isNew3DS(lua_State *L) { + bool isNew3ds; + + APT_CheckNew3DS(&isNew3ds); + + lua_pushboolean(L, isNew3ds); + + return 1; +} + +static const struct luaL_Reg apt_lib[] = { + { "setStatus", apt_setStatus }, + { "getStatus", apt_getStatus }, + { "returnToMenu", apt_returnToMenu }, + { "getStatusPower", apt_getStatusPower }, + { "setStatusPower", apt_setStatusPower }, + { "signalReadyForSleep", apt_signalReadyForSleep }, + { "getMenuAppID", apt_getMenuAppID }, + { "setSleepAllowed", apt_setSleepAllowed }, + { "isSleepAllowed", apt_isSleepAllowed }, + { "isNew3DS", apt_isNew3DS }, + {NULL, NULL} +}; + +struct { char *name; int value; } apt_constants[] = { + /*** + @field APPID_HOMEMENU + */ + {"APPID_HOMEMENU", APPID_HOMEMENU }, + /*** + @field APPID_CAMERA + */ + {"APPID_CAMERA", APPID_CAMERA }, + /*** + @field APPID_FRIENDS_LIST + */ + {"APPID_FRIENDS_LIST", APPID_FRIENDS_LIST }, + /*** + @field APPID_GAME_NOTES + */ + {"APPID_GAME_NOTES", APPID_GAME_NOTES }, + /*** + @field APPID_WEB + */ + {"APPID_WEB", APPID_WEB }, + /*** + @field APPID_INSTRUCTION_MANUAL + */ + {"APPID_INSTRUCTION_MANUAL", APPID_INSTRUCTION_MANUAL}, + /*** + @field APPID_NOTIFICATIONS + */ + {"APPID_NOTIFICATIONS", APPID_NOTIFICATIONS }, + /*** + @field APPID_MIIVERSE + */ + {"APPID_MIIVERSE", APPID_MIIVERSE }, + /*** + @field APPID_MIIVERSE_POSTING + */ + {"APPID_MIIVERSE_POSTING", APPID_MIIVERSE_POSTING }, + /*** + @field APPID_AMIIBO_SETTINGS + */ + {"APPID_AMIIBO_SETTINGS", APPID_AMIIBO_SETTINGS }, + /*** + @field APPID_APPLICATION + */ + {"APPID_APPLICATION", APPID_APPLICATION }, + /*** + @field APPID_ESHOP + */ + {"APPID_ESHOP", APPID_ESHOP }, + /*** + @field APPID_SOFTWARE_KEYBOARD + */ + {"APPID_SOFTWARE_KEYBOARD", APPID_SOFTWARE_KEYBOARD }, + /*** + @field APPID_APPLETED + */ + {"APPID_APPLETED", APPID_APPLETED }, + /*** + @field APPID_PNOTE_AP + */ + {"APPID_PNOTE_AP", APPID_PNOTE_AP }, + /*** + @field APPID_SNOTE_AP + */ + {"APPID_SNOTE_AP", APPID_SNOTE_AP }, + /*** + @field APPID_ERROR + */ + {"APPID_ERROR", APPID_ERROR }, + /*** + @field APPID_MINT + */ + {"APPID_MINT", APPID_MINT }, + /*** + @field APPID_EXTRAPAD + */ + {"APPID_EXTRAPAD", APPID_EXTRAPAD }, + /*** + @field APPID_MEMOLIB + */ + {"APPID_MEMOLIB", APPID_MEMOLIB }, + /*** + @field APP_NOTINITIALIZED + */ + {"APP_NOTINITIALIZED", APP_NOTINITIALIZED }, + /*** + @field APP_RUNNING + */ + {"APP_RUNNING", APP_RUNNING }, + /*** + @field APP_SUSPENDED + */ + {"APP_SUSPENDED", APP_SUSPENDED }, + /*** + @field APP_EXITING + */ + {"APP_EXITING", APP_EXITING }, + /*** + @field APP_SUSPENDING + */ + {"APP_SUSPENDING", APP_SUSPENDING }, + /*** + @field APP_SLEEPMODE + */ + {"APP_SLEEPMODE", APP_SLEEPMODE }, + /*** + @field APP_PREPARE_SLEEPMODE + */ + {"APP_PREPARE_SLEEPMODE", APP_PREPARE_SLEEPMODE}, + /*** + @field APP_APPLETSTARTED + */ + {"APP_APPLETSTARTED", APP_APPLETSTARTED }, + /*** + @field APP_APPLETCLOSED + */ + {"APP_APPLETCLOSED", APP_APPLETCLOSED }, + /*** + @field APTSIGNAL_HOMEBUTTON + */ + {"APTSIGNAL_HOMEBUTTON", APTSIGNAL_HOMEBUTTON }, + /*** + @field APTSIGNAL_HOMEBUTTON2 + */ + {"APTSIGNAL_HOMEBUTTON2", APTSIGNAL_HOMEBUTTON2 }, + /*** + @field APTSIGNAL_SLEEP_QUERY + */ + {"APTSIGNAL_SLEEP_QUERY", APTSIGNAL_SLEEP_QUERY }, + /*** + @field APTSIGNAL_SLEEP_CANCEL + */ + {"APTSIGNAL_SLEEP_CANCEL", APTSIGNAL_SLEEP_CANCEL}, + /*** + @field APTSIGNAL_SLEEP_ENTER + */ + {"APTSIGNAL_SLEEP_ENTER", APTSIGNAL_SLEEP_ENTER }, + /*** + @field APTSIGNAL_WAKEUP + */ + {"APTSIGNAL_SLEEP_WAKEUP", APTSIGNAL_SLEEP_WAKEUP}, + /*** + @field APTSIGNAL_SHUTDOWN + */ + {"APTSIGNAL_SHUTDOWN", APTSIGNAL_SHUTDOWN }, + /*** + @field APTSIGNAL_POWERBUTTON + */ + {"APTSIGNAL_POWERBUTTON", APTSIGNAL_POWERBUTTON }, + /*** + @field APTSIGNAL_POWERBUTTON2 + */ + {"APTSIGNAL_POWERBUTTON2", APTSIGNAL_POWERBUTTON2}, + /*** + @field APTSIGNAL_TRY_SLEEP + */ + {"APTSIGNAL_TRY_SLEEP", APTSIGNAL_TRY_SLEEP }, + /*** + @field APTSIGNAL_ORDERTOCLOSE + */ + {"APTSIGNAL_ORDERTOCLOSE", APTSIGNAL_ORDERTOCLOSE}, + /*** + @field APTHOOK_ONSUSPEND + */ + {"APTHOOK_ONSUSPEND", APTHOOK_ONSUSPEND}, + /*** + @field APTHOOK_ONRESTORE + */ + {"APTHOOK_ONRESTORE", APTHOOK_ONRESTORE}, + /*** + @field APTHOOK_ONSLEEP + */ + {"APTHOOK_ONSLEEP", APTHOOK_ONSLEEP }, + /*** + @field APTHOOK_ONWAKEUP + */ + {"APTHOOK_ONWAKEUP", APTHOOK_ONWAKEUP }, + /*** + @field APTHOOK_ONEXIT + */ + {"APTHOOK_ONEXIT", APTHOOK_ONEXIT }, + /*** + @field APTHOOK_COUNT + */ + {"APTHOOK_COUNT", APTHOOK_COUNT }, + {NULL, 0} +}; + +int luaopen_apt_lib(lua_State *L) { + aptInit(); + + luaL_newlib(L, apt_lib); + + for (int i = 0; apt_constants[i].name; i++) { + lua_pushinteger(L, apt_constants[i].value); + lua_setfield(L, -2, apt_constants[i].name); + } + + return 1; +} + +void load_apt_lib(lua_State *L) { + luaL_requiref(L, "ctr.apt", luaopen_apt_lib, false); +} + +void unload_apt_lib(lua_State *L) { + aptExit(); +} diff --git a/source/audio.c b/source/audio.c new file mode 100644 index 0000000..fa56cd0 --- /dev/null +++ b/source/audio.c @@ -0,0 +1,1182 @@ +/*** +The `audio` module. +An audio channel can play only one audio object at a time. +There are 24 audio channels available, numbered from 0 to 23. +@module ctr.audio +@usage local audio = require("ctr.audio") +*/ + +#include <3ds.h> + +#include +#include +#include +#include + +#include +#include + +#include +#include + +// Audio object type +typedef enum { + TYPE_UNKNOWN = -1, + TYPE_OGG = 0, + TYPE_WAV = 1, + TYPE_RAW = 2 +} filetype; + +// Audio object userdata +typedef struct { + filetype type; // file type + + // File type specific + union { + // OGG Vorbis + struct { + OggVorbis_File vf; + int currentSection; // section and position at the end of the initial data + long rawPosition; + }; + // WAV + struct { + FILE* file; + long fileSize; + long filePosition; // position at the end of the initial data + }; + }; + + // Needed for playback + float rate; // sample rate (per channel) (Hz) + u32 channels; // channel count + u32 encoding; // data encoding (NDSP_ENCODING_*) + + // Initial data + u32 nsamples; // numbers of samples in the audio (per channel, not the total) + u32 size; // number of bytes in the audio (total, ie data size) + char* data; // raw audio data + + // Other useful data + u16 bytePerSample; // bytes per sample (warning: undefined for ADPCM (only for raw data)) + u32 chunkSize; // size per chunk (for streaming) + u32 chunkNsamples; // number of samples per chunk + + // Playing parameters (type-independant) + float mix[12]; // mix parameters + ndspInterpType interp; // interpolation type + double speed; // playing speed +} audio_userdata; + +// Audio stream instance struct (when an audio is played; only used when streaming) +typedef struct { + audio_userdata* audio; + + bool loop; // loop audio? + + // Current position information + union { + // OGG + struct { + int currentSection; + long rawPosition; + }; + // WAV + long filePosition; + }; + + double prevStartTime; // audio time when last chunk started playing + bool eof; // if reached end of file + bool done; // if streaming ended and the stream will be skipped on the next update + // (the struct should be keept in memory until replaced or audio stopped or it will break audio:time()) + + char* nextData; // the next data to play + ndspWaveBuf* nextWaveBuf; + + char* prevData; // the data actually playing + ndspWaveBuf* prevWaveBuf; +} audio_stream; + +// Indicate if NDSP was initialized or not. +// NDSP doesn't work on citra yet. +// Please only throw an error related to this when using a ndsp function, so other parts of the +// audio module are still available on citra, like audio.load() and audio:info(). +bool isAudioInitialized = false; + +// Array of the last audio_userdata sent to each channel; channels range from 0 to 23 +audio_userdata* channels[24]; + +// Array of the audio_instance that needs to be updated when calling audio.update (indexed per channel). +audio_stream* streaming[24]; + +// Stop playing audio on a channel, and stop streaming/free memory. +void stopAudio(int channel) { + ndspChnWaveBufClear(channel); + + // Stop streaming and free data + if (streaming[channel] != NULL) { + audio_stream* stream = streaming[channel]; + if (stream->nextWaveBuf != NULL) { + free(stream->nextWaveBuf); + stream->nextWaveBuf = NULL; + } + if (stream->nextData != NULL) { + linearFree(stream->nextData); + stream->nextData = NULL; + } + if (stream->prevWaveBuf != NULL) { + free(stream->prevWaveBuf); + stream->prevWaveBuf = NULL; + } + if (stream->prevData != NULL) { + linearFree(stream->prevData); + stream->prevData = NULL; + } + free(stream); + streaming[channel] = NULL; + } +} + +/*** +Load an audio file. +OGG Vorbis and PCM WAV file format are currently supported. +(Most WAV files use the PCM encoding). +NOTE: audio streaming doesn't use threading for now, this means that the decoding will be done on the main thread. +It should work fine with WAVs, but with OGG files you may suffer slowdowns when a new chunk of data is decoded. +To avoid that, you can either reduce the chunkDuration or disable streaming, but be careful if you do so, audio files +can fill the memory really quickly. +@function load +@tparam string path path to the file or the data if type is raw +@tparam[opt=0.1] number chunkDuration if set to -1, streaming will be disabled (all data is loaded in memory at once) + Other values are the stream chunk duration in seconds (ctrµLua will load + the audio per chunk of x seconds). Note that you need to call audio.update() each + frame in order for ctµLua to load new data from audio streams. Two chunks of data + will be loaded at the same time at most (one playing, the other ready to be played). +@tparam[opt=detect] string type file type, `"ogg"` or `"wav"`. + If set to `"detect"`, will try to deduce the type from the filename. +@treturn[1] audio the loaded audio object +@treturn[2] nil if a error happened +@treturn[2] string error message +*/ +static int audio_load(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + double streamChunk = luaL_optnumber(L, 2, 0.1); + const char* argType = luaL_optstring(L, 3, "detect"); + + // Create userdata + audio_userdata *audio = lua_newuserdata(L, sizeof(*audio)); + luaL_getmetatable(L, "LAudio"); + lua_setmetatable(L, -2); + for (int i=0; i<12; i++) audio->mix[i] = 1; + audio->interp = NDSP_INTERP_LINEAR; + audio->speed = 1; + + // Get file type + filetype type = TYPE_UNKNOWN; + if (strcmp(argType, "detect") == 0) { + const char *dot = strrchr(path, '.'); + if (!dot || dot == path) dot = ""; + const char *ext = dot + 1; + if (strncmp(ext, "ogg", 3) == 0) type = TYPE_OGG; + else if (strncmp(ext, "wav", 3) == 0) type = TYPE_WAV; + } else if (strcmp(argType, "ogg") == 0) { + type = TYPE_OGG; + } else if (strcmp(argType, "wav") == 0) { + type = TYPE_WAV; + } else if (strcmp(argType, "raw") == 0) { + type = TYPE_RAW; + } + + // Open and read file + if (type == TYPE_OGG) { + audio->type = TYPE_OGG; + + // Load audio file + FILE *file = fopen(path, "rb"); + if (ov_open(file, &audio->vf, NULL, 0) < 0) { + lua_pushnil(L); + lua_pushstring(L, "input does not appear to be a valid ogg vorbis file or doesn't exist"); + return 2; + } + + // Decoding Ogg Vorbis bitstream + vorbis_info* vi = ov_info(&audio->vf, -1); + if (vi == NULL) luaL_error(L, "could not retrieve ogg audio stream informations"); + + audio->rate = vi->rate; + audio->channels = vi->channels; + audio->encoding = NDSP_ENCODING_PCM16; + audio->nsamples = ov_pcm_total(&audio->vf, -1); + audio->size = audio->nsamples * audio->channels * 2; // *2 because output is PCM16 (2 bytes/sample) + audio->bytePerSample = 2; + + // Streaming + if (streamChunk < 0) { + audio->chunkNsamples = audio->nsamples; + audio->chunkSize = audio->size; + } else { + audio->chunkNsamples = fmin(round(streamChunk * audio->rate), audio->nsamples); + audio->chunkSize = audio->chunkNsamples * audio->channels * 2; + } + + // Allocate + if (linearSpaceFree() < audio->chunkSize) luaL_error(L, "not enough linear memory available"); + audio->data = linearAlloc(audio->chunkSize); + + // Decoding loop + int offset = 0; + int eof = 0; + while (!eof && offset < audio->chunkSize) { + long ret = ov_read(&audio->vf, &audio->data[offset], fmin(audio->chunkSize - offset, 4096), &audio->currentSection); + + if (ret == 0) { + eof = 1; + } else if (ret < 0) { + ov_clear(&audio->vf); + linearFree(audio->data); + luaL_error(L, "error in the ogg vorbis stream"); + return 0; + } else { + // TODO handle multiple links (http://xiph.org/vorbis/doc/vorbisfile/decoding.html) + offset += ret; + } + } + audio->rawPosition = ov_raw_tell(&audio->vf); + + return 1; + + } else if (type == TYPE_WAV) { + audio->type = TYPE_WAV; + + // Used this as a reference for the WAV format: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html + + // Load file + FILE *file = fopen(path, "rb"); + if (file) { + bool valid = true; // if something goes wrong, this will be false + + char buff[8]; + + // Master chunk + fread(buff, 4, 1, file); // ckId + if (strncmp(buff, "RIFF", 4) != 0) valid = false; + + fseek(file, 4, SEEK_CUR); // skip ckSize + + fread(buff, 4, 1, file); // WAVEID + if (strncmp(buff, "WAVE", 4) != 0) valid = false; + + // fmt Chunk + fread(buff, 4, 1, file); // ckId + if (strncmp(buff, "fmt ", 4) != 0) valid = false; + + fread(buff, 4, 1, file); // ckSize + if (*buff != 16) valid = false; // should be 16 for PCM format + + fread(buff, 2, 1, file); // wFormatTag + if (*buff != 0x0001) valid = false; // PCM format + + u16 channels; + fread(&channels, 2, 1, file); // nChannels + audio->channels = channels; + + u32 rate; + fread(&rate, 4, 1, file); // nSamplesPerSec + audio->rate = rate; + + fseek(file, 4, SEEK_CUR); // skip nAvgBytesPerSec + + u16 byte_per_block; // 1 block = 1*channelCount samples + fread(&byte_per_block, 2, 1, file); // nBlockAlign + + u16 byte_per_sample; + fread(&byte_per_sample, 2, 1, file); // wBitsPerSample + byte_per_sample /= 8; // bits -> bytes + + // There may be some additionals chunks between fmt and data + // TODO handle some usefull chunks that may be here + fread(&buff, 4, 1, file); // ckId + while (strncmp(buff, "data", 4) != 0) { + u32 size; + fread(&size, 4, 1, file); // ckSize + + fseek(file, size, SEEK_CUR); // skip chunk + + int i = fread(&buff, 4, 1, file); // next chunk ckId + + if (i < 4) { // reached EOF before finding a data chunk + valid = false; + break; + } + } + + // data Chunk (ckId already read) + u32 size; + fread(&size, 4, 1, file); // ckSize + audio->size = size; + + audio->nsamples = audio->size / byte_per_block; + + if (byte_per_sample == 1) audio->encoding = NDSP_ENCODING_PCM8; + else if (byte_per_sample == 2) audio->encoding = NDSP_ENCODING_PCM16; + else luaL_error(L, "unknown encoding, needs to be PCM8 or PCM16"); + + if (!valid) { + fclose(file); + luaL_error(L, "invalid PCM wav file"); + return 0; + } + + audio->bytePerSample = byte_per_sample / audio->channels; + + // Streaming + if (streamChunk < 0) { + audio->chunkNsamples = audio->nsamples; + audio->chunkSize = audio->size; + } else { + audio->chunkNsamples = fmin(round(streamChunk * audio->rate), audio->nsamples); + audio->chunkSize = audio->chunkNsamples * audio->channels * audio->bytePerSample; + } + + // Read data + if (linearSpaceFree() < audio->chunkSize) luaL_error(L, "not enough linear memory available"); + audio->data = linearAlloc(audio->chunkSize); + + fread(audio->data, audio->chunkSize, 1, file); + + audio->file = file; + audio->filePosition = ftell(file); + + fseek(file, 0, SEEK_END); + audio->fileSize = ftell(file); + + return 1; + + } else { + lua_pushnil(L); + lua_pushfstring(L, "error while opening wav file: %s", strerror(errno));; + return 2; + } + } + + luaL_error(L, "unknown audio type"); + return 0; +} + +/*** +Load raw audio data from a string. +No streaming. +@function loadRaw +@tparam string data raw audio data +@tparam number rate sampling rate +@tparam string encoding audio encoding, can be `"PCM8"`, `"PCM16"` or `"ADPCM"` +@tparam[opt=1] number channels audio channels count +@treturn[1] audio the loaded audio object +@treturn[2] nil if a error happened +@treturn[2] string error message +*/ +static int audio_loadRaw(lua_State *L) { + size_t dataSize; + char* data = (char*)luaL_checklstring(L, 1, &dataSize); + float rate = luaL_checkinteger(L, 2); + const char* argEncoding = luaL_checkstring(L, 3); + u32 channels = luaL_optinteger(L, 4, 1); + + audio_userdata *audio = lua_newuserdata(L, sizeof(*audio)); + luaL_getmetatable(L, "LAudio"); + lua_setmetatable(L, -2); + + audio->type = TYPE_RAW; + audio->rate = rate; + audio->channels = channels; + + u8 sampleSize = 2; // default to 2 + if (strcmp(argEncoding, "PCM8")) { + audio->encoding = NDSP_ENCODING_PCM8; + audio->bytePerSample = 1; + sampleSize = 1; + } else if (strcmp(argEncoding, "PCM16")) { + audio->encoding = NDSP_ENCODING_PCM16; + audio->bytePerSample = 2; + } else if (strcmp(argEncoding, "ADPCM")) { + audio->encoding = NDSP_ENCODING_ADPCM; + } else { + lua_pushnil(L); + lua_pushstring(L, "Wrong format"); + return 2; + } + + audio->nsamples = dataSize/sampleSize; + audio->size = dataSize; + audio->data = data; + + audio->chunkSize = audio->size; + audio->chunkNsamples = audio->nsamples; + + audio->speed = 1.0; + + return 1; +} + +/*** +Check if audio is currently playing on a channel. +@function playing +@tparam[opt] integer channel number; if `nil` will search the first channel playing an audio +@treturn boolean `true` if the channel is currently playing the audio, `false` otherwise. + If channel is not set, `false` means no audio is playing at all. +*/ +static int audio_playing(lua_State *L) { + if (!isAudioInitialized) { + lua_pushboolean(L, false); + return 1; + } + + int channel = luaL_optinteger(L, 1, -1); + if (channel < -1 || channel > 23) luaL_error(L, "channel number must be between 0 and 23"); + + // Search a channel playing audio + if (channel == -1) { + for (int i = 0; i <= 23; i++) { + if (ndspChnIsPlaying(i)) { + lua_pushboolean(L, true); + return 1; + } + } + + lua_pushboolean(L, false); + return 1; + + } else { + lua_pushboolean(L, ndspChnIsPlaying(channel)); + return 1; + } + + return 0; +} + +/*** +Set the mix parameters (volumes) of a channel. +Volumes go from 0 (0%) to 1 (100%). +Note that when a new audio object will play on this channel, theses parameters will be +reset with the new audio object defaults (set in `audio:mix()`). +@function mix +@tparam[opt] integer channel the channel number, if `nil` will change the mix parmaters of all channels +@tparam[opt=1] number frontLeft front left volume +@tparam[opt=frontLeft] number frontRight front right volume +@tparam[opt=frontLeft] number backLeft back left volume +@tparam[opt=frontRight] number backRight back right volume +*/ +static int audio_mix(lua_State *L) { + if (!isAudioInitialized) luaL_error(L, "audio wasn't initialized correctly"); + + int channel = luaL_optinteger(L, 1, -1); + if (channel < -1 || channel > 23) luaL_error(L, "channel number must be between 0 and 23"); + + float mix[12]; + mix[0] = luaL_optnumber(L, 2, 1); + mix[1] = luaL_optnumber(L, 3, mix[0]); + mix[2] = luaL_optnumber(L, 4, mix[0]); + mix[3] = luaL_optnumber(L, 5, mix[2]); + + if (channel == -1) { + for (int i=0; i<=23; i++) ndspChnSetMix(i, mix); + } else { + ndspChnSetMix(channel, mix); + } + + return 0; +} + +/*** +Set the interpolation type of a channel. +Note that when a new audio object will play on this channel, this parameter will be +reset with the new audio object default (set in `audio:interpolation()`). +@function interpolation +@tparam[opt] integer channel stop playing audio on this channel; if `nil` will change interpolation type on all channels +@tparam[opt=linear] string "none", "linear" or "polyphase" +*/ +static int audio_interpolation(lua_State *L) { + if (!isAudioInitialized) luaL_error(L, "audio wasn't initialized correctly"); + + int channel = luaL_optinteger(L, 1, -1); + if (channel < -1 || channel > 23) luaL_error(L, "channel number must be between 0 and 23"); + + const char* interpArg = luaL_optstring(L, 2, "linear"); + + ndspInterpType interp; + if (strcmp(interpArg, "none") == 0) + interp = NDSP_INTERP_NONE; + else if (strcmp(interpArg, "linear") == 0) + interp = NDSP_INTERP_LINEAR; + else if (strcmp(interpArg, "polyphase") == 0) + interp = NDSP_INTERP_POLYPHASE; + else { + luaL_error(L, "unknown interpolation type"); + return 0; + } + + if (channel == -1) { + for (int i=0; i<=23; i++) ndspChnSetInterp(i, interp); + } else { + ndspChnSetInterp(channel, interp); + } + + return 0; +} + +/*** +Set the speed of the audio playing in a channel. +Speed is expressed as a percentage of the normal playing speed. +1 is 100% speed and 2 is 200%, etc. +Note that when a new audio object will play on this channel, this parameter will be +reset with the new audio object default (set in `audio:speed()`). +@function speed +@tparam[opt] integer channel stop playing audio on this channel; if `nil` will change interpolation type on all channels +@tparam[opt=1] number speed percentage +*/ +static int audio_speed(lua_State *L) { + if (!isAudioInitialized) luaL_error(L, "audio wasn't initialized correctly"); + + int channel = luaL_optinteger(L, 1, -1); + if (channel < -1 || channel > 23) luaL_error(L, "channel number must be between 0 and 23"); + + double speed = luaL_optnumber(L, 2, 1); + + if (channel == -1) { + for (int i=0; i<=23; i++) { + if (channels[i]) ndspChnSetRate(i, channels[i]->rate * speed); + } + } else { + if (channels[channel]) ndspChnSetRate(channel, channels[channel]->rate * speed); + } + + return 0; +} + +/*** +Stop playing all audio on all channels or a specific channel. +@function stop +@tparam[opt] integer channel stop playing audio on this channel; if `nil` will stop audio on all channels +@treturn integer number of channels where audio was stopped +*/ +static int audio_stop(lua_State *L) { + if (!isAudioInitialized) { + lua_pushinteger(L, 0); + return 1; + } + + int channel = luaL_optinteger(L, 1, -1); + + int n = 0; + + if (channel == -1) { + for (int i = 0; i <= 23; i++) { + if (ndspChnIsPlaying(i)) { + stopAudio(i); + n++; + } + } + } else if (channel < 0 || channel > 23) { + luaL_error(L, "channel number must be between 0 and 23"); + } else { + if (ndspChnIsPlaying(channel)) { + stopAudio(channel); + n++; + } + } + + lua_pushinteger(L, n); + + return 1; +} + +/*** +Update all the currently playing audio streams. +Must be called every frame if you want to use audio with streaming. +@function update +*/ +static int audio_update(lua_State *L) { + if (!isAudioInitialized) luaL_error(L, "audio wasn't initialized correctly"); + + for (int i = 0; i <= 23; i++) { + if (streaming[i] == NULL) continue; + audio_stream* stream = streaming[i]; + if (stream->done) continue; + audio_userdata* audio = stream->audio; + + // If the next chunk started to play, load the next one + if (stream->nextWaveBuf != NULL && ndspChnGetWaveBufSeq(i) == stream->nextWaveBuf->sequence_id) { + if (stream->prevWaveBuf) stream->prevStartTime = stream->prevStartTime + (double)(audio->chunkNsamples) / audio->rate; + + if (!stream->eof) { + // Swap buffers + char* prevData = stream->prevData; // doesn't contain important data, can rewrite + char* nextData = stream->nextData; // contains the data that started playing + stream->prevData = nextData; // buffer in use + stream->nextData = prevData; // now contains an available buffer + stream->prevWaveBuf = stream->nextWaveBuf; + + // Decoding loop + u32 chunkNsamples = audio->chunkNsamples; // chunk nsamples and size may be lower than the defaults if reached EOF + u32 chunkSize = audio->chunkSize; + if (audio->type == TYPE_OGG) { + if (ov_seekable(&audio->vf) && ov_raw_tell(&audio->vf) != stream->rawPosition) + ov_raw_seek(&audio->vf, stream->rawPosition); // goto last read end (audio file may be played multiple times at one) + + int offset = 0; + while (!stream->eof && offset < audio->chunkSize) { + long ret = ov_read(&audio->vf, &stream->nextData[offset], fmin(audio->chunkSize - offset, 4096), &stream->currentSection); + if (ret == 0) { + stream->eof = 1; + } else if (ret < 0) { + luaL_error(L, "error in the ogg vorbis stream"); + return 0; + } else { + offset += ret; + } + } + stream->rawPosition = ov_raw_tell(&audio->vf); + chunkSize = offset; + chunkNsamples = chunkSize / audio->channels / audio->bytePerSample; + + } else if (audio->type == TYPE_WAV) { + chunkSize = fmin(audio->fileSize - stream->filePosition, audio->chunkSize); + chunkNsamples = chunkSize / audio->channels / audio->bytePerSample; + + fseek(audio->file, stream->filePosition, SEEK_SET); // goto last read end (audio file may be played multiple times at one) + fread(stream->nextData, chunkSize, 1, audio->file); + stream->filePosition = ftell(audio->file); + if (stream->filePosition == audio->fileSize) stream->eof = 1; + + } else luaL_error(L, "unknown audio type"); + + // Send & play audio data + ndspWaveBuf* waveBuf = calloc(1, sizeof(ndspWaveBuf)); + + waveBuf->data_vaddr = stream->nextData; + waveBuf->nsamples = chunkNsamples; + waveBuf->looping = false; + + DSP_FlushDataCache((u32*)stream->nextData, chunkSize); + + ndspChnWaveBufAdd(i, waveBuf); + + stream->nextWaveBuf = waveBuf; + } + } + + // Free the last chunk if it's no longer played + if (stream->prevWaveBuf != NULL && ndspChnGetWaveBufSeq(i) != stream->prevWaveBuf->sequence_id) { + free(stream->prevWaveBuf); + stream->prevWaveBuf = NULL; + } + + // We're done + if (stream->prevWaveBuf == NULL && stream->nextWaveBuf != NULL && ndspChnGetWaveBufSeq(i) != stream->nextWaveBuf->sequence_id && stream->eof) { + free(stream->nextWaveBuf); + stream->nextWaveBuf = NULL; + + // Free memory + if (!stream->loop) { + linearFree(stream->prevData); + stream->prevData = NULL; + linearFree(stream->nextData); + stream->nextData = NULL; + stream->done = true; + // Loop: goto start + } else { + // Send & play audio initial data + ndspWaveBuf* waveBuf = calloc(1, sizeof(ndspWaveBuf)); + + waveBuf->data_vaddr = audio->data; + waveBuf->nsamples = audio->chunkNsamples; + waveBuf->looping = false; + + DSP_FlushDataCache((u32*)audio->data, audio->chunkSize); + + ndspChnWaveBufAdd(i, waveBuf); + + stream->nextWaveBuf = waveBuf; + + // Reset stream values + stream->prevStartTime = 0; + stream->eof = false; + if (audio->type == TYPE_OGG) { + stream->currentSection = audio->currentSection; + stream->rawPosition = audio->rawPosition; + } else if (audio->type == TYPE_WAV) stream->filePosition = audio->filePosition; + } + } + } + + return 0; +} + +/*** +audio object +@section Methods +*/ + +/*** +Returns the audio object duration. +@function :duration +@treturn number duration in seconds +*/ +static int audio_object_duration(lua_State *L) { + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + + lua_pushnumber(L, (double)(audio->nsamples) / audio->rate); + + return 1; +} + +/*** +Returns the current playing position. +@function :time +@tparam[opt] integer channel number; if `nil` will use the first channel found which played this audio +@treturn number time in seconds +*/ +static int audio_object_time(lua_State *L) { + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + + int channel = luaL_optinteger(L, 2, -1); + if (channel < -1 || channel > 23) luaL_error(L, "channel number must be between 0 and 23"); + + // Search a channel playing the audio object + if (channel == -1) { + for (int i = 0; i <= 23; i++) { + if (channels[i] == audio) { + channel = i; + break; + } + } + } + + if (channel == -1 || channels[channel] != audio || !isAudioInitialized) // audio not playing + lua_pushnumber(L, 0); + else { + double additionnalTime = 0; + if (streaming[channel] != NULL) additionnalTime = streaming[channel]->prevStartTime; + lua_pushnumber(L, (double)(ndspChnGetSamplePos(channel)) / audio->rate + additionnalTime); + } + + return 1; +} + +/*** +Check if the audio is currently playing. +@function :playing +@tparam[opt] integer channel channel number; if `nil` will search the first channel playing this audio +@treturn boolean true if the channel is currently playing the audio, false otherwise +*/ +static int audio_object_playing(lua_State *L) { + if (!isAudioInitialized) { + lua_pushboolean(L, false); + return 1; + } + + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + + int channel = luaL_optinteger(L, 2, -1); + if (channel < -1 || channel > 23) luaL_error(L, "channel number must be between 0 and 23"); + + // Search a channel playing the audio object + if (channel == -1) { + for (int i = 0; i <= 23; i++) { + if (channels[i] == audio && ndspChnIsPlaying(i)) { + lua_pushboolean(L, true); + return 1; + } + } + + lua_pushboolean(L, false); + return 1; + + } else { + lua_pushboolean(L, channels[channel] == audio && ndspChnIsPlaying(channel)); + return 1; + } + + return 0; +} + +/*** +Set the mix parameters (volumes) of the audio. +Volumes go from 0 (0%) to 1 (100%). +@function :mix +@tparam[opt=1] number frontLeft front left volume +@tparam[opt=frontLeft] number frontRight front right volume +@tparam[opt=frontLeft] number backLeft back left volume +@tparam[opt=frontRight] number backRight back right volume +*/ +static int audio_object_mix(lua_State *L) { + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + + audio->mix[0] = luaL_optnumber(L, 2, 1); + audio->mix[1] = luaL_optnumber(L, 3, audio->mix[0]); + audio->mix[2] = luaL_optnumber(L, 4, audio->mix[0]); + audio->mix[3] = luaL_optnumber(L, 5, audio->mix[2]); + + return 0; +} + +/*** +Set the interpolation type of the audio. +@function :interpolation +@tparam[opt=linear] string "none", "linear" or "polyphase" +*/ +static int audio_object_interpolation(lua_State *L) { + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + + const char* interp = luaL_optstring(L, 2, "linear"); + + if (strcmp(interp, "none") == 0) + audio->interp = NDSP_INTERP_NONE; + else if (strcmp(interp, "linear") == 0) + audio->interp = NDSP_INTERP_LINEAR; + else if (strcmp(interp, "polyphase") == 0) + audio->interp = NDSP_INTERP_POLYPHASE; + else { + luaL_error(L, "unknown interpolation type"); + return 0; + } + + return 0; +} + +/*** +Set the speed of the audio. +Speed is expressed as a percentage of the normal playing speed. +1 is 100% speed and 2 is 200%, etc. +@function :speed +@tparam[opt=1] number speed percentage +*/ +static int audio_object_speed(lua_State *L) { + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + + audio->speed = luaL_optnumber(L, 2, 1); + + return 0; +} + +/*** +Plays the audio file. +@function :play +@tparam[opt=false] boolean loop if the audio should loop or not +@tparam[opt] integer channel the channel to play the audio on (0-23); if `nil` will use the first available channel. + If the channel was playing another audio, it will be stopped and replaced by this audio. + If not set and no channel is available, will return nil plus an error message. +@treturn[1] integer channel number the audio is playing on +@treturn[2] nil an error happened and the audio was not played +@treturn[2] error the error message +*/ +static int audio_object_play(lua_State *L) { + if (!isAudioInitialized) luaL_error(L, "audio wasn't initialized correctly"); + + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + bool loop = lua_toboolean(L, 2); + int channel = luaL_optinteger(L, 3, -1); + + // Find a free channel + if (channel == -1) { + for (int i = 0; i <= 23; i++) { + if (!ndspChnIsPlaying(i)) { + channel = i; + break; + } + } + } + if (channel == -1) { + lua_pushnil(L); + lua_pushstring(L, "no audio channel is currently available"); + return 2; + } + if (channel < 0 || channel > 23) luaL_error(L, "channel number must be between 0 and 23"); + + // Set channel parameters + stopAudio(channel); + ndspChnReset(channel); + ndspChnInitParams(channel); + ndspChnSetMix(channel, audio->mix); + ndspChnSetInterp(channel, audio->interp); + ndspChnSetRate(channel, audio->rate * audio->speed); // maybe hackish way to set a different speed, but it works + ndspChnSetFormat(channel, NDSP_CHANNELS(audio->channels) | NDSP_ENCODING(audio->encoding)); + + // Send & play audio initial data + ndspWaveBuf* waveBuf = calloc(1, sizeof(ndspWaveBuf)); + + waveBuf->data_vaddr = audio->data; + waveBuf->nsamples = audio->chunkNsamples; + waveBuf->looping = (audio->chunkSize < audio->size) ? false : loop; // let ndsp loop the chunk if not streaming + + DSP_FlushDataCache((u32*)audio->data, audio->chunkSize); + + ndspChnWaveBufAdd(channel, waveBuf); + channels[channel] = audio; + + lua_pushinteger(L, channel); + + // Remove last audio stream + if (streaming[channel] != NULL) { + free(streaming[channel]); + streaming[channel] = NULL; + } + + // Stream the rest of the audio + if (audio->chunkSize < audio->size) { + audio_stream* stream = calloc(1, sizeof(audio_stream)); + stream->audio = audio; + stream->loop = loop; + stream->nextWaveBuf = waveBuf; + + // Allocate buffers + if (linearSpaceFree() < audio->chunkSize*2) luaL_error(L, "not enough linear memory available"); + stream->nextData = linearAlloc(audio->chunkSize); + stream->prevData = linearAlloc(audio->chunkSize); + + // Init stream values + if (audio->type == TYPE_OGG) { + stream->currentSection = audio->currentSection; + stream->rawPosition = audio->rawPosition; + } else if (audio->type == TYPE_WAV) stream->filePosition = audio->filePosition; + + streaming[channel] = stream; + } + + return 1; +} + +/*** +Stop playing an audio object. +@function :stop +@tparam[opt] integer channel stop playing the audio on this channel; if `nil` will stop all channels playing this audio. + If the channel is playing another audio object, this function will do nothing. +@treturn integer number of channels where this audio was stopped +*/ +static int audio_object_stop(lua_State *L) { + if (!isAudioInitialized) { + lua_pushinteger(L, 0); + return 1; + } + + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + int channel = luaL_optinteger(L, 2, -1); + + int n = 0; + + if (channel == -1) { + for (int i = 0; i <= 23; i++) { + if (channels[i] == audio && ndspChnIsPlaying(i)) { + stopAudio(i); + n++; + } + } + } else if (channel < 0 || channel > 23) { + luaL_error(L, "channel number must be between 0 and 23"); + } else { + if (channels[channel] == audio && ndspChnIsPlaying(channel)) { + stopAudio(channel); + n++; + } + } + + lua_pushinteger(L, n); + + return 1; +} + +/*** +Returns the audio object type. +@function :type +@treturn string "ogg", "wav" or "raw" +*/ +static int audio_object_type(lua_State *L) { + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + + if (audio->type == TYPE_OGG) + lua_pushstring(L, "ogg"); + else if (audio->type == TYPE_WAV) + lua_pushstring(L, "wav"); + else if (audio->type == TYPE_RAW) + lua_pushstring(L, "raw"); + else + lua_pushstring(L, "unknown"); + + return 1; +} + +/*** +Unload an audio object. +@function :unload +*/ +static int audio_object_unload(lua_State *L) { + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + + // Stop playing the audio + if (isAudioInitialized) { + for (int i = 0; i <= 23; i++) { + if (channels[i] == audio) { + stopAudio(i); + } + } + } + + if (audio->type == TYPE_OGG) ov_clear(&audio->vf); + else if (audio->type == TYPE_WAV) fclose(audio->file); + + // Free memory + linearFree(audio->data); + + return 0; +} + +/*** +audio object (ogg-only). +Ogg Vorbis files specific methods. +Using one of theses methods will throw an error if used on an non-ogg audio object. +@section Methods +*/ + +/*** +Returns basic information about the audio in a vorbis bitstream. +@function :info +@treturn infoTable information table +*/ +static int audio_object_info(lua_State *L) { + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + + if (audio->type != TYPE_OGG) luaL_error(L, "only avaible on OGG audio objects"); + + vorbis_info* vi = ov_info(&audio->vf, -1); + if (vi == NULL) luaL_error(L, "could not retrieve audio stream informations"); + + lua_createtable(L, 0, 6); + + lua_pushinteger(L, vi->version); + lua_setfield(L, -2, "version"); + + lua_pushinteger(L, vi->channels); + lua_setfield(L, -2, "channels"); + + lua_pushinteger(L, vi->rate); + lua_setfield(L, -2, "rate"); + + lua_pushinteger(L, vi->bitrate_upper); + lua_setfield(L, -2, "bitrateUpper"); + + lua_pushinteger(L, vi->bitrate_nominal); + lua_setfield(L, -2, "bitrateNominal"); + + lua_pushinteger(L, vi->bitrate_lower); + lua_setfield(L, -2, "bitrateLower"); + + return 1; +} + +/*** +Returns the Ogg Vorbis bitstream comment. +@function :comment +@treturn commentTable comment table +*/ +static int audio_object_comment(lua_State *L) { + audio_userdata *audio = luaL_checkudata(L, 1, "LAudio"); + + if (audio->type != TYPE_OGG) luaL_error(L, "only avaible on OGG audio objects"); + + vorbis_comment *vc = ov_comment(&audio->vf, -1); + + if (vc == NULL) luaL_error(L, "could not retrieve audio stream comment"); + + lua_createtable(L, 0, 5); + + lua_newtable(L); + for (int i=0; icomments; i++) { + lua_pushstring(L, vc->user_comments[i]); + lua_seti(L, -2, i+1); + } + lua_setfield(L, -2, "userComments"); + + lua_pushstring(L, vc->vendor); + lua_setfield(L, -2, "vendor"); + + return 1; +} + +/*** +Tables return. +The detailled table structures returned by some methods of audio objects. +@section +*/ + +/*** +Vorbis bitstream information, returned by audio:info(). +If bitrateLower == bitrateNominal == bitrateUpper, the stream is fixed bitrate. +@table infoTable +@tfield integer version Vorbis encoder version used to create this bitstream +@tfield integer channels number of channels in bitstream +@tfield integer rate sampling rate of the bitstream +@tfield integer bitrateUpper the upper limit in a VBR bitstream; may be unset if no limit exists +@tfield integer bitrateNominal the average bitrate for a VBR bitstream; may be unset +@tfield integer bitrateLower the lower limit in a VBR bitstream; may be unset if no limit exists +*/ + +/*** +Vorbis bitstream comment, returned by audio:comment(). +@table commentTable +@tfield table userComments list of all the user comment +@tfield string vendor information about the Vorbis implementation that encoded the file +*/ + +// Audio object methods +static const struct luaL_Reg audio_object_methods[] = { + // common + { "duration", audio_object_duration }, + { "time", audio_object_time }, + { "playing", audio_object_playing }, + { "mix", audio_object_mix }, + { "interpolation", audio_object_interpolation }, + { "speed", audio_object_speed }, + { "play", audio_object_play }, + { "stop", audio_object_stop }, + { "type", audio_object_type }, + { "unload", audio_object_unload }, + { "__gc", audio_object_unload }, + // ogg only + { "info", audio_object_info }, + { "comment", audio_object_comment }, + { NULL, NULL } +}; + +// Library functions +static const struct luaL_Reg audio_lib[] = { + { "load", audio_load }, + { "loadRaw", audio_loadRaw }, + { "playing", audio_playing }, + { "mix", audio_mix }, + { "interpolation", audio_interpolation }, + { "speed", audio_speed }, + { "stop", audio_stop }, + { "update", audio_update }, + { NULL, NULL } +}; + +int luaopen_audio_lib(lua_State *L) { + luaL_newmetatable(L, "LAudio"); + lua_pushvalue(L, -1); + lua_setfield(L, -2, "__index"); + luaL_setfuncs(L, audio_object_methods, 0); + + luaL_newlib(L, audio_lib); + + return 1; +} + +void load_audio_lib(lua_State *L) { + if (!isAudioInitialized) isAudioInitialized = !ndspInit(); // ndspInit returns 0 in case of success + + luaL_requiref(L, "ctr.audio", luaopen_audio_lib, false); +} + +void unload_audio_lib(lua_State *L) { + if (isAudioInitialized) ndspExit(); +} diff --git a/source/cam.c b/source/cam.c new file mode 100644 index 0000000..4d756c5 --- /dev/null +++ b/source/cam.c @@ -0,0 +1,754 @@ +/*** +The `cam` module. +@module ctr.cam +@usage local cam = require("ctr.cam") +*/ + +#include <3ds.h> +#include <3ds/types.h> +#include <3ds/svc.h> +#include <3ds/services/cam.h> + +#include + +#include +#include + +#include + +#include "texture.h" + +/*** +Initialize the camera module. +@function init +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code +*/ +static int cam_init(lua_State *L) { + Result ret = camInit(); + if (ret) { + lua_pushboolean(L, false); + lua_pushinteger(L, ret); + return 2; + } + + lua_pushboolean(L, true); + return 1; +} + +/*** +Disable the camera module. +@function shutdown +*/ +static int cam_shutdown(lua_State *L) { + camExit(); + + return 0; +} + +/*** +Activate a camera. +@function activate +@tparam number camera camera to activate (`SELECT_x`) +*/ +static int cam_activate(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + + CAMU_Activate(cam); + + return 0; +} + +/*** +Set the exposure of a camera. +@function setExposure +@tparam number camera (`SELECT_x`) +@tparam number exposure (from `-128` to `127`) +*/ +static int cam_setExposure(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + s8 expo = luaL_checkinteger(L, 2); + + CAMU_SetExposure(cam, expo); + + return 0; +} + +/*** +Set the white balance of a camera. +@function setWhiteBalance +@tparam number camera (`SELECT_x`) +@tparam number white white balance (`WHITE_BALANCE_x`) +*/ +static int cam_setWhiteBalance(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + u8 bal = luaL_checkinteger(L, 2); + + CAMU_SetWhiteBalance(cam, bal); + + return 0; +} + +/*** +Set the sharpness of a camera. +@function setSharpness +@tparam number camera (`SELECT_x`) +@tparam number sharpness from (from `-128` to `127`) +*/ +static int cam_setSharpness(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + s8 sharp = luaL_checkinteger(L, 2); + + CAMU_SetSharpness(cam, sharp); + + return 0; +} + +/*** +Set the auto exposure mode of a camera. +@function setAutoExposure +@tparam number camera (`SELECT_x`) +@tparam boolean auto `true` to enable, `false` to disable +*/ +static int cam_setAutoExposure(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + bool expo = lua_toboolean(L, 2); + + CAMU_SetAutoExposure(cam, expo); + + return 0; +} + +/*** +Check if the auto exposure mode is enabled for a camera. +@function isAutoExposure +@tparam number camera (`SELECT_x`) +@treturn boolean `true` if enabled, `false` if not +*/ +static int cam_isAutoExposure(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + bool expo = false; + + CAMU_IsAutoExposure(&expo, cam); + + lua_pushboolean(L, expo); + return 1; +} + +/*** +Set the auto white balance mode for a camera. +@function setAutoWhiteBalance +@tparam number camera (`SELECT_x`) +@tparam boolean auto `true` to enable, `false` to disable +*/ +static int cam_setAutoWhiteBalance(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + bool bal = lua_toboolean(L, 2); + + CAMU_SetAutoWhiteBalance(cam, bal); + + return 0; +} + +/*** +Check if the auto white balance mode is enabled for a camera. +@function isAutoWhiteBalance +@tparam number camera (`SELECT_x`) +@treturn boolean `true` if enabled, `false` if not +*/ +static int cam_isAutoWhiteBalance(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + bool bal = false; + + CAMU_IsAutoWhiteBalance(&bal, cam); + + lua_pushboolean(L, bal); + return 1; +} + +/*** +Set the contrast on a camera. +@function setContrast +@tparam number camera (`SELECT_x`) +@tparam number contrast (`CONTRAST_x`) +*/ +static int cam_setContrast(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + u8 cont = luaL_checkinteger(L, 2); + + CAMU_SetContrast(cam, cont); + + return 0; +} + +/*** +Set the lens correction of a camera. +@function setLensCorrection +@tparam number camera (`SELECT_x`) +@tparam number correction lens correction (`LENS_CORRECTION_x`) +*/ +static int cam_setLensCorrection(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + u8 corr = luaL_checkinteger(L, 2); + + CAMU_SetLensCorrection(cam, corr); + + return 0; +} + +/*** +Set the window where the exposure will be check. +@function setAutoExposureWindow +@tparam number x x starting position of the window +@tparam number y y starting position of the window +@tparam number w width of the window +@tparam number h height of the window +*/ +static int cam_setAutoExposureWindow(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + s16 x = luaL_checkinteger(L, 2); + s16 y = luaL_checkinteger(L, 3); + s16 w = luaL_checkinteger(L, 4); + s16 h = luaL_checkinteger(L, 5); + + CAMU_SetAutoExposureWindow(cam, x, y, w, h); + + return 0; +} + +/*** +Set the window where the white balance will be check. +@function setAutoWhiteBalanceWindow +@tparam number x x starting position of the window +@tparam number y y starting position of the window +@tparam number w width of the window +@tparam number h height of the window +*/ +static int cam_setAutoWhiteBalanceWindow(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + s16 x = luaL_checkinteger(L, 2); + s16 y = luaL_checkinteger(L, 3); + s16 w = luaL_checkinteger(L, 4); + s16 h = luaL_checkinteger(L, 5); + + CAMU_SetAutoWhiteBalanceWindow(cam, x, y, w, h); + + return 0; +} + +/*** +Enable or disable the noise filter on a camera. +@function setNoiseFilter +@tparam number camera (`SELECT_x`) +@tparam boolean filter `true` to enable, `false` to disable +*/ +static int cam_setNoiseFilter(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + bool fil = lua_toboolean(L, 2); + + CAMU_SetNoiseFilter(cam, fil); + + return 0; +} + +/*** +Play a shutter sound. +@function playShutterSound +@tparam number sound shutter sound type (`SHUTTER_x`) +*/ +static int cam_playShutterSound(lua_State *L) { + u8 shut = luaL_checkinteger(L, 1); + + CAMU_PlayShutterSound(shut); + + return 0; +} + +/*** +Set the size of the base camera image. +@function setSize +@tparam number camera (`SELECT_x`) +@tparam number size (`SIZE_x`) +@tparam number context (`CONTEXT_x`) +*/ +static int cam_setSize(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + u8 size = luaL_checkinteger(L, 2); + u8 context = luaL_checkinteger(L, 3); + + CAMU_SetSize(cam, size, context); + + return 0; +} + +/*** +Set the effect applied on the image. +@function setEffect +@tparam number camera (`SELECT_x`) +@tparam number effect (`EFFECT_x`) +@tparam number context (`CONTEXT_x`) +*/ +static int cam_setEffect(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + u8 effect = luaL_checkinteger(L, 2); + u8 context = luaL_checkinteger(L, 3); + + CAMU_SetEffect(cam, effect, context); + + return 0; +} + +/*** +Set the frame rate of a camera. +@function setFrameRate +@tparam number camera (`SELECT_x`) +@tparam number rate frame rate (`FRAME_RATE_x`) +*/ +static int cam_setFrameRate(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + u8 rate = luaL_checkinteger(L, 2); + + CAMU_SetFrameRate(cam, rate); + + return 0; +} + +/*** +Take a picture and put it in a texture. +@function takePicture +@tparam number camera should be PORT_CAM1 if you have only 1 camera activated (`PORT_x`) +@tparam number w width of the picture +@tparam number h height of the picture +@tparam[opt=PLACE_RAM] number place where to put the texture +@treturn texture the texture object +*/ +static int cam_takePicture(lua_State *L) { + u8 cam = luaL_checkinteger(L, 1); + s16 w = luaL_optinteger(L, 2, 640); + s16 h = luaL_optinteger(L, 3, 480); + u32 bufSize = 0; + + // Take the actual picture + CAMU_GetMaxBytes(&bufSize, w, h); + u8* buf = malloc(bufSize); + CAMU_SetTransferBytes(cam, bufSize, w, h); + + Handle camReceiveEvent = 0; + + CAMU_ClearBuffer(cam); + CAMU_StartCapture(cam); + CAMU_SetReceiving(&camReceiveEvent, buf, cam, bufSize, (s16)bufSize); + svcWaitSynchronization(camReceiveEvent, 300000000ULL); + CAMU_StopCapture(cam); + + // Load it in a texture + u8 place = luaL_optinteger(L, 4, SF2D_PLACE_RAM); + + texture_userdata *texture; + texture = (texture_userdata *)lua_newuserdata(L, sizeof(*texture)); + + luaL_getmetatable(L, "LTexture"); + lua_setmetatable(L, -2); + + texture->texture = sf2d_create_texture_mem_RGBA8(buf, w, h, TEXFMT_RGB565, place); + sf2d_texture_tile32(texture->texture); + + texture->scaleX = 1.0f; + texture->scaleY = 1.0f; + texture->blendColor = 0xffffffff; + + return 1; +} + +// Functions +static const struct luaL_Reg cam_lib[] = { + {"init", cam_init }, + {"shutdown", cam_shutdown }, + {"activate", cam_activate }, + {"setExposure", cam_setExposure }, + {"setWhiteBalance", cam_setWhiteBalance }, + {"setSharpness", cam_setSharpness }, + {"setAutoExposure", cam_setAutoExposure }, + {"isAutoExposure", cam_isAutoExposure }, + {"setAutoWhiteBalance", cam_setAutoWhiteBalance }, + {"isAutoWhiteBalance", cam_isAutoWhiteBalance }, + {"setContrast", cam_setContrast }, + {"setLensCorrection", cam_setLensCorrection }, + {"setAutoExposureWindow", cam_setAutoExposureWindow }, + {"setAutoWhiteBalanceWindow", cam_setAutoWhiteBalanceWindow}, + {"setNoiseFilter", cam_setNoiseFilter }, + {"playShutterSound", cam_playShutterSound }, + {"setSize", cam_setSize }, + {"setEffect", cam_setEffect }, + {"setFrameRate", cam_setFrameRate }, + {"takePicture", cam_takePicture }, + {NULL, NULL} +}; + +struct { char *name; int value; } cam_constants[] = { + /*** + First camera activated. + @field PORT_CAM1 + */ + {"PORT_CAM1", PORT_CAM1}, + /*** + Second camera activated. + @field PORT_CAM2 + */ + {"PORT_CAM2", PORT_CAM2}, + /*** + The two activated camera. Should not be used ATM. + @field PORT_BOTH + */ + {"PORT_BOTH", PORT_BOTH}, + /*** + @field SELECT_NONE + */ + {"SELECT_NONE", SELECT_NONE }, + /*** + @field SELECT_OUT1 + */ + {"SELECT_OUT1", SELECT_OUT1 }, + /*** + @field SELECT_IN1 + */ + {"SELECT_IN1", SELECT_IN1 }, + /*** + @field SELECT_OUT2 + */ + {"SELECT_OUT2", SELECT_OUT2 }, + /*** + @field SELECT_IN1_OUT1 + */ + {"SELECT_IN1_OUT1", SELECT_IN1_OUT1 }, + /*** + @field SELECT_OUT1_OUT2 + */ + {"SELECT_OUT1_OUT2", SELECT_OUT1_OUT2}, + /*** + @field SELECT_IN1_OUT2 + */ + {"SELECT_IN1_OUT2", SELECT_IN1_OUT2 }, + /*** + @field SELECT_ALL + */ + {"SELECT_ALL", SELECT_ALL }, + /*** + @field CONTEXT_NONE + */ + {"CONTEXT_NONE", CONTEXT_NONE}, + /*** + @field CONTEXT_A + */ + {"CONTEXT_A", CONTEXT_A }, + /*** + @field CONTEXT_B + */ + {"CONTEXT_B", CONTEXT_B }, + /*** + @field CONTEXT_BOTH + */ + {"CONTEXT_BOTH", CONTEXT_BOTH}, + /*** + @field FLIP_NONE + */ + {"FLIP_NONE", FLIP_NONE }, + /*** + @field FLIP_HORIZONTAL + */ + {"FLIP_HORIZONTAL", FLIP_HORIZONTAL}, + /*** + @field FLIP_VERTICAL + */ + {"FLIP_VERTICAL", FLIP_VERTICAL }, + /*** + @field FLIP_REVERSE + */ + {"FLIP_REVERSE", FLIP_REVERSE }, + /*** + 640x480 + @field SIZE_VGA + */ + {"SIZE_VGA", SIZE_VGA }, + /*** + 320x240 + @field SIZE_QVGA + */ + {"SIZE_QVGA", SIZE_QVGA }, + /*** + 160x120 + @field SIZE_QQVGA + */ + {"SIZE_QQVGA", SIZE_QQVGA }, + /*** + 352x288 + @field SIZE_CIF + */ + {"SIZE_CIF", SIZE_CIF }, + /*** + 176x144 + @field SIZE_QCIF + */ + {"SIZE_QCIF", SIZE_QCIF }, + /*** + 256x192 + @field SIZE_DS_LCD + */ + {"SIZE_DS_LCD", SIZE_DS_LCD }, + /*** + 512x384 + @field SIZE_DS_LCDx4 + */ + {"SIZE_DS_LCDx4", SIZE_DS_LCDx4 }, + /*** + 400x240 + @field SIZE_CTR_TOP_LCD + */ + {"SIZE_CTR_TOP_LCD", SIZE_CTR_TOP_LCD }, + /*** + 320x240 + @field SIZE_BOTTOM_LCD + */ + {"SIZE_CTR_BOTTOM_LCD", SIZE_CTR_BOTTOM_LCD}, + /*** + @field FRAME_RATE_15 + */ + {"FRAME_RATE_15", FRAME_RATE_15 }, + /*** + @field FRAME_RATE_15_TO_5 + */ + {"FRAME_RATE_15_TO_5", FRAME_RATE_15_TO_5 }, + /*** + @field FRAME_RATE_15_TO_2 + */ + {"FRAME_RATE_15_To_2", FRAME_RATE_15_TO_2 }, + /*** + @field FRAME_RATE_10 + */ + {"FRAME_RATE_10", FRAME_RATE_10 }, + /*** + @field FRAME_RATE_8_5 + */ + {"FRAME_RATE_8_5", FRAME_RATE_8_5 }, + /*** + @field FRAME_RATE_5 + */ + {"FRAME_RATE_5", FRAME_RATE_5 }, + /*** + @field FRAME_RATE_20 + */ + {"FRAME_RATE_20", FRAME_RATE_20 }, + /*** + @field FRAME_RATE_20_TO_5 + */ + {"FRAME_RATE_20_TO_5", FRAME_RATE_20_TO_5 }, + /*** + @field FRAME_RATE_30 + */ + {"FRAME_RATE_30", FRAME_RATE_30 }, + /*** + @field FRAME_RATE_TO_5 + */ + {"FRAME_RATE_30_TO_5", FRAME_RATE_30_TO_5 }, + /*** + @field FRAME_RATE_15_TO_10 + */ + {"FRAME_RATE_15_TO_10", FRAME_RATE_15_TO_10}, + /*** + @field FRAME_RATE_20_TO_10 + */ + {"FRAME_RATE_20_TO_10", FRAME_RATE_20_TO_10}, + /*** + @field FRAME_RATE_30_TO_10 + */ + {"FRAME_RATE_30_TO_10", FRAME_RATE_30_TO_10}, + /*** + @field WHITe_BALANCE_AUTO + */ + {"WHITE_BALANCE_AUTO", WHITE_BALANCE_AUTO }, + /*** + @field WHITE_BALANCE_3200K + */ + {"WHITE_BALANCE_3200K", WHITE_BALANCE_3200K}, + /*** + @field WHITE_BALANCE_4150K + */ + {"WHITE_BALANCE_4150K", WHITE_BALANCE_4150K}, + /*** + @field WHITE_BALANCE_5200K + */ + {"WHITE_BALANCE_5200K", WHITE_BALANCE_5200K}, + /*** + @field WHITE_BALANCE_6000K + */ + {"WHITE_BALANCE_6000K", WHITE_BALANCE_6000K}, + /*** + @field WHITE_BALANCE_7000K + */ + {"WHITE_BALANCE_7000K", WHITE_BALANCE_7000K}, + /*** + @field WHITE_BALANCE_TUNGSTEN + */ + {"WHITE_BALANCE_TUNGSTEN", WHITE_BALANCE_TUNGSTEN }, + /*** + @field WHITE_BALANCE_WHITE_FLUORESCENT_LIGHT + */ + {"WHITE_BALANCE_WHITE_FLUORESCENT_LIGHT", WHITE_BALANCE_WHITE_FLUORESCENT_LIGHT}, + /*** + @field WHITE_BALANCE_DAYLIGHT + */ + {"WHITE_BALANCE_DAYLIGHT", WHITE_BALANCE_DAYLIGHT }, + /*** + @field WHITE_BALANCE_CLOUDY + */ + {"WHITE_BALANCE_CLOUDY", WHITE_BALANCE_CLOUDY }, + /*** + @field WHITE_BALANCE_HORIZON + */ + {"WHITE_BALANCE_HORIZON", WHITE_BALANCE_HORIZON }, + /*** + @field WHITE_BALANCE_SHADE + */ + {"WHITE_BALANCE_SHADE", WHITE_BALANCE_SHADE }, + /*** + @field PHOTO_MODE_NORMAL + */ + {"PHOTO_MODE_NORMAL", PHOTO_MODE_NORMAL }, + /*** + @field PHOTO_MODE_PORTRAIT + */ + {"PHOTO_MODE_PORTRAIT", PHOTO_MODE_PORTRAIT }, + /*** + @field PHOTO_MODE_LANDSCAPE + */ + {"PHOTO_MODE_LANDSCAPE", PHOTO_MODE_LANDSCAPE}, + /*** + @field PHOTO_MODE_NIGHTVIEW + */ + {"PHOTO_MODE_NIGHTVIEW", PHOTO_MODE_NIGHTVIEW}, + /*** + @field PHOTO_MODE_LETTER + */ + {"PHOTO_MODE_LETTER", PHOTO_MODE_LETTER }, + /*** + @field EFFECT_NONE + */ + {"EFFECT_NONE", EFFECT_NONE }, + /*** + @field EFFECT_MONO + */ + {"EFFECT_MONO", EFFECT_MONO }, + /*** + @field EFFECT_SEPIA + */ + {"EFFECT_SEPIA", EFFECT_SEPIA }, + /*** + @field EFFECT_NEGATIVE + */ + {"EFFECT_NEGATIVE", EFFECT_NEGATIVE}, + /*** + @field EFFECT_NEGAFILM + */ + {"EFFECT_NEGAFILM", EFFECT_NEGAFILM}, + /*** + @field EFFECT_SEPIA01 + */ + {"EFFECT_SEPIA01", EFFECT_SEPIA01 }, + /*** + @field CONTRAST_01 + */ + {"CONTRAST_01", CONTRAST_PATTERN_01}, + /*** + @field CONTRAST_02 + */ + {"CONTRAST_02", CONTRAST_PATTERN_02}, + /*** + @field CONTRAST_03 + */ + {"CONTRAST_03", CONTRAST_PATTERN_03}, + /*** + @field CONTRAST_04 + */ + {"CONTRAST_04", CONTRAST_PATTERN_04}, + /*** + @field CONTRAST_05 + */ + {"CONTRAST_05", CONTRAST_PATTERN_05}, + /*** + @field CONTRAST_06 + */ + {"CONTRAST_06", CONTRAST_PATTERN_06}, + /*** + @field CONTRAST_07 + */ + {"CONTRAST_07", CONTRAST_PATTERN_07}, + /*** + @field CONTRAST_08 + */ + {"CONTRAST_08", CONTRAST_PATTERN_08}, + /*** + @field CONTRAST_09 + */ + {"CONTRAST_09", CONTRAST_PATTERN_09}, + /*** + @field CONTRAST_10 + */ + {"CONTRAST_10", CONTRAST_PATTERN_10}, + /*** + @field CONTRAST_11 + */ + {"CONTRAST_11", CONTRAST_PATTERN_11}, + /*** + @field CONTRAST_LOW + */ + {"CONTRAST_LOW", CONTRAST_LOW }, + /*** + @field CONTRAST_NORMAL + */ + {"CONTRAST_NORMAL", CONTRAST_NORMAL }, + /*** + @field CONTRAST_HIGH + */ + {"CONTRAST_HIGH", CONTRAST_HIGH }, + /*** + @field LENS_CORRECTION_OFF + */ + {"LENS_CORRECTION_OFF", LENS_CORRECTION_OFF }, + /*** + @field LENS_CORRECTION_NORMAL + */ + {"LENS_CORRECTION_NORMAL", LENS_CORRECTION_NORMAL}, + /*** + @field LENS_CORRECTION_BRIGHT + */ + {"LENS_CORRECTION_BRIGHT", LENS_CORRECTION_BRIGHT}, + /*** + @field SHUTTER_NORMAL + */ + {"SHUTTER_NORMAL", SHUTTER_SOUND_TYPE_NORMAL }, + /*** + @field SHUTTER_MOVIE + */ + {"SHUTTER_MOVIE", SHUTTER_SOUND_TYPE_MOVIE }, + /*** + @field SHUTTER_MOVIE_END + */ + {"SHUTTER_MOVIE_END", SHUTTER_SOUND_TYPE_MOVIE_END}, + {NULL, 0} +}; + +int luaopen_cam_lib(lua_State *L) { + luaL_newlib(L, cam_lib); + + for (int i = 0; cam_constants[i].name; i++) { + lua_pushinteger(L, cam_constants[i].value); + lua_setfield(L, -2, cam_constants[i].name); + } + + return 1; +} + +void load_cam_lib(lua_State *L) { + luaL_requiref(L, "ctr.cam", luaopen_cam_lib, false); +} diff --git a/source/cfgu.c b/source/cfgu.c index 57829d0..c31a8af 100644 --- a/source/cfgu.c +++ b/source/cfgu.c @@ -14,13 +14,17 @@ Used to get some user config. #include #include +bool initStateCFGU = false; + /*** Initialize the CFGU module. @function init */ static int cfgu_init(lua_State *L) { - initCfgu(); - + if (!initStateCFGU) { + cfguInit(); + initStateCFGU = true; + } return 0; } @@ -29,8 +33,10 @@ Disable the CFGU module. @function shutdown */ static int cfgu_shutdown(lua_State *L) { - exitCfgu(); - + if (initStateCFGU) { + cfguExit(); + initStateCFGU = false; + } return 0; } @@ -103,9 +109,13 @@ static int cfgu_getUsername(lua_State *L) { CFGU_GetConfigInfoBlk2(0x1C, 0xA0000, (u8*)block); u8 *name = malloc(0x14); - utf16_to_utf8(name, block, 0x14); + ssize_t len = utf16_to_utf8(name, block, 0x14); + if (len < 0) { + lua_pushstring(L, ""); + return 1; + } - lua_pushlstring(L, (const char *)name, 0x14); // The username is only 0x14 characters long. + lua_pushlstring(L, (const char *)name, len); // The username is only 0x14 characters long. return 1; } @@ -215,7 +225,7 @@ struct { char *name; int value; } cfgu_constants[] = { /*** Constant returned by `getLanguage` if the language is Italian. It is equal to `4`. - @field LANGUAGE_JP + @field LANGUAGE_IT */ {"LANGUAGE_IT", CFG_LANGUAGE_IT}, /*** @@ -276,7 +286,7 @@ struct { char *name; int value; } cfgu_constants[] = { /*** Constant returned by `getModel` if the console is a New 3DS. It is equal to `2`. - @field MODEL_3DSXL + @field MODEL_N3DS */ {"MODEL_N3DS", 2}, /*** @@ -290,7 +300,7 @@ struct { char *name; int value; } cfgu_constants[] = { It is equal to `4`. @field MODEL_N3DSXL */ - {"MOdEL_N3DSXL", 4}, + {"MODEL_N3DSXL", 4}, {NULL, 0} }; @@ -309,3 +319,10 @@ int luaopen_cfgu_lib(lua_State *L) { void load_cfgu_lib(lua_State *L) { luaL_requiref(L, "ctr.cfgu", luaopen_cfgu_lib, false); } + +void unload_cfgu_lib(lua_State *L) { + if (initStateCFGU) { + initStateCFGU = false; + cfguExit(); + } +} diff --git a/source/color.c b/source/color.c index bb27e80..41d809e 100644 --- a/source/color.c +++ b/source/color.c @@ -1,3 +1,8 @@ +/*** +The `gfx.color` module +@module ctr.gfx.color +@usage local color = require("ctr.gfx.color") +*/ #include #include @@ -6,18 +11,33 @@ u32 color_default = RGBA8(255, 255, 255, 255); u32 color_background = RGBA8(0, 0, 0, 255); +/*** +Set a color as the default one. +@function setDefault +@tparam integer color the color to set as the default one. +*/ static int color_setDefault(lua_State *L) { color_default = luaL_checkinteger(L, 1); return 0; } +/*** +Return the default color. +@function getDefault +@treturn integer default color +*/ static int color_getDefault(lua_State *L) { lua_pushinteger(L, color_default); return 1; } +/*** +Set a color as the background one. +@function setBackground +@tparam integer color the color to set as the background one. +*/ static int color_setBackground(lua_State *L) { color_background = luaL_checkinteger(L, 1); sf2d_set_clear_color(color_background); @@ -25,12 +45,26 @@ static int color_setBackground(lua_State *L) { return 0; } +/*** +Return the background color. +@function getBackground +@treturn integer background color +*/ static int color_getBackground(lua_State *L) { lua_pushinteger(L, color_background); return 1; } +/*** +Return a color from red, green, blue and alpha values. +@function RGBA8 +@tparam integer r the red value (0-255) +@tparam integer g the green value (0-255) +@tparam integer b the blue value (0-255) +@tparam[opt=255] integer a the alpha (opacity) value (0-255) +@treturn integer the color +*/ static int color_RGBA8(lua_State *L) { int r = luaL_checkinteger(L, 1); int g = luaL_checkinteger(L, 2); @@ -42,12 +76,32 @@ static int color_RGBA8(lua_State *L) { return 1; } +/*** +Return a color from a hexadecimal value. +@function hex +@tparam integer hex the hexadecimal color code: 0xRRGGBBAA +@treturn integer the color +*/ +static int color_hex(lua_State *L) { + u32 hex = luaL_checkinteger(L, 1); + + u8 r = (hex & 0xFF000000) >> 24; + u8 g = (hex & 0x00FF0000) >> 16; + u8 b = (hex & 0x0000FF00) >> 8; + u8 a = (hex & 0x000000FF); + + lua_pushinteger(L, RGBA8(r, g, b, a)); + + return 1; +} + static const struct luaL_Reg color_lib[] = { { "setDefault", color_setDefault }, { "getDefault", color_getDefault }, { "setBackground", color_setBackground }, { "getBackground", color_getBackground }, { "RGBA8", color_RGBA8 }, + { "hex", color_hex }, { NULL, NULL } }; @@ -58,4 +112,4 @@ int luaopen_color_lib(lua_State *L) { void load_color_lib(lua_State *L) { luaL_requiref(L, "ctr.gfx.color", luaopen_color_lib, false); -} \ No newline at end of file +} diff --git a/source/ctr.c b/source/ctr.c index b046636..62e1a38 100644 --- a/source/ctr.c +++ b/source/ctr.c @@ -3,9 +3,13 @@ The `ctr` module. @module ctr @usage local ctr = require("ctr") */ +#include +#include + #include <3ds/types.h> #include <3ds/services/apt.h> #include <3ds/os.h> +#include <3ds/svc.h> #include #include @@ -24,6 +28,7 @@ The `ctr.news` module. @see ctr.news */ void load_news_lib(lua_State *L); +void unload_news_lib(lua_State *L); /*** The `ctr.ptm` module. @@ -31,6 +36,7 @@ The `ctr.ptm` module. @see ctr.ptm */ void load_ptm_lib(lua_State *L); +void unload_ptm_lib(lua_State *L); /*** The `ctr.hid` module. @@ -76,6 +82,7 @@ The `ctr.cfgu` module. @see ctr.cfgu */ void load_cfgu_lib(lua_State *L); +void unload_cfgu_lib(lua_State *L); /*** The `ctr.socket` module. @@ -84,7 +91,50 @@ The `ctr.socket` module. */ void load_socket_lib(lua_State *L); -//void load_cam_lib(lua_State *L); +/*** +The `ctr.cam` module. +@table cam +@see ctr.cam +*/ +void load_cam_lib(lua_State *L); + +/*** +The `ctr.audio` module. +@table audio +@see ctr.audio +*/ +void load_audio_lib(lua_State *L); +void unload_audio_lib(lua_State *L); + +/*** +The `ctr.apt` module. +@table apt +@see ctr.apt +*/ +void load_apt_lib(lua_State *L); +void unload_apt_lib(lua_State *L); + +/*** +The `ctr.mic` module. +@table mic +@see ctr.mic +*/ +void load_mic_lib(lua_State *L); + +/*** +The `ctr.thread` module. +@table thread +@see ctr.thread +*/ +void load_thread_lib(lua_State *L); + +/*** +The `ctr.uds` module. +@table uds +@see ctr.uds +*/ +void load_uds_lib(lua_State *L); +void unload_uds_lib(lua_State *L); /*** Return whether or not the program should continue. @@ -98,37 +148,66 @@ static int ctr_run(lua_State *L) { } /*** -Return the number of milliseconds since 1st Jan 1900 00:00. +Return the number of milliseconds spent since some point in time. +This can be used to measure a duration with milliseconds precision; however this can't be used to get the current time or date. +See Lua's os.date() for this use. +For various reasons (see the C source), this will actually returns a negative value. @function time @treturn number milliseconds +@usage +-- Measuring a duration: +local startTime = ctr.time() +-- do stuff +local duration = ctr.time() - startTime */ static int ctr_time(lua_State *L) { + // osGetTime actually returns the number of seconds elapsed since 1st Jan 1900 00:00. + // However, it returns a u64, we build Lua with 32bits numbers, and every number is signed in Lua, so this obvioulsy doesn't work + // and actually returns a negative value. It still works for durations however. Because having the date and time with millisecond-presion + // doesn't really seem useful and changing ctrµLua's API to work on 64bits numbers will take a long time, we choosed to keep this as-is. lua_pushinteger(L, osGetTime()); return 1; } +/*** +Return a number of microseconds based on the system ticks. +@function utime +@treturn number microseconds +*/ +static int ctr_utime(lua_State *L) { + lua_pushinteger(L, svcGetSystemTick()/268.123480); + + return 1; +} + // Functions static const struct luaL_Reg ctr_lib[] = { - { "run", ctr_run }, - { "time", ctr_time}, + { "run", ctr_run }, + { "time", ctr_time }, + { "utime", ctr_utime}, { NULL, NULL } }; // Subtables struct { char *name; void (*load)(lua_State *L); void (*unload)(lua_State *L); } ctr_libs[] = { { "gfx", load_gfx_lib, unload_gfx_lib }, - { "news", load_news_lib, NULL }, - { "ptm", load_ptm_lib, NULL }, + { "news", load_news_lib, unload_news_lib }, + { "ptm", load_ptm_lib, unload_ptm_lib }, { "hid", load_hid_lib, unload_hid_lib }, { "ir", load_ir_lib, NULL }, { "fs", load_fs_lib, unload_fs_lib }, { "httpc", load_httpc_lib, unload_httpc_lib }, { "qtm", load_qtm_lib, NULL }, - { "cfgu", load_cfgu_lib, NULL }, + { "cfgu", load_cfgu_lib, unload_cfgu_lib }, { "socket", load_socket_lib, NULL }, -// { "cam", load_cam_lib, NULL }, - { NULL, NULL } + { "cam", load_cam_lib, NULL }, + { "audio", load_audio_lib, unload_audio_lib }, + { "apt", load_apt_lib, unload_apt_lib }, + { "mic", load_mic_lib, NULL }, + { "thread", load_thread_lib, NULL }, + { "uds", load_uds_lib, unload_uds_lib }, + { NULL, NULL, NULL } }; int luaopen_ctr_lib(lua_State *L) { @@ -138,6 +217,33 @@ int luaopen_ctr_lib(lua_State *L) { ctr_libs[i].load(L); lua_setfield(L, -2, ctr_libs[i].name); } + + /*** + Running version of ctrµLua. This string contains the exact name of the last (pre-)release tag. + @field version + */ + lua_pushstring(L, CTR_VERSION); + lua_setfield(L, -2, "version"); + /*** + Running build of ctrµLua. This string contains the last commit hash. + @field build + */ + lua_pushstring(L, CTR_BUILD); + lua_setfield(L, -2, "build"); + + /*** + Root directory of ctrµLua. Contains the working directory where ctrµLua has been launched OR the romfs root if romfs has been enabled. + @field root + */ + #ifdef ROMFS + char* buff = "romfs:/"; + chdir(buff); + #else + char* buff = malloc(1024); + getcwd(buff, 1024); + #endif + lua_pushstring(L, buff); + lua_setfield(L, -2, "root"); return 1; } diff --git a/source/font.c b/source/font.c index be75d45..615b299 100644 --- a/source/font.c +++ b/source/font.c @@ -1,5 +1,5 @@ /*** -The `font` module +The `gfx.font` module @module ctr.gfx.font @usage local font = require("ctr.gfx.font") */ @@ -15,11 +15,16 @@ The `font` module #include "font.h" +u32 textSize = 9; + /*** -Load a TTF font. +Load a font. Supported formats: TTF, OTF, TTC, OTC, WOFF, PFA, PFB, PCF, FNT, BDF, PFR, and others. +ctrµLua support all formats supported by FreeType. See here for a more complete list: http://freetype.org/freetype2/docs/index.html @function load @tparam string path path to the file -@treturn font the loaded font. +@treturn[1] font the loaded font. +@treturn[2] nil if an error occurred +@treturn[2] string error message */ static int font_load(lua_State *L) { const char *path = luaL_checkstring(L, 1); @@ -70,6 +75,28 @@ static int font_getDefault(lua_State *L) { return 1; } +/*** +Set the default text size. +@function setSize +@tparam number size new default text size +*/ +static int font_setSize(lua_State *L) { + textSize = luaL_checkinteger(L, 1); + + return 0; +} + +/*** +Return the default text size. +@function getSize +@treturn number the default text size +*/ +static int font_getSize(lua_State *L) { + lua_pushinteger(L, textSize); + + return 1; +} + /*** font object @section Methods @@ -79,6 +106,7 @@ font object Return the width of a string with a font. @function :width @tparam string text the text to test +@tparam[opt=default size] integer font size, in pixels @treturn number the width of the text (in pixels) */ static int font_object_width(lua_State *L) { @@ -91,11 +119,11 @@ static int font_object_width(lua_State *L) { int size = luaL_optinteger(L, 3, 9); // Wide caracters support. (wchar = UTF32 on 3DS.) - wchar_t wtext[len]; + wchar_t wtext[len+1]; len = mbstowcs(wtext, text, len); *(wtext+len) = 0x0; // text end - lua_pushinteger(L, sftd_width_wtext(font->font, size, wtext)); + lua_pushinteger(L, sftd_get_wtext_width(font->font, size, wtext)); return 1; } @@ -127,6 +155,8 @@ static const struct luaL_Reg font_lib[] = { { "load", font_load }, { "setDefault", font_setDefault }, { "getDefault", font_getDefault }, + { "setSize", font_setSize }, + { "getSize", font_getSize }, { NULL, NULL } }; @@ -160,4 +190,6 @@ void unload_font_lib(lua_State *L) { if (luaL_testudata(L, -1, "LFont") != NULL) sftd_free_font(((font_userdata *)lua_touserdata(L, -1))->font); // Unload current font + + lua_pop(L, 1); } diff --git a/source/font.h b/source/font.h index 888176c..2dc87ad 100644 --- a/source/font.h +++ b/source/font.h @@ -5,4 +5,6 @@ typedef struct { sftd_font *font; } font_userdata; +extern u32 textSize; + #endif diff --git a/source/fs.c b/source/fs.c index 576ec48..bc08fdd 100644 --- a/source/fs.c +++ b/source/fs.c @@ -1,99 +1,182 @@ +/*** +The `fs` module. +@module ctr.fs +@usage local fs = require("ctr.fs") +*/ +#include #include +#include +#include +#include +#include #include <3ds/types.h> #include <3ds/util/utf.h> #include <3ds/services/fs.h> +#include <3ds/sdmc.h> +#include <3ds/romfs.h> #include #include -Handle *fsuHandle; -FS_archive sdmcArchive; -#ifdef ROMFS -FS_archive romfsArchive; -#endif +bool isFsInitialized = false; +/*** +The `ctr.fs.lzlib` module. +@table lzlib +@see ctr.fs.lzlib +*/ void load_lzlib(lua_State *L); +/* +Automatically prefix the path if it's absolute (starts with /) +*/ +const char* prefix_path(const char* path) { + if (strncmp(path, "/", 1) == 0) { + #ifdef ROMFS + char* prefix = "romfs:"; + #else + char* prefix = "sdmc:"; + #endif + + char out[1024]; + strcpy(out, prefix); + return strcat(out, path); + + } else { + return path; + } +} + +/*** +Lists a directory contents (unsorted). +@function list +@tparam string path the directory we wants to list the content +@treturn[1] table the item list. Each item is a table like: +` + { + name = "Item name.txt", + isDirectory = false, + size = 321 -- (integer) item size, in bytes + } +` +@treturn[2] nil if an error occurred +@treturn[2] string error message +*/ static int fs_list(lua_State *L) { - const char *path = luaL_checkstring(L, 1); + const char* basepath = prefix_path(luaL_checkstring(L, 1)); + char* path; + bool shouldFreePath = false; + if (basepath[strlen(basepath)-1] != '/') { + path = malloc(strlen(basepath)+2); + strcpy(path, basepath); + strcat(path, "/"); + shouldFreePath = true; + } else { + path = (char*)basepath; + } lua_newtable(L); int i = 1; // table index - - FS_path dirPath = FS_makePath(PATH_CHAR, path); - - Handle dirHandle; - FSUSER_OpenDirectory(fsuHandle, &dirHandle, sdmcArchive, dirPath); - - u32 entriesRead = 0; - do { - FS_dirent buffer; - - FSDIR_Read(dirHandle, &entriesRead, 1, &buffer); - - if (!entriesRead) break; - - uint8_t name[256]; // utf8 file name - size_t size = utf16_to_utf8(name, buffer.name, 0x106); - *(name+size) = 0x0; // mark text end - - lua_createtable(L, 0, 8); - - lua_pushstring(L, (const char *)name); + + DIR* dir = opendir(path); + if (dir == NULL) { + if (shouldFreePath) free(path); + lua_pushnil(L); + lua_pushfstring(L, "Can't open directory: %s (%s)", strerror(errno), errno); + return 2; + } + errno = 0; + struct dirent *entry; + while (((entry = readdir(dir)) != NULL) && !errno) { + lua_createtable(L, 0, 3); + + lua_pushstring(L, (const char*)entry->d_name); lua_setfield(L, -2, "name"); - lua_pushstring(L, (const char *)buffer.shortName); - lua_setfield(L, -2, "shortName"); - lua_pushstring(L, (const char *)buffer.shortExt); - lua_setfield(L, -2, "shortExt"); - lua_pushboolean(L, buffer.isDirectory); + lua_pushboolean(L, entry->d_type==DT_DIR); lua_setfield(L, -2, "isDirectory"); - lua_pushboolean(L, buffer.isHidden); - lua_setfield(L, -2, "isHidden"); - lua_pushboolean(L, buffer.isArchive); - lua_setfield(L, -2, "isArchive"); - lua_pushboolean(L, buffer.isReadOnly); - lua_setfield(L, -2, "isReadOnly"); - lua_pushinteger(L, buffer.fileSize); - lua_setfield(L, -2, "fileSize"); + + if (entry->d_type==DT_REG) { // Regular files: check size + char* filepath = malloc(strlen(path)+strlen(entry->d_name)+1); + if (filepath == NULL) + luaL_error(L, "Memory allocation error"); + strcpy(filepath, path); + strcat(filepath, entry->d_name); + + struct stat stats; + if (stat(filepath, &stats)) { + free(filepath); + if (shouldFreePath) free(path); + luaL_error(L, "Stat error: %s (%d)", strerror(errno), errno); + return 0; + } else { + lua_pushinteger(L, stats.st_size); + } + free(filepath); + } else { // Everything else: 0 bytes + lua_pushinteger(L, 0); + } + lua_setfield(L, -2, "size"); lua_seti(L, -2, i); i++; - - } while (entriesRead > 0); - - FSDIR_Close(dirHandle); + } + + closedir(dir); + if (shouldFreePath) free(path); return 1; } +/*** +Check if a item (file or directory) exists. +@function exists +@tparam string path the item +@treturn boolean true if it exists, false otherwise +*/ static int fs_exists(lua_State *L) { - const char *path = luaL_checkstring(L, 1); + const char *path = prefix_path(luaL_checkstring(L, 1)); lua_pushboolean(L, access(path, F_OK) == 0); return 1; } +/*** +Get the current working directory. +@function getDirectory +@treturn string the current working directory +*/ static int fs_getDirectory(lua_State *L) { - char cwd[256]; + char cwd[1024]; - lua_pushstring(L, getcwd(cwd, 256)); + lua_pushstring(L, getcwd(cwd, 1024)); return 1; } +/*** +Set the current working directory. +@function setDirectory +@tparam path path of the new working directory +@treturn[1] boolean true if success +@treturn[2] boolean false if failed +@treturn[2] string error message +*/ static int fs_setDirectory(lua_State *L) { - const char *path = luaL_checkstring(L, 1); + const char *path = prefix_path(luaL_checkstring(L, 1)); int result = chdir(path); - if (result == 0) + if (result == 0) { lua_pushboolean(L, true); - else - lua_pushboolean(L, false); + return 1; - return 1; + } else { + lua_pushboolean(L, false); + lua_pushstring(L, strerror(errno)); + return 2; + } } static const struct luaL_Reg fs_lib[] = { @@ -106,7 +189,7 @@ static const struct luaL_Reg fs_lib[] = { // submodules struct { char *name; void (*load)(lua_State *L); void (*unload)(lua_State *L); } fs_libs[] = { - {"zip", load_lzlib, NULL}, + {"lzlib", load_lzlib, NULL}, {NULL, NULL} }; @@ -122,26 +205,20 @@ int luaopen_fs_lib(lua_State *L) { } void load_fs_lib(lua_State *L) { - fsInit(); - - fsuHandle = fsGetSessionHandle(); - FSUSER_Initialize(fsuHandle); - - sdmcArchive = (FS_archive){ARCH_SDMC, FS_makePath(PATH_EMPTY, "")}; - FSUSER_OpenArchive(fsuHandle, &sdmcArchive); - #ifdef ROMFS - romfsArchive = (FS_archive){ARCH_ROMFS, FS_makePath(PATH_EMPTY, "")}; - FSUSER_OpenArchive(fsuHandle, &romfsArchive); - #endif - + if (!isFsInitialized) { + sdmcInit(); + #ifdef ROMFS + romfsInit(); + #endif + isFsInitialized = true; + } + luaL_requiref(L, "ctr.fs", luaopen_fs_lib, false); } void unload_fs_lib(lua_State *L) { - FSUSER_CloseArchive(fsuHandle, &sdmcArchive); + sdmcExit(); #ifdef ROMFS - FSUSER_CloseArchive(fsuHandle, &romfsArchive); + romfsExit(); #endif - - fsExit(); } diff --git a/source/gfx.c b/source/gfx.c index c43be37..bf9dc8d 100644 --- a/source/gfx.c +++ b/source/gfx.c @@ -4,21 +4,45 @@ The `gfx` module. @usage local gfx = require("ctr.gfx") */ #include +#include +#include #include #include -#include <3ds/vram.h> -#include <3ds/services/gsp.h> +//#include <3ds/vram.h> +//#include <3ds/services/gsp.h> +#include <3ds/console.h> #include #include +#include "gfx.h" #include "font.h" +#include "texture.h" -bool isGfxInitialised = false; +typedef struct { + sf2d_rendertarget *target; +} target_userdata; + +bool isGfxInitialized = false; bool is3DEnabled = false; //TODO: add a function for this in the ctrulib/sf2dlib. +// The scissor-test state, as defined in Lua code. When you apply a new scissor in C, remember to get back to this state to avoid unexpected behaviour. +scissor_state lua_scissor = { + GPU_SCISSOR_DISABLE, + 0, 0, + 0, 0 +}; + +// Rotate a point (x,y) around the center (cx,cy) by angle radians. +void rotatePoint(int x, int y, int cx, int cy, float angle, int* outx, int* outy) { + float s = sin(angle), c = cos(angle); + int tx = x - cx, ty = y - cy; + *outx = round(tx * c - ty * s) + cx; + *outy = round(tx * s + ty * c) + cy; +} + /*** The `ctr.gfx.color` module. @table color @@ -50,17 +74,23 @@ The `ctr.gfx.map` module. void load_map_lib(lua_State *L); /*** -Start drawing to a screen. +Start drawing to a screen/target. Must be called before any draw operation. -@function startFrame -@tparam number screen the screen to draw to (`GFX_TOP` or `GFX_BOTTOM`) -@tparam[opt=GFX_LEFT] number eye the eye to draw to (`GFX_LEFT` or `GFX_RIGHT`) +@function start +@tparam number/target screen the screen or target to draw to (`gfx.TOP`, `gfx.BOTTOM`, or render target) +@tparam[opt=gfx.LEFT] number eye the eye to draw to (`gfx.LEFT` or `gfx.RIGHT`) */ -static int gfx_startFrame(lua_State *L) { - u8 screen = luaL_checkinteger(L, 1); - u8 eye = luaL_optinteger(L, 2, GFX_LEFT); +static int gfx_start(lua_State *L) { + if (lua_isinteger(L, 1)) { + u8 screen = luaL_checkinteger(L, 1); + u8 eye = luaL_optinteger(L, 2, GFX_LEFT); - sf2d_start_frame(screen, eye); + sf2d_start_frame(screen, eye); + } else if (lua_isuserdata(L, 1)) { + target_userdata *target = luaL_checkudata(L, 1, "LTarget"); + + sf2d_start_frame_target(target->target); + } return 0; } @@ -68,9 +98,9 @@ static int gfx_startFrame(lua_State *L) { /*** End drawing to a screen. Must be called after your draw operations. -@function endFrame +@function stop */ -static int gfx_endFrame(lua_State *L) { +static int gfx_stop(lua_State *L) { sf2d_end_frame(); return 0; @@ -162,28 +192,6 @@ static int gfx_vramSpaceFree(lua_State *L) { return 1; } -/*** -Draw a line on the current screen. -@function line -@tparam integer x1 line's starting point horizontal coordinate, in pixels -@tparam integer y1 line's starting point vertical coordinate, in pixels -@tparam integer x2 line's endpoint horizontal coordinate, in pixels -@tparam integer y2 line's endpoint vertical coordinate, in pixels -@tparam[opt=default color] integer color drawing color -*/ -static int gfx_line(lua_State *L) { - int x1 = luaL_checkinteger(L, 1); - int y1 = luaL_checkinteger(L, 2); - int x2 = luaL_checkinteger(L, 3); - int y2 = luaL_checkinteger(L, 4); - - u32 color = luaL_optinteger(L, 5, color_default); - - sf2d_draw_line(x1, y1, x2, y2, color); - - return 0; -} - /*** Draw a point, a single pixel, on the current screen. @function point @@ -194,16 +202,96 @@ Draw a point, a single pixel, on the current screen. static int gfx_point(lua_State *L) { int x = luaL_checkinteger(L, 1); int y = luaL_checkinteger(L, 2); - + u32 color = luaL_optinteger(L, 3, color_default); - + sf2d_draw_rectangle(x, y, 1, 1, color); // well, it looks like a point return 0; } /*** -Draw a rectangle on the current screen. +Draw a line on the current screen. +@function line +@tparam integer x1 line's starting point horizontal coordinate, in pixels +@tparam integer y1 line's starting point vertical coordinate, in pixels +@tparam integer x2 line's endpoint horizontal coordinate, in pixels +@tparam integer y2 line's endpoint vertical coordinate, in pixels +@tparam[opt=1] number width line's thickness, in pixels +@tparam[opt=default color] integer color drawing color +*/ +static int gfx_line(lua_State *L) { + int x1 = luaL_checkinteger(L, 1); + int y1 = luaL_checkinteger(L, 2); + int x2 = luaL_checkinteger(L, 3); + int y2 = luaL_checkinteger(L, 4); + float width = luaL_optnumber(L, 5, 1.0f); + + u32 color = luaL_optinteger(L, 6, color_default); + + sf2d_draw_line(x1, y1, x2, y2, width, color); + + return 0; +} + +/*** +Draw a filled triangle on the current screen. +@function triangle +@tparam integer x1 horizontal coordinate of a vertex of the triangle, in pixels +@tparam integer y1 vertical coordinate of a vertex of the triangle, in pixels +@tparam integer x2 horizontal coordinate of a vertex of the triangle, in pixels +@tparam integer y2 vertical coordinate of a vertex of the triangle, in pixels +@tparam integer x3 horizontal coordinate of a vertex of the triangle, in pixels +@tparam integer y3 vertical coordinate of a vertex of the triangle, in pixels +@tparam[opt=default color] integer color drawing color +*/ +static int gfx_triangle(lua_State *L) { + int x1 = luaL_checkinteger(L, 1); + int y1 = luaL_checkinteger(L, 2); + int x2 = luaL_checkinteger(L, 3); + int y2 = luaL_checkinteger(L, 4); + int x3 = luaL_checkinteger(L, 5); + int y3 = luaL_checkinteger(L, 6); + + u32 color = luaL_optinteger(L, 7, color_default); + + sf2d_draw_triangle(x1, y1, x2, y2, x3, y3, color); + + return 0; +} + +/*** +Draw a triangle outline on the current screen. +@function linedTriangle +@tparam integer x1 horizontal coordinate of a vertex of the triangle, in pixels +@tparam integer y1 vertical coordinate of a vertex of the triangle, in pixels +@tparam integer x2 horizontal coordinate of a vertex of the triangle, in pixels +@tparam integer y2 vertical coordinate of a vertex of the triangle, in pixels +@tparam integer x3 horizontal coordinate of a vertex of the triangle, in pixels +@tparam integer y3 vertical coordinate of a vertex of the triangle, in pixels +@tparam[opt=1] number lineWidth line's thickness, in pixels +@tparam[opt=default color] integer color drawing color +*/ +static int gfx_linedTriangle(lua_State *L) { + int x1 = luaL_checkinteger(L, 1); + int y1 = luaL_checkinteger(L, 2); + int x2 = luaL_checkinteger(L, 3); + int y2 = luaL_checkinteger(L, 4); + int x3 = luaL_checkinteger(L, 5); + int y3 = luaL_checkinteger(L, 6); + float lineWidth = luaL_optnumber(L, 7, 1.0f); + + u32 color = luaL_optinteger(L, 8, color_default); + + sf2d_draw_line(x1, y1, x2, y2, lineWidth, color); + sf2d_draw_line(x2, y2, x3, y3, lineWidth, color); + sf2d_draw_line(x3, y3, x1, y1, lineWidth, color); + + return 0; +} + +/*** +Draw a filled rectangle on the current screen. @function rectangle @tparam integer x rectangle origin horizontal coordinate, in pixels @tparam integer y rectangle origin vertical coordinate, in pixels @@ -211,6 +299,8 @@ Draw a rectangle on the current screen. @tparam integer height rectangle height, in pixels @tparam[opt=0] number angle rectangle rotation, in radians @tparam[opt=default color] integer color drawing color +@tparam[opt] integer color2 Second drawing color ; if the argument is not nil, the rectangle will be filled with a gradient from color to color2 +@tparam[opt] integer direction Gradient drawing direction (`gfx.TOP_TO_BOTTOM` or `gfx.LEFT_TO_RIGHT`). This argument is mandatory if a second color was specified. */ static int gfx_rectangle(lua_State *L) { int x = luaL_checkinteger(L, 1); @@ -220,17 +310,73 @@ static int gfx_rectangle(lua_State *L) { float angle = luaL_optnumber(L, 5, 0); u32 color = luaL_optinteger(L, 6, color_default); - - if (angle == 0) - sf2d_draw_rectangle(x, y, width, height, color); - else - sf2d_draw_rectangle_rotate(x, y, width, height, color, angle); + + // Not second color : fill with plain color. + if (lua_isnoneornil(L, 7)) { + if (angle == 0) + sf2d_draw_rectangle(x, y, width, height, color); + else + sf2d_draw_rectangle_rotate(x, y, width, height, color, angle); + // Two colors : fill with a gradient. + } else { + u32 color2 = luaL_checkinteger(L, 7); + u8 direction = luaL_checkinteger(L, 8); + + if (angle == 0) + sf2d_draw_rectangle_gradient(x, y, width, height, color, color2, direction); + else + sf2d_draw_rectangle_gradient_rotate(x, y, width, height, color, color2, direction, angle); + } return 0; } /*** -Draw a circle on the current screen. +Draw a rectangle outline on the current screen. +@function linedRectangle +@tparam integer x rectangle origin horizontal coordinate, in pixels +@tparam integer y rectangle origin vertical coordinate, in pixels +@tparam integer width rectangle width, in pixels +@tparam integer height rectangle height, in pixels +@tparam[opt=1] integer lineWidth line's thickness, in pixels +@tparam[opt=0] number angle rectangle rotation, in radians +@tparam[opt=default color] integer color drawing color +*/ +static int gfx_linedRectangle(lua_State *L) { + int x = luaL_checkinteger(L, 1); + int y = luaL_checkinteger(L, 2); + int width = luaL_checkinteger(L, 3); + int height = luaL_checkinteger(L, 4); + float lineWidth = luaL_optnumber(L, 5, 1.0f); + + float angle = luaL_optnumber(L, 6, 0); + u32 color = luaL_optinteger(L, 7, color_default); + + // Corner coordinates + int x2 = x + width, y2 = y; + int x3 = x2, y3 = y + height; + int x4 = x, y4 = y3; + + // Rotate corners + if (angle != 0) { + int cx = x + width/2, cy = y + height/2; + rotatePoint(x, y, cx, cy, angle, &x, &y ); + rotatePoint(x2, y2, cx, cy, angle, &x2, &y2); + rotatePoint(x3, y3, cx, cy, angle, &x3, &y3); + rotatePoint(x4, y4, cx, cy, angle, &x4, &y4); + } + + // Draw lines + sf2d_draw_line(x, y, x2, y2, lineWidth, color); + sf2d_draw_line(x2, y2, x3, y3, lineWidth, color); + sf2d_draw_line(x3, y3, x4, y4, lineWidth, color); + sf2d_draw_line(x4, y4, x, y, lineWidth, color); + + return 0; +} + +/*** +Draw a filled circle on the current screen. @function circle @tparam integer x circle center horizontal coordinate, in pixels @tparam integer y circle center vertical coordinate, in pixels @@ -249,13 +395,63 @@ static int gfx_circle(lua_State *L) { return 0; } +/*** +Draw a circle outline on the current screen. +@function linedCircle +@tparam integer x circle center horizontal coordinate, in pixels +@tparam integer y circle center vertical coordinate, in pixels +@tparam integer radius circle radius, in pixels +@tparam[opt=1] integer width line's thickness, in pixels +@tparam[opt=default color] integer color drawing color +*/ +static int gfx_linedCircle(lua_State *L) { + int x0 = luaL_checkinteger(L, 1); + int y0 = luaL_checkinteger(L, 2); + int radius = luaL_checkinteger(L, 3); + float width = luaL_optnumber(L, 4, 1.0f); + + u32 color = luaL_optinteger(L, 5, color_default); + + for (int r = ceil(radius - width/2), maxr = ceil(radius + width/2)-1; r <= maxr; r++) { + // Implementatin of the Andres circle algorithm. + int x = 0; + int y = r; + int d = r - 1; + while (y >= x) { + // Best way to draw a lot of points, 10/10 + sf2d_draw_rectangle(x0 + x , y0 + y, 1, 1, color); + sf2d_draw_rectangle(x0 + y , y0 + x, 1, 1, color); + sf2d_draw_rectangle(x0 - x , y0 + y, 1, 1, color); + sf2d_draw_rectangle(x0 - y , y0 + x, 1, 1, color); + sf2d_draw_rectangle(x0 + x , y0 - y, 1, 1, color); + sf2d_draw_rectangle(x0 + y , y0 - x, 1, 1, color); + sf2d_draw_rectangle(x0 - x , y0 - y, 1, 1, color); + sf2d_draw_rectangle(x0 - y , y0 - x, 1, 1, color); + + if (d >= 2*x) { + d -= 2*x + 1; + x++; + } else if (d < 2*(r-y)) { + d += 2*y - 1; + y--; + } else { + d += 2*(y - x - 1); + y--; + x++; + } + } + } + + return 0; +} + /*** Draw a text on the current screen. @function text @tparam integer x text drawing origin horizontal coordinate, in pixels @tparam integer y text drawing origin vertical coordinate, in pixels @tparam string text the text to draw -@tparam[opt=9] integer size drawing size, in pixels +@tparam[opt=default size] integer size drawing size, in pixels @tparam[opt=default color] integer color drawing color @tparam[opt=default font] font font to use */ @@ -265,7 +461,7 @@ static int gfx_text(lua_State *L) { size_t len; const char *text = luaL_checklstring(L, 3, &len); - int size = luaL_optinteger(L, 4, 9); + int size = luaL_optinteger(L, 4, textSize); u32 color = luaL_optinteger(L, 5, color_default); font_userdata *font = luaL_testudata(L, 6, "LFont"); if (font == NULL) { @@ -276,7 +472,7 @@ static int gfx_text(lua_State *L) { if (font->font == NULL) luaL_error(L, "The font object was unloaded"); // Wide caracters support. (wchar = UTF32 on 3DS.) - wchar_t wtext[len]; + wchar_t wtext[len+1]; len = mbstowcs(wtext, text, len); *(wtext+len) = 0x0; // text end @@ -293,7 +489,7 @@ Warning: No UTF32 support. @tparam integer y text drawing origin vertical coordinate, in pixels @tparam string text the text to draw @tparam integer width width of a line, in pixels -@tparam[opt=9] integer size drawing size, in pixels +@tparam[opt=default Size] integer size drawing size, in pixels @tparam[opt=default color] integer color drawing color @tparam[opt=default font] font font to use */ @@ -304,7 +500,7 @@ static int gfx_wrappedText(lua_State *L) { const char *text = luaL_checklstring(L, 3, &len); unsigned int lineWidth = luaL_checkinteger(L, 4); - int size = luaL_optinteger(L, 5, 9); + int size = luaL_optinteger(L, 5, textSize); u32 color = luaL_optinteger(L, 6, color_default); font_userdata *font = luaL_testudata(L, 7, "LFont"); if (font == NULL) { @@ -316,7 +512,7 @@ static int gfx_wrappedText(lua_State *L) { // Wide caracters support. (wchar = UTF32 on 3DS.) // Disabled as sftd_draw_wtext_wrap() doesn't exist. - /*wchar_t wtext[len]; + /*wchar_t wtext[len+1]; len = mbstowcs(wtext, text, len); *(wtext+len) = 0x0; // text end */ @@ -330,7 +526,7 @@ Calculate the size of a text draw with `wrappedText`. @function calcBoundingBox @tparam string text The text to check @tparam integer lineWidth width of a line, in pixels -@tparam[opt=9] integer size drawing size, in pixels +@tparam[opt=default size] integer size drawing size, in pixels @tparam[opt=default font] font font to use @treturn integer width of the text, in pixels @treturn integer height of the text, in pixels @@ -339,7 +535,7 @@ static int gfx_calcBoundingBox(lua_State *L) { size_t len; const char *text = luaL_checklstring(L, 1, &len); unsigned int lineWidth = luaL_checkinteger(L, 2); - int size = luaL_optinteger(L, 3, 9); + int size = luaL_optinteger(L, 3, textSize); font_userdata *font = luaL_testudata(L, 4, "LFont"); if (font == NULL) { lua_getfield(L, LUA_REGISTRYINDEX, "LFontDefault"); @@ -356,10 +552,196 @@ static int gfx_calcBoundingBox(lua_State *L) { return 2; } +/*** +Enables or disable the scissor test. +When the scissor test is enabled, the drawing area will be limited to a specific rectangle, every pixel drawn outside will be discarded. +Calls this function without argument to disable the scissor test. +@function scissor +@tparam integer x scissor rectangle origin horizontal coordinate, in pixels +@tparam integer y scissor rectangle origin vertical coordinate, in pixels +@tparam integer width scissor rectangle width, in pixels +@tparam integer height scissor rectangle height, in pixels +@tparam[opt=false] boolean invert if true the scissor will be inverted (will draw only outside of the rectangle) +*/ +static int gfx_scissor(lua_State *L) { + if (lua_gettop(L) == 0) { + lua_scissor.mode = GPU_SCISSOR_DISABLE; + lua_scissor.x = 0; + lua_scissor.y = 0; + lua_scissor.width = 0; + lua_scissor.height = 0; + } else { + lua_scissor.x = luaL_checkinteger(L, 1); + lua_scissor.y = luaL_checkinteger(L, 2); + lua_scissor.width = luaL_checkinteger(L, 3); + lua_scissor.height = luaL_checkinteger(L, 4); + lua_scissor.mode = lua_toboolean(L, 5) ? GPU_SCISSOR_INVERT : GPU_SCISSOR_NORMAL; + } + + sf2d_set_scissor_test(lua_scissor.mode, lua_scissor.x, lua_scissor.y, lua_scissor.width, lua_scissor.height); + + return 0; +} + +/*** +__Work in progress__. Create a render target. Don't use it. +@function target +@tparam integer width +@tparam integer height +@treturn target +*/ +static int gfx_target(lua_State *L) { + int width = luaL_checkinteger(L, 1); + int height = luaL_checkinteger(L, 2); + int wpo2 = 0, hpo2 = 0; + for (;width>pow(2,wpo2);wpo2++); + width = pow(2,wpo2); + for (;height>pow(2,hpo2);hpo2++); + height = pow(2,hpo2); + + target_userdata *target; + target = (target_userdata*)lua_newuserdata(L, sizeof(*target)); + + luaL_getmetatable(L, "LTarget"); + lua_setmetatable(L, -2); + + target->target = sf2d_create_rendertarget(width, height); + + return 1; +} + +/*** +Render targets +@section target +*/ + +/*** +Clear a target to a specified color. +@function :clear +@tparam[opt=default color] integer color color to fill the target with +*/ +static int gfx_target_clear(lua_State *L) { + target_userdata *target = luaL_checkudata(L, 1, "LTarget"); + u32 color = luaL_optinteger(L, 2, color_default); + + sf2d_clear_target(target->target, color); + + return 0; +} + +/*** +Destroy a target. +@function :destroy +*/ +static int gfx_target_destroy(lua_State *L) { + target_userdata *target = luaL_checkudata(L, 1, "LTarget"); + + sf2d_free_target(target->target); + + return 0; +} + +static const struct luaL_Reg target_methods[]; +/*** + +*/ +static int gfx_target___index(lua_State *L) { + target_userdata *target = luaL_checkudata(L, 1, "LTarget"); + const char* name = luaL_checkstring(L, 2); + + if (strcmp(name, "texture") == 0) { + texture_userdata *texture; + texture = (texture_userdata*)lua_newuserdata(L, sizeof(*texture)); + luaL_getmetatable(L, "LTexture"); + lua_setmetatable(L, -2); + + texture->texture = &(target->target->texture); + texture->scaleX = 1.0f; + texture->scaleY = 1.0f; + texture->blendColor = 0xffffffff; + + return 1; + } else if (strcmp(name, "duck") == 0) { + sf2d_rendertarget *target = sf2d_create_rendertarget(64, 64); + for(int i=0;;i++) { + sf2d_clear_target(target, 0xff000000); + sf2d_start_frame_target(target); + sf2d_draw_fill_circle(i%380, i%200, 10, 0xff0000ff); + sf2d_end_frame(); + //sf2d_texture_tile32(&target->texture); + + sf2d_start_frame(GFX_TOP, GFX_LEFT); + sf2d_draw_texture(&target->texture, 10, 10); + sf2d_end_frame(); + sf2d_swapbuffers(); + } + } else { + for (u8 i=0;target_methods[i].name;i++) { + if (strcmp(target_methods[i].name, name) == 0) { + lua_pushcfunction(L, target_methods[i].func); + return 1; + } + } + } + + lua_pushnil(L); + return 1; +} + +/*** +Console +@section console +*/ + +/*** +Initialize the console. You can print on it using print(), or any function that normally outputs to stdout. +Warning: you can't use a screen for both a console and drawing, you have to disable the console first. +@function console +@tparam[opt=gfx.TOP] number screen screen to draw the console on. +@tparam[opt=false] boolean debug enable stderr output on the console +*/ +u8 consoleScreen = GFX_TOP; +static int gfx_console(lua_State *L) { + consoleScreen = luaL_optinteger(L, 1, GFX_TOP); + bool err = false; + if (lua_isboolean(L, 2)) { + err = lua_toboolean(L, 2); + } + + consoleInit(consoleScreen, NULL); + if (err) + consoleDebugInit(debugDevice_CONSOLE); + + return 0; +} + +/*** +Clear the console. +@function clearConsole +*/ +static int gfx_clearConsole(lua_State *L) { + consoleClear(); + + return 0; +} + +/*** +Disable the console. +@function disableConsole +*/ +static int gfx_disableConsole(lua_State *L) { + gfxSetScreenFormat(consoleScreen, GSP_BGR8_OES); + gfxSetDoubleBuffering(consoleScreen, true); + gfxSwapBuffersGpu(); + gspWaitForVBlank(); + + return 0; +} + // Functions static const struct luaL_Reg gfx_lib[] = { - { "startFrame", gfx_startFrame }, - { "endFrame", gfx_endFrame }, + { "start", gfx_start }, + { "stop", gfx_stop }, { "render", gfx_render }, { "getFPS", gfx_getFPS }, { "set3D", gfx_set3D }, @@ -367,66 +749,97 @@ static const struct luaL_Reg gfx_lib[] = { { "setVBlankWait", gfx_setVBlankWait }, { "waitForVBlank", gfx_waitForVBlank }, { "vramSpaceFree", gfx_vramSpaceFree }, - { "line", gfx_line }, { "point", gfx_point }, + { "line", gfx_line }, + { "triangle", gfx_triangle }, + { "linedTriangle", gfx_linedTriangle }, { "rectangle", gfx_rectangle }, + { "linedRectangle", gfx_linedRectangle }, { "circle", gfx_circle }, + { "linedCircle", gfx_linedCircle }, { "text", gfx_text }, { "wrappedText", gfx_wrappedText }, { "calcBoundingBox", gfx_calcBoundingBox }, + { "scissor", gfx_scissor }, + { "target", gfx_target }, + { "console", gfx_console }, + { "clearConsole", gfx_clearConsole }, + { "disableConsole", gfx_disableConsole }, { NULL, NULL } }; -// Constants +// Render target +static const struct luaL_Reg target_methods[] = { + { "__index", gfx_target___index }, + { "clear", gfx_target_clear }, + { "destroy", gfx_target_destroy }, + { "__gc", gfx_target_destroy }, + { NULL, NULL } +}; + +/*** +Constants +@section constants +*/ struct { char *name; int value; } gfx_constants[] = { /*** Constant used to select the top screen. It is equal to `0`. - @field GFX_TOP + @field TOP */ - { "GFX_TOP", GFX_TOP }, + { "TOP", GFX_TOP }, /*** Constant used to select the bottom screen. It is equal to `1`. - @field GFX_BOTTOM + @field BOTTOM */ - { "GFX_BOTTOM", GFX_BOTTOM }, + { "BOTTOM", GFX_BOTTOM }, /*** Constant used to select the left eye. It is equal to `0`. - @field GFX_LEFT + @field LEFT */ - { "GFX_LEFT", GFX_LEFT }, + { "LEFT", GFX_LEFT }, /*** Constant used to select the right eye. It is equal to `1`. - @field GFX_RIGHT + @field RIGHT */ - { "GFX_RIGHT", GFX_RIGHT }, + { "RIGHT", GFX_RIGHT }, /*** The top screen height, in pixels. It is equal to `240`. @field TOP_HEIGHT */ - { "TOP_HEIGHT", 240 }, + { "TOP_HEIGHT", 240 }, /*** The top screen width, in pixels. It is equal to `400`. @field TOP_WIDTH */ - { "TOP_WIDTH", 400 }, + { "TOP_WIDTH", 400 }, /*** The bottom screen height, in pixels. It is equal to `240`. @field BOTTOM_HEIGHT */ - { "BOTTOM_HEIGHT", 240 }, + { "BOTTOM_HEIGHT", 240 }, /*** The bottom screen width, in pixels. It is equal to `320`. @field BOTTOM_WIDTH */ - { "BOTTOM_WIDTH", 320 }, + { "BOTTOM_WIDTH", 320 }, + /*** + Represents a vertical gradient drawn from the top (first color) to the bottom (second color). + @field TOP_TO_BOTTOM + */ + { "TOP_TO_BOTTOM", SF2D_TOP_TO_BOTTOM }, + /*** + Represents a horizontal gradient drawn from the left (first color) to the right (second color). + @field LEFT_TO_RIGHT + */ + { "LEFT_TO_RIGHT", SF2D_LEFT_TO_RIGHT }, { NULL, 0 } }; @@ -440,6 +853,11 @@ struct { char *name; void (*load)(lua_State *L); void (*unload)(lua_State *L); } }; int luaopen_gfx_lib(lua_State *L) { + luaL_newmetatable(L, "LTarget"); + lua_pushvalue(L, -1); + lua_setfield(L, -2, "__index"); + luaL_setfuncs(L, target_methods, 0); + luaL_newlib(L, gfx_lib); for (int i = 0; gfx_constants[i].name; i++) { @@ -456,10 +874,12 @@ int luaopen_gfx_lib(lua_State *L) { } void load_gfx_lib(lua_State *L) { - sf2d_init(); - sftd_init(); + if (!isGfxInitialized) { + sf2d_init(); + sftd_init(); + } - isGfxInitialised = true; + isGfxInitialized = true; luaL_requiref(L, "ctr.gfx", luaopen_gfx_lib, 0); } diff --git a/source/gfx.h b/source/gfx.h new file mode 100644 index 0000000..7a7afbe --- /dev/null +++ b/source/gfx.h @@ -0,0 +1,12 @@ +#ifndef GFX_H +#define GFX_H + +typedef struct { + GPU_SCISSORMODE mode; + u32 x; u32 y; + u32 width; u32 height; +} scissor_state; + +extern scissor_state lua_scissor; + +#endif diff --git a/source/hid.c b/source/hid.c index 6d54b20..ed76ee7 100644 --- a/source/hid.c +++ b/source/hid.c @@ -1,11 +1,12 @@ /*** The `hid` module. -The circle pad pro is supported, it's keys replace de "3ds only" keys +The circle pad pro is supported, it's keys replace the "3ds only" keys @module ctr.hid @usage local hid = require("ctr.hid") */ #include <3ds/types.h> #include <3ds/services/hid.h> +#include <3ds/services/irrst.h> #include #include @@ -51,7 +52,7 @@ Keys states */ // Key list based on hid.h from the ctrulib by smealum -struct { PAD_KEY key; char *name; } hid_keys_name[] = { +struct { u32 key; char *name; } hid_keys_name[] = { { KEY_A , "a" }, { KEY_B , "b" }, { KEY_SELECT , "select" }, @@ -117,7 +118,7 @@ static int hid_keys(lua_State *L) { lua_newtable(L); // up table for (int i = 0; hid_keys_name[i].key; i++) { - PAD_KEY key = hid_keys_name[i].key; + u32 key = hid_keys_name[i].key; char *name = hid_keys_name[i].name; if (kDown & key) { @@ -175,6 +176,25 @@ static int hid_circle(lua_State *L) { return 2; } +/*** +Return the C-stick position. +`0,0` is the center position, and the stick should return to it if not touched (95% of the time). +Range is from `-146` to `146` on both X and Y, but these are hard to reach. +@newonly +@function cstick +@treturn number X position +@treturn number Y position +*/ +static int hid_cstick(lua_State *L) { + circlePosition pos; + irrstCstickRead(&pos); + + lua_pushinteger(L, pos.dx); + lua_pushinteger(L, pos.dy); + + return 2; +} + /*** Return the accelerometer vector @function accel @@ -243,6 +263,7 @@ static const struct luaL_Reg hid_lib[] = { { "keys", hid_keys }, { "touch", hid_touch }, { "circle", hid_circle }, + { "cstick", hid_cstick }, { "accel", hid_accel }, { "gyro", hid_gyro }, { "volume", hid_volume }, diff --git a/source/httpc.c b/source/httpc.c index e104e18..87c826d 100644 --- a/source/httpc.c +++ b/source/httpc.c @@ -9,10 +9,13 @@ The `httpc` module. #include <3ds.h> #include <3ds/types.h> #include <3ds/services/httpc.h> +#include <3ds/services/sslc.h> #include #include +bool isHttpcInitialized = false; + /*** Create a HTTP Context. @function context @@ -20,12 +23,6 @@ Create a HTTP Context. */ static int httpc_context(lua_State *L) { httpcContext context; - Result ret = httpcOpenContext(&context, "http://google.com/", 0); // Initialization only. - if (ret != 0) { - lua_pushnil(L); - lua_pushinteger(L, ret); - return 2; - } lua_newuserdata(L, sizeof(&context)); luaL_getmetatable(L, "LHTTPC"); lua_setmetatable(L, -2); @@ -42,15 +39,30 @@ context object Open an url in the context. @function :open @tparam string url the url to open +@tparam[opt="GET"] string method method to use; can be `"GET"`, `"POST"`, `"HEAD"`, `"PUT"` or `"DELETE"` +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code */ static int httpc_open(lua_State *L) { httpcContext *context = lua_touserdata(L, 1); char *url = (char*)luaL_checkstring(L, 2); + char *smethod = (char*)luaL_optstring(L, 3, "GET"); + HTTPC_RequestMethod method = HTTPC_METHOD_GET; // default to GET + if (strcmp(smethod, "POST")) { + method = HTTPC_METHOD_POST; + } else if (strcmp(smethod, "HEAD")) { + method = HTTPC_METHOD_HEAD; + } else if (strcmp(smethod, "PUT")) { + method = HTTPC_METHOD_PUT; + } else if (strcmp(smethod, "DELETE")) { + method = HTTPC_METHOD_DELETE; + } Result ret = 0; - ret = httpcOpenContext(context, url, 0); + ret = httpcOpenContext(context, method, url, 0); if (ret != 0) { - lua_pushnil(L); + lua_pushboolean(L, false); lua_pushinteger(L, ret); return 2; } @@ -63,6 +75,9 @@ Add a field in the request header. @function :addRequestHeaderField @tparam string name Name of the field @tparam string value Value of the field +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code */ static int httpc_addRequestHeaderField(lua_State *L) { httpcContext *context = lua_touserdata(L, 1); @@ -71,7 +86,7 @@ static int httpc_addRequestHeaderField(lua_State *L) { Result ret = httpcAddRequestHeaderField(context, name ,value); if (ret != 0) { - lua_pushnil(L); + lua_pushboolean(L, false); lua_pushinteger(L, ret); return 2; } @@ -82,6 +97,9 @@ static int httpc_addRequestHeaderField(lua_State *L) { /*** Begin a request to get the content at the URL. @function :beginRequest +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code */ static int httpc_beginRequest(lua_State *L) { httpcContext *context = lua_touserdata(L, 1); @@ -89,7 +107,7 @@ static int httpc_beginRequest(lua_State *L) { ret = httpcBeginRequest(context); if (ret != 0) { - lua_pushnil(L); + lua_pushboolean(L, false); lua_pushinteger(L, ret); return 2; } @@ -100,7 +118,9 @@ static int httpc_beginRequest(lua_State *L) { /*** Return the status code returned by the request. @function :getStatusCode -@treturn number the status code +@treturn[1] integer the status code +@treturn[2] nil in case of error +@treturn[2] integer error code */ static int httpc_getStatusCode(lua_State *L) { httpcContext *context = lua_touserdata(L, 1); @@ -134,7 +154,9 @@ static int httpc_getDownloadSize(lua_State *L) { /*** Download and return the data of the context. @function :downloadData -@treturn string data +@treturn[1] string data +@treturn[2] nil in case of error +@treturn[2] integer error code */ static int httpc_downloadData(lua_State *L) { httpcContext *context = lua_touserdata(L, 1); @@ -152,15 +174,16 @@ static int httpc_downloadData(lua_State *L) { ret = httpcDownloadData(context, buff, size, NULL); if (ret != 0) { + free(buff); lua_pushnil(L); lua_pushinteger(L, ret); return 2; } lua_pushstring(L, (char*)buff); - //free(buff); - lua_pushinteger(L, size); // only for test purposes. - return 2; + free(buff); + //lua_pushinteger(L, size); // only for test purposes. + return 1; } /*** @@ -175,6 +198,100 @@ static int httpc_close(lua_State *L) { return 0; } +/*** +Add a POST form field to a HTTP context. +@function :addPostData +@tparam string name name of the field +@tparam string value value of the field +*/ +static int httpc_addPostData(lua_State *L) { + httpcContext *context = lua_touserdata(L, 1); + char *name = (char*)luaL_checkstring(L, 2); + char *value = (char*)luaL_checkstring(L, 3); + + httpcAddPostDataAscii(context, name, value); + + return 0; +} + +/*** +Get a header field from a response. +@function :getResponseHeader +@tparam string name name of the header field to get +@tparam[opt=2048] number maximum size of the value to get +@treturn string field value +*/ +static int httpc_getResponseHeader(lua_State *L) { + httpcContext *context = lua_touserdata(L, 1); + char *name = (char*)luaL_checkstring(L, 2); + u32 maxSize = luaL_checkinteger(L, 3); + char* value = 0; + + httpcGetResponseHeader(context, name, value, maxSize); + + lua_pushstring(L, value); + return 1; +} + +/*** +Add a trusted RootCA cert to a context. +@function :addTrustedRootCA +@tparam string DER certificate +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code +*/ +static int httpc_addTrustedRootCA(lua_State *L) { + httpcContext *context = lua_touserdata(L, 1); + u32 certsize; + u8* cert = (u8*)luaL_checklstring(L, 2, (size_t*)&certsize); + + Result ret = httpcAddTrustedRootCA(context, cert, certsize); + if (ret != 0) { + lua_pushboolean(L, false); + lua_pushinteger(L, ret); + return 2; + } + + lua_pushboolean(L, true); + return 1; +} + +/*** +Set SSL options for a context. +@function :setSSLOptions +@tparam boolean disableVerify disable server certificate verification if `true` +@tparam[opt=false] boolean tlsv10 use TLS v1.0 if `true` +*/ +static int httpc_setSSLOptions(lua_State *L) { + httpcContext *context = lua_touserdata(L, 1); + + bool disVer = lua_toboolean(L, 2); + bool tsl10 = false; + if (lua_isboolean(L, 3)) + tsl10 = lua_toboolean(L, 3); + + httpcSetSSLOpt(context, (disVer?SSLCOPT_DisableVerify:0)|(tsl10?SSLCOPT_TLSv10:0)); + + return 0; +} + +/*** +Add all the default certificates to the context. +@function addDefaultCert +*/ +static int httpc_addDefaultCert(lua_State *L) { + httpcContext *context = lua_touserdata(L, 1); + + httpcAddDefaultCert(context, SSLC_DefaultRootCert_CyberTrust); + httpcAddDefaultCert(context, SSLC_DefaultRootCert_AddTrust_External_CA); + httpcAddDefaultCert(context, SSLC_DefaultRootCert_COMODO); + httpcAddDefaultCert(context, SSLC_DefaultRootCert_USERTrust); + httpcAddDefaultCert(context, SSLC_DefaultRootCert_DigiCert_EV); + + return 0; +} + // object static const struct luaL_Reg httpc_methods[] = { {"open", httpc_open }, @@ -184,6 +301,12 @@ static const struct luaL_Reg httpc_methods[] = { {"getDownloadSize", httpc_getDownloadSize }, {"downloadData", httpc_downloadData }, {"close", httpc_close }, + {"__gc", httpc_close }, + {"addPostData", httpc_addPostData }, + {"getResponseHeader", httpc_getResponseHeader }, + {"addTrustedRootCA", httpc_addTrustedRootCA }, + {"setSSLOptions", httpc_setSSLOptions }, + {"addDefaultCert", httpc_addDefaultCert }, {NULL, NULL} }; @@ -205,7 +328,10 @@ int luaopen_httpc_lib(lua_State *L) { } void load_httpc_lib(lua_State *L) { - httpcInit(); + if (!isHttpcInitialized) { + httpcInit(0x1000); + isHttpcInitialized = true; + } luaL_requiref(L, "ctr.httpc", luaopen_httpc_lib, false); } diff --git a/source/ir.c b/source/ir.c index 705091b..0144bfb 100644 --- a/source/ir.c +++ b/source/ir.c @@ -5,13 +5,12 @@ The `ir` module. */ #include <3ds/types.h> #include <3ds/services/ir.h> -#include <3ds/linear.h> +//#include <3ds/linear.h> #include #include -u32 bufferSize = 0; -u32 *buffer; +#include /*** Bitrate codes list (this is not a part of the module, just a reference) @@ -38,19 +37,14 @@ Bitrate codes list (this is not a part of the module, just a reference) Initialize the IR module. @function init @tparam[opt=6] number bitrate bitrate of the IR module (more informations below) -@tparam[opt=2048] number buffer size of the buffer, in bytes (max 2048) +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code */ static int ir_init(lua_State *L) { u8 bitrate = luaL_optinteger(L, 1, 6); - bufferSize = luaL_optinteger(L, 2, 2048); //default: 2Kio - if (bufferSize > 2048) { - lua_pushboolean(L, false); - lua_pushstring(L, "the buffer can't be larger than 2048 bytes."); - return 2; - } - buffer = linearAlloc(bufferSize); - Result ret = IRU_Initialize(buffer, bufferSize); + Result ret = IRU_Initialize(); if (ret) { lua_pushboolean(L, false); lua_pushinteger(L, ret); @@ -65,6 +59,9 @@ static int ir_init(lua_State *L) { /*** Disable the IR module. @function shutdown +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code */ static int ir_shutdown(lua_State *L) { Result ret = IRU_Shutdown(); @@ -83,42 +80,51 @@ Send some data over the IR module. @function send @tparam string data just some data @tparam[opt=false] boolean wait set to `true` to wait until the data is sent. +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code */ static int ir_send(lua_State *L) { u8 *data = (u8*)luaL_checkstring(L, 1); u32 wait = lua_toboolean(L, 2); - Result ret = IRU_SendData(data, sizeof(data), wait); + Result ret = IRU_StartSendTransfer(data, strlen((const char*)data)); + if (wait) + IRU_WaitSendTransfer(); + if (ret) { lua_pushboolean(L, false); lua_pushinteger(L, ret); return 2; } - return 0; + lua_pushboolean(L, true); + return 1; } /*** Receive some data from the IR module. @function receive -@tparam[opt=buffer size] number size bytes to receive +@tparam number size bytes to receive @tparam[opt=false] boolean wait wait until the data is received -@return string data +@treturn[1] string data +@treturn[2] nil in case of error +@treturn[2] integer error code */ static int ir_receive(lua_State *L) { - u32 size = luaL_optinteger(L, 1, bufferSize); + u32 size = luaL_checkinteger(L, 1); u32 wait = lua_toboolean(L, 2); u8 *data = 0; - u32 *transfercount = 0; + u32 transfercount = 0; - Result ret = IRU_RecvData(data, size, 0x00, transfercount, wait); + Result ret = iruRecvData(data, size, 0x00, &transfercount, wait); if (ret) { - lua_pushboolean(L, false); + lua_pushnil(L); lua_pushinteger(L, ret); return 2; } - lua_pushstring(L, (const char *)data); + lua_pushlstring(L, (const char *)data, (size_t)transfercount); return 1; } @@ -127,6 +133,9 @@ static int ir_receive(lua_State *L) { Set the bitrate of the communication. @function setBitRate @tparam number bitrate new bitrate for the communication +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code */ static int ir_setBitRate(lua_State *L) { u8 bitrate = luaL_checkinteger(L, 1); @@ -138,20 +147,24 @@ static int ir_setBitRate(lua_State *L) { return 2; } - return 0; + lua_pushboolean(L, true); + + return 1; } /*** Return the actual bitrate of the communication. @function getBitRate -@treturn number actual bitrate +@treturn[1] number actual bitrate +@treturn[2] nil in case of error +@treturn[2] integer error code */ static int ir_getBitRate(lua_State *L) { u8 bitrate = 0; Result ret = IRU_GetBitRate(&bitrate); if (ret) { - lua_pushboolean(L, false); + lua_pushnil(L); lua_pushinteger(L, ret); return 2; } diff --git a/source/main.c b/source/main.c index be7d9d7..33febb3 100644 --- a/source/main.c +++ b/source/main.c @@ -1,19 +1,19 @@ +#include + #include <3ds.h> #include #include #include -#define BOOT_FILE "sdmc:/3ds/ctruLua/main.lua" - void load_ctr_lib(lua_State *L); void unload_ctr_lib(lua_State *L); -bool isGfxInitialised; +bool isGfxInitialized; // Display an error void error(const char *error) { - if (!isGfxInitialised) gfxInitDefault(); + if (!isGfxInitialized) gfxInitDefault(); gfxSet3D(false); consoleInit(GFX_TOP, NULL); @@ -30,11 +30,18 @@ void error(const char *error) { gspWaitForVBlank(); } - if (!isGfxInitialised) gfxExit(); + if (!isGfxInitialized) gfxExit(); } // Main loop -int main() { +int main(int argc, char** argv) { + // Default arguments + #ifdef ROMFS + char* mainFile = "romfs:/main.lua"; + #else + char* mainFile = "main.lua"; + #endif + // Init Lua lua_State *L = luaL_newstate(); if (L == NULL) { @@ -45,13 +52,36 @@ int main() { // Load libs luaL_openlibs(L); load_ctr_lib(L); - + isGfxInitialized = true; + + // Parse arguments + for (int i=0;i #include #include +#include +#include "gfx.h" #include "texture.h" typedef struct { @@ -42,23 +45,32 @@ u16 getTile(map_userdata *map, int x, int y) { /*** Load a map from a file. @function load -@tparam string path path to the .map +@tparam string/table map path to the .map or a 2D table containing tile data (`{ [Y1]={[X1]=tile1, [X2]=tile2}, [Y2]=..., ... }`) @tparam texture tileset containing the tileset @tparam number tileWidth tile width @tparam number tileHeight tile height -@treturn map loaded map object +@treturn[1] map loaded map object +@treturn[2] nil in case of error +@treturn[2] string error message */ static int map_load(lua_State *L) { - const char *mapPath = luaL_checkstring(L, 1); texture_userdata *texture = luaL_checkudata(L, 2, "LTexture"); u8 tileSizeX = luaL_checkinteger(L, 3); u8 tileSizeY = luaL_checkinteger(L, 4); - map_userdata *map; - map = (map_userdata*)lua_newuserdata(L, sizeof(map_userdata)); + map_userdata *map = lua_newuserdata(L, sizeof(map_userdata)); luaL_getmetatable(L, "LMap"); lua_setmetatable(L, -2); - + + // Block GC of the texture by keeping a reference to it in the registry + // registry[map_userdata] = texture_userdata + lua_pushnil(L); + lua_copy(L, -2, -1); // map_userdata + lua_pushnil(L); + lua_copy(L, 2, -1); // texture_userdata + lua_settable(L, LUA_REGISTRYINDEX); + + // Init userdata fields map->texture = texture; map->tileSizeX = tileSizeX; map->tileSizeY = tileSizeY; @@ -68,47 +80,87 @@ static int map_load(lua_State *L) { map->spaceY = 0; // read the map file - FILE *mapFile = fopen(mapPath, "r"); - if (mapFile == NULL) { - lua_pushnil(L); - lua_pushstring(L, "No such file"); - return 2; - } - fseek(mapFile, 0L, SEEK_END); - int fileSize = ftell(mapFile); - fseek(mapFile, 0L, SEEK_SET); - char *buffer = (char *)malloc(sizeof(char)*fileSize); - fread(buffer, 1, fileSize, mapFile); - fclose(mapFile); - - int width = 0; - for (int i=0; buffer[i]; i++) { - if (buffer[i] == '|') { - width++; - } else if (buffer[i] == '\n') { - break; + if (lua_isstring(L, 1)) { + const char *mapPath = luaL_checkstring(L, 1); + + FILE *mapFile = fopen(mapPath, "r"); + if (mapFile == NULL) { + lua_pushnil(L); + lua_pushfstring(L, "no such file \"%s\"", mapPath); + return 2; } + fseek(mapFile, 0L, SEEK_END); + int fileSize = ftell(mapFile); + fseek(mapFile, 0L, SEEK_SET); + char *buffer = (char *)malloc(sizeof(char)*fileSize); + fread(buffer, 1, fileSize, mapFile); + fclose(mapFile); + + int width = 0; + for (int i=0; buffer[i]; i++) { + if (buffer[i] == ',') { + width++; + } else if (buffer[i] == '\n') { + width++; + break; + } + } + int height = 0; + for (int i=0; buffer[i]; i++) { // this should do + if (buffer[i] == '\n' && (buffer[i+1] != '\n' || !buffer[i+1])) height++; + } + + map->width = width; + map->height = height; + + map->data = malloc(sizeof(u16)*width*height); + int i = 0; + char *token = strtok(buffer, ",\n"); + while (token != NULL) { + map->data[i] = (u16)atoi(token); + i++; + token = strtok(NULL, ",\n"); + } + free(buffer); + + return 1; + + } else if (lua_istable(L, 1)) { + int height = luaL_len(L, 1); + if (height < 1) luaL_error(L, "map height must be greater or equal to 1"); + + lua_geti(L, 1, 1); + int width = luaL_len(L, -1); + if (width < 1) luaL_error(L, "map width must be greater or equal to 1"); + lua_pop(L, 1); + + map->width = width; + map->height = height; + + map->data = malloc(sizeof(u16)*width*height); + for (int y=1; y<=height; y++) { + if (lua_geti(L, 1, y) != LUA_TTABLE) luaL_error(L, "map table must be an array of tables"); + if (luaL_len(L, -1) < width) luaL_error(L, "table line y=%d is shorter than the map width", y); + + for (int x=1; x<=width; x++) { + lua_geti(L, -1, x); + + bool isnum; + map->data[(x-1)+((y-1)*map->width)] = (u16)lua_tointegerx(L, -1, (int *)&isnum); + if (!isnum) luaL_error(L, "tiles must be integers"); + + lua_pop(L, 1); + } + + lua_pop(L, 1); + } + + return 1; + + } else { + luaL_error(L, "map (first argument) must be a string or a table"); + return 0; } - int height = 0; - for (int i=0; buffer[i]; i++) { // this should do - if (buffer[i] == '\n' && (buffer[i+1] != '\n' || !buffer[i+1])) height++; - } - - map->width = width; - map->height = height; - - map->data = malloc(sizeof(u16)*width*height); - int i = 0; - char *token; - token = strtok(buffer, "|"); - while (token != NULL) { - map->data[i] = (u16)atoi(token); - i++; - token = strtok(NULL, "|"); - } - free(buffer); - - return 1; } /*** @@ -117,50 +169,81 @@ Map object */ /*** -Draw a map. +Draw (a part of) the map on the screen. @function :draw -@tparam number x X position -@tparam number y Y position -@within Methods +@tparam integer x X top-left coordinate to draw the map on the screen (pixels) +@tparam integer y Y top-left coordinate to draw the map on the screen (pixels) +@tparam[opt=0] integer offsetX drawn area X start coordinate on the map (pixels) (x=0,y=0 correspond to the first tile top-left corner) +@tparam[opt=0] integer offsetY drawn area Y start coordinate on the map (pixels) +@tparam[opt=400] integer width width of the drawn area on the map (pixels) +@tparam[opt=240] integer height height of the drawn area on the map (pixels) +@usage +-- This will draw on the screen at x=5,y=5 a part of the map. The part is the rectangle on the map starting at x=16,y=16 and width=32,height=48. +-- For example, if you use 16x16 pixel tiles, this will draw the tiles from 1,1 (top-left corner of the rectangle) to 2,3 (bottom-right corner). +map:draw(5, 5, 16, 16, 32, 48) */ static int map_draw(lua_State *L) { map_userdata *map = luaL_checkudata(L, 1, "LMap"); int x = luaL_checkinteger(L, 2); int y = luaL_checkinteger(L, 3); + int offsetX = luaL_optinteger(L, 4, 0); + int offsetY = luaL_optinteger(L, 5, 0); + int width = luaL_optinteger(L, 6, 400); + int height = luaL_optinteger(L, 7, 240); + + int xI = fmax(floor((double)offsetX / map->tileSizeX), 0); // initial tile X + int xF = fmin(ceil((double)(offsetX + width) / map->tileSizeX), map->width); // final tile X + + int yI = fmax(floor((double)offsetY / map->tileSizeY), 0); // initial tile Y + int yF = fmin(ceil((double)(offsetY + height) / map->tileSizeY), map->height); // final tile Y + + if (sf2d_get_current_screen() == GFX_TOP) + sf2d_set_scissor_test(GPU_SCISSOR_NORMAL, x, y, fmin(width, 400 - x), fmin(height, 240 - y)); // Scissor test doesn't work when x/y + width > screenWidth/Height + else + sf2d_set_scissor_test(GPU_SCISSOR_NORMAL, x, y, fmin(width, 320 - x), fmin(height, 240 - y)); + int texX = 0; int texY = 0; - - + if (map->texture->blendColor == 0xffffffff) { - for (int xp=0; xpwidth; xp++) { - for (int yp=0; ypheight; yp++) { + for (int xp = xI; xp < xF; xp++) { + for (int yp = yI; yp < yF; yp++) { u16 tile = getTile(map, xp, yp); getTilePos(map, tile, &texX, &texY); - sf2d_draw_texture_part(map->texture->texture, (x+(map->tileSizeX*xp)+(xp*map->spaceX)), (y+(map->tileSizeY*yp)+(yp*map->spaceY)), texX, texY, map->tileSizeX, map->tileSizeY); + sf2d_draw_texture_part(map->texture->texture, x+(map->tileSizeX*xp)+(xp*map->spaceX)-offsetX, y+(map->tileSizeY*yp)+(yp*map->spaceY)-offsetY, texX, texY, map->tileSizeX, map->tileSizeY); } } } else { - for (int xp=0; xpwidth; xp++) { - for (int yp=0; ypheight; yp++) { + for (int xp = xI; xp < xF; xp++) { + for (int yp = yI; yp < yF; yp++) { u16 tile = getTile(map, xp, yp); getTilePos(map, tile, &texX, &texY); - sf2d_draw_texture_part_blend(map->texture->texture, (x+(map->tileSizeX*xp)+(xp*map->spaceX)), (y+(map->tileSizeY*yp)+(yp*map->spaceY)), texX, texY, map->tileSizeX, map->tileSizeY, map->texture->blendColor); + sf2d_draw_texture_part_blend(map->texture->texture, x+(map->tileSizeX*xp)+(xp*map->spaceX)-offsetX, y+(map->tileSizeY*yp)+(yp*map->spaceY)-offsetY, texX, texY, map->tileSizeX, map->tileSizeY, map->texture->blendColor); } } } - + + sf2d_set_scissor_test(lua_scissor.mode, lua_scissor.x, lua_scissor.y, lua_scissor.width, lua_scissor.height); + return 0; } /*** Unload a map. @function :unload -@within Methods */ static int map_unload(lua_State *L) { map_userdata *map = luaL_checkudata(L, 1, "LMap"); + free(map->data); - free(map); + + // Remove the reference to the texture in the registry + // registry[map_userdata] = nil + lua_pushnil(L); + lua_copy(L, 1, -1); // map_userdata + lua_pushnil(L); + lua_settable(L, LUA_REGISTRYINDEX); + return 0; } @@ -169,7 +252,6 @@ Return the size of a map. @function :getSize @treturn number width of the map, in tiles @treturn number height of the map, in tiles -@within Methods */ static int map_getSize(lua_State *L) { map_userdata *map = luaL_checkudata(L, 1, "LMap"); @@ -183,10 +265,9 @@ static int map_getSize(lua_State *L) { /*** Return the value of a tile. @function :getTile -@tparam number x X position of the tile -@tparam number y Y position of the tile +@tparam number x X position of the tile (in tiles) +@tparam number y Y position of the tile (in tiles) @treturn number value of the tile -@within Methods */ static int map_getTile(lua_State *L) { map_userdata *map = luaL_checkudata(L, 1, "LMap"); @@ -194,16 +275,16 @@ static int map_getTile(lua_State *L) { int y = luaL_checkinteger(L, 3); lua_pushinteger(L, getTile(map, x, y)); + return 1; } /*** Set the value of a tile. @function :setTile -@tparam number x X position of the tile -@tparam number y Y position of the tile -@tparam number value New value for the tile -@within Methods +@tparam number x X position of the tile (in tiles) +@tparam number y Y position of the tile (in tiles) +@tparam number value new value for the tile */ static int map_setTile(lua_State *L) { map_userdata *map = luaL_checkudata(L, 1, "LMap"); @@ -219,8 +300,8 @@ static int map_setTile(lua_State *L) { /*** Set the space between draw tiles (in pixels). @function :setSpace -@tparam number x X space -@tparam number y Y space +@tparam number x X space (in pixels) +@tparam number y Y space (in pixels) */ static int map_setSpace(lua_State *L) { map_userdata *map = luaL_checkudata(L, 1, "LMap"); @@ -247,7 +328,7 @@ static const struct luaL_Reg map_methods[] = { // module static const struct luaL_Reg map_functions[] = { - {"load", map_load}, + { "load", map_load }, {NULL, NULL} }; diff --git a/source/mic.c b/source/mic.c new file mode 100644 index 0000000..0e3f19a --- /dev/null +++ b/source/mic.c @@ -0,0 +1,307 @@ +/*** +The `mic` module. +@module ctr.mic +@usage local mic = require("ctr.mic") +*/ + +#include <3ds/types.h> +#include <3ds/services/mic.h> + +#include +#include + +#include +#include + +u8* buff; +u32 bufferSize = 0; + +/*** +Initialize the mic module. +@function init +@tparam[opt=0x50000] number bufferSize size of the buffer (must be a multiple of 0x1000) +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer/string error code/message +*/ +static int mic_init(lua_State *L) { + bufferSize = luaL_optinteger(L, 1, 0x50000); + + buff = memalign(0x1000, bufferSize); + if (buff == NULL) { + lua_pushboolean(L, false); + lua_pushstring(L, "Couldn't allocate buffer"); + return 2; + } + Result ret = micInit(buff, bufferSize); + if (ret) { + free(buff); + lua_pushboolean(L, false); + lua_pushinteger(L, ret); + return 2; + } + + lua_pushboolean(L, true); + return 1; +} + +/*** +Shutdown the mic module. +@function shutdown +*/ +static int mic_shutdown(lua_State *L) { + micExit(); + free(buff); + return 0; +} + +/*** +Start sampling from the mic. +@function startSampling +@tparam[opt="PCM8"] encoding encoding encoding of the data to record, can be `"PCM8"` or `"PCM16"` +@tparam[opt=8180] number rate sampling rate, can be `8180`, `10910`, `16360` or `32730` +@tparam[opt=false] boolean loop if true, loop back to the beginning of the buffer when the end is reached +@tparam[opt=bufferFreeSize-4] number size size of audio data to write to the buffer, can be reduced to fit in the buffer +@tparam[opt=false] boolean restart if `true`, start at position 0 in the buffer; if `false`, start after the last sample +*/ +static int mic_startSampling(lua_State *L) { + const char *encodingArg = luaL_optstring(L, 1, "PCM8"); + MICU_Encoding encoding = MICU_ENCODING_PCM8; + if (strcmp(encodingArg, "PCM16")) { + encoding = MICU_ENCODING_PCM16; + } + + u16 rateArg = luaL_optinteger(L, 2, 8180); + MICU_SampleRate rate = MICU_SAMPLE_RATE_8180; + switch (rateArg) { + case 10910: + rate = MICU_SAMPLE_RATE_10910; + case 16360: + rate = MICU_SAMPLE_RATE_16360; + case 32730: + rate = MICU_SAMPLE_RATE_32730; + } + + bool loop = false; + if (lua_isboolean(L, 3)) + loop = lua_toboolean(L, 3); + + + u32 currentSampleSize = micGetSampleDataSize(); + u32 size = luaL_optinteger(L, 4, bufferSize-currentSampleSize-4); + if (size > (bufferSize-currentSampleSize-4)) { + size = bufferSize-currentSampleSize-4; + } + + u32 offset = currentSampleSize; + if (lua_isboolean(L, 5) && lua_toboolean(L, 5)) // restart to 0 + offset = 0; + + MICU_StartSampling(encoding, rate, offset, size, loop); + + return 0; +} + +/*** +Stop sampling from the mic. +@function stopSampling +*/ +static int mic_stopSampling(lua_State *L) { + MICU_StopSampling(); + + return 0; +} + +/*** +Adjust the sampling rate. +@function adjustSampling +@tparam number rate sampling rate, can be `8180`, `10910`, `16360` or `32730` +*/ +static int mic_adjustSampling(lua_State *L) { + u16 rateArg = luaL_checkinteger(L, 1); + MICU_SampleRate rate = MICU_SAMPLE_RATE_8180; + switch (rateArg) { + case 10910: + rate = MICU_SAMPLE_RATE_10910; + case 16360: + rate = MICU_SAMPLE_RATE_16360; + case 32730: + rate = MICU_SAMPLE_RATE_32730; + } + + MICU_AdjustSampling(rate); + + return 0; +} + +/*** +Check whether the mic is sampling. +@function isSampling +@treturn boolean `true` if sampling +*/ +static int mic_isSampling(lua_State *L) { + bool sampling; + MICU_IsSampling(&sampling); + + lua_pushboolean(L, sampling); + return 1; +} + +/*** +Return a string containing the raw sampled audio data. +@function getData +@tparam[opt=true] boolean lastSampleOnly set to `true` to only get the last sample, and to `false` to get everything +@treturn string raw audio data +*/ +static int mic_getData(lua_State *L) { + bool last = false; + if (lua_isboolean(L, 1)) + last = lua_toboolean(L, 1); + + u32 offset = 0; + if (last) { + offset = micGetLastSampleOffset(); + } + u32 size = micGetSampleDataSize(); + + char* data = malloc(size-offset); + for (int i=offset;i #include +#include #include +bool initStateNews = false; + /*** Initialize the news module. @function init */ static int news_init(lua_State *L) { - newsInit(); - + if (!initStateNews) { + newsInit(); + initStateNews = true; + } return 0; } /*** -Send a notification to the user. WIP, do not use !!! +Send a notification to the user. Should work now. @function notification @tparam string title title of the notification -@tparam string message message of the notification -@tparam string imageData data from a JPEG image (content of a file) or raw data -@tparam[OPT=false] boolean jpeg set to `true` if the data is from a JPEG file +@tparam[opt=nil] string message message of the notification, or nil for no message +@tparam[opt=nil] string imageData data from a JPEG image (content of a file) or raw data, or nil for no image +@tparam[opt=false] boolean jpeg set to `true` if the data is from a JPEG file */ static int news_notification(lua_State *L) { const char *title = luaL_checkstring(L, 1); - const char *message = luaL_checkstring(L, 2); + const char *message = luaL_optstring(L, 2, NULL); u32 imageDataLength = 0; const void *imageData = luaL_optlstring(L, 3, NULL, (size_t*)&imageDataLength); @@ -40,14 +45,19 @@ static int news_notification(lua_State *L) { if (lua_isboolean(L, 4)) jpeg = lua_toboolean(L, 4); - const u16* cTitle = 0; - const u16* cMessage = 0; + const u16* cTitle = malloc(strlen(title)*sizeof(u16)); + const u16* cMessage = malloc(strlen(message)*sizeof(u16)); u32 titleLength, messageLength; titleLength = (u32) utf8_to_utf16((uint16_t*)cTitle, (uint8_t*)title, strlen(title)); - messageLength = (u32) utf8_to_utf16((uint16_t*)cMessage, (uint8_t*)message, strlen(message)); + if (message != NULL) { + messageLength = (u32) utf8_to_utf16((uint16_t*)cMessage, (uint8_t*)message, strlen(message)); + } else { + messageLength = 0; + cMessage = NULL; + } - NEWSU_AddNotification(cTitle, titleLength, cMessage, messageLength, imageData, imageDataLength, jpeg); + NEWS_AddNotification(cTitle, titleLength, cMessage, messageLength, imageData, imageDataLength, jpeg); return 0; } @@ -57,8 +67,10 @@ Disable the news module. @function shutdown */ static int news_shutdown(lua_State *L) { - newsExit(); - + if (initStateNews) { + newsExit(); + initStateNews = false; + } return 0; } @@ -77,3 +89,10 @@ int luaopen_news_lib(lua_State *L) { void load_news_lib(lua_State *L) { luaL_requiref(L, "ctr.news", luaopen_news_lib, 0); } + +void unload_news_lib(lua_State *L) { + if (initStateNews) { + newsExit(); + initStateNews = false; + } +} diff --git a/source/ptm.c b/source/ptm.c index 6182635..125e0ea 100644 --- a/source/ptm.c +++ b/source/ptm.c @@ -4,19 +4,25 @@ The `ptm` module. @usage local ptm = require("ctr.ptm") */ #include <3ds/types.h> -#include <3ds/services/ptm.h> +#include <3ds/services/ptmu.h> +#include <3ds/services/ptmsysm.h> #include #include -static Handle *ptmHandle; +bool initStatePTM = false; /*** Initialize the PTM module. @function init */ static int ptm_init(lua_State *L) { - ptmInit(); + if (!initStatePTM) { + ptmuInit(); + ptmSysmInit(); + + initStatePTM = true; + } return 0; } @@ -26,21 +32,26 @@ Disable the PTM module. @function shutdown */ static int ptm_shutdown(lua_State *L) { - ptmExit(); + if (initStatePTM) { + ptmuExit(); + ptmSysmExit(); + + initStatePTM = false; + } return 0; } /*** -Return the shell state. Don't care about this. +Return the shell state. @function getShellState -@treturn number shell state +@treturn boolean shell state, `true` if open, `false` if closed. */ static int ptm_getShellState(lua_State *L) { u8 out = 0; - PTMU_GetShellState(ptmHandle, &out); + PTMU_GetShellState(&out); - lua_pushinteger(L, out); + lua_pushboolean(L, out); return 1; } @@ -52,7 +63,7 @@ Return the battery level. */ static int ptm_getBatteryLevel(lua_State *L) { u8 out = 0; - PTMU_GetBatteryLevel(ptmHandle, &out); + PTMU_GetBatteryLevel(&out); lua_pushinteger(L, out); @@ -66,7 +77,7 @@ Return whether or not the battery is charging. */ static int ptm_getBatteryChargeState(lua_State *L) { u8 out = 0; - PTMU_GetBatteryChargeState(ptmHandle, &out); + PTMU_GetBatteryChargeState(&out); lua_pushboolean(L, out); @@ -80,7 +91,7 @@ Return whether or not the pedometer is counting. */ static int ptm_getPedometerState(lua_State *L) { u8 out = 0; - PTMU_GetPedometerState(ptmHandle, &out); + PTMU_GetPedometerState(&out); lua_pushboolean(L, out); @@ -94,13 +105,39 @@ Return the total steps taken with the system. */ static int ptm_getTotalStepCount(lua_State *L) { u32 steps = 0; - PTMU_GetTotalStepCount(ptmHandle, &steps); + PTMU_GetTotalStepCount(&steps); lua_pushinteger(L, steps); return 1; } +/*** +Setup the new 3DS CPU features (overclock, 4 cores ...) +@newonly +@function configureNew3DSCPU +@tparam boolean enable enable the New3DS CPU features +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code +*/ +static int ptm_configureNew3DSCPU(lua_State *L) { + u8 conf = false; + if (lua_isboolean(L, 1)) + conf = lua_toboolean(L, 1); + + Result ret = PTMSYSM_ConfigureNew3DSCPU(conf); + + if (ret) { + lua_pushboolean(L, false); + lua_pushinteger(L, ret); + return 2; + } + + lua_pushboolean(L, true); + return 1; +} + static const struct luaL_Reg ptm_lib[] = { {"init", ptm_init }, {"shutdown", ptm_shutdown }, @@ -109,6 +146,7 @@ static const struct luaL_Reg ptm_lib[] = { {"getBatteryChargeState", ptm_getBatteryChargeState}, {"getPedometerState", ptm_getPedometerState }, {"getTotalStepCount", ptm_getTotalStepCount }, + {"configureNew3DSCPU", ptm_configureNew3DSCPU }, {NULL, NULL} }; @@ -120,3 +158,10 @@ int luaopen_ptm_lib(lua_State *L) { void load_ptm_lib(lua_State *L) { luaL_requiref(L, "ctr.ptm", luaopen_ptm_lib, 0); } + +void unload_ptm_lib(lua_State *L) { + if (initStatePTM) { + ptmuExit(); + ptmSysmExit(); + } +} diff --git a/source/qtm.c b/source/qtm.c index 2e31cf3..dfa9ca4 100644 --- a/source/qtm.c +++ b/source/qtm.c @@ -14,7 +14,7 @@ The `qtm` module, for headtracking. New3ds only. #include typedef struct { - qtmHeadtrackingInfo *info; + QTM_HeadTrackingInfo *info; } qtm_userdata; static const struct luaL_Reg qtm_methods[]; @@ -22,6 +22,9 @@ static const struct luaL_Reg qtm_methods[]; /*** Initialize the QTM module. @function init +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] integer error code */ static int qtm_init(lua_State *L) { Result ret = qtmInit(); @@ -59,14 +62,14 @@ static int qtm_checkInitialized(lua_State *L) { /*** Return informations about the headtracking -@function getHeadTrackingInfo +@function getHeadtrackingInfo @treturn qtmInfos QTM informations */ static int qtm_getHeadtrackingInfo(lua_State *L) { qtm_userdata *data = lua_newuserdata(L, sizeof(*data)); luaL_getmetatable(L, "LQTM"); lua_setmetatable(L, -2); - Result ret = qtmGetHeadtrackingInfo(0, data->info); + Result ret = QTM_GetHeadTrackingInfo(0, data->info); if (ret) { lua_pushnil(L); return 1; @@ -121,8 +124,10 @@ Convert QTM coordinates to screen coordinates @tparam number coordinates index @tparam[opt=400] number screenWidth specify a screen width @tparam[opt=320] number screenHeight specify a screen height -@treturn number screen X coordinate -@treturn number screen Y coordinate +@treturn[1] number screen X coordinate +@treturn[1] number screen Y coordinate +@treturn[2] nil in case of error +@treturn[2] string error message */ static int qtm_convertCoordToScreen(lua_State *L) { qtm_userdata *info = luaL_checkudata(L, 1, "LQTM"); @@ -130,7 +135,7 @@ static int qtm_convertCoordToScreen(lua_State *L) { index = index - 1; // Lua index begins at 1 if (index > 3 || index < 0) { lua_pushnil(L); - lua_pushnil(L); + lua_pushstring(L, "Index must be between 1 and 3"); return 2; } float screenWidth = luaL_optnumber(L, 3, 400.0f); diff --git a/source/socket.c b/source/socket.c index d921c1c..947a035 100644 --- a/source/socket.c +++ b/source/socket.c @@ -1,5 +1,7 @@ /*** -The `socket` module. Almost like luasocket, but for TCP only. +The `socket` module. Almost like luasocket, but for the TCP part only. +The UDP part is only without connection. +All sockets are not blocking by default. @module ctr.socket @usage local socket = require("ctr.socket") */ @@ -7,6 +9,7 @@ The `socket` module. Almost like luasocket, but for TCP only. #include <3ds.h> #include <3ds/types.h> #include <3ds/services/soc.h> +#include <3ds/services/sslc.h> #include #include @@ -14,7 +17,9 @@ The `socket` module. Almost like luasocket, but for TCP only. #include #include #include +#include #include +#include #include #include #include @@ -24,22 +29,62 @@ The `socket` module. Almost like luasocket, but for TCP only. typedef struct { int socket; struct sockaddr_in addr; - struct hostent *host; // only user for client sockets + struct hostent *host; // only used for client sockets + sslcContext sslContext; + bool isSSL; } socket_userdata; +bool initStateSocket = false; + +u32 rootCertChain = 0; + /*** Initialize the socket module @function init @tparam[opt=0x100000] number buffer size (in bytes), must be a multiple of 0x1000 +@treturn[1] boolean `true` if everything went fine +@treturn[2] boolean `false` in case of error +@treturn[2] number/string error code/message */ static int socket_init(lua_State *L) { - u32 size = luaL_optinteger(L, 1, 0x100000); - Result ret = SOC_Initialize((u32*)memalign(0x1000, size), size); + if (!initStateSocket) { + u32 size = luaL_optinteger(L, 1, 0x100000); + if (size%0x1000 != 0) { + lua_pushboolean(L, false); + lua_pushstring(L, "Not a multiple of 0x1000"); + return 2; + } + + u32* mem = (u32*)memalign(0x1000, size); + if (mem == NULL) { + lua_pushboolean(L, false); + lua_pushstring(L, "Failed to allocate memory"); + return 2; + } + + Result ret = socInit(mem, size); - if (ret) { - lua_pushboolean(L, false); - lua_pushinteger(L, ret); - return 2; + if (R_FAILED(ret)) { + lua_pushboolean(L, false); + lua_pushinteger(L, ret); + return 2; + } + + ret = sslcInit(0); + if (R_FAILED(ret)) { + lua_pushboolean(L, false); + lua_pushinteger(L, ret); + return 2; + } + + sslcCreateRootCertChain(&rootCertChain); + sslcRootCertChainAddDefaultCert(rootCertChain, SSLC_DefaultRootCert_CyberTrust, NULL); + sslcRootCertChainAddDefaultCert(rootCertChain, SSLC_DefaultRootCert_AddTrust_External_CA, NULL); + sslcRootCertChainAddDefaultCert(rootCertChain, SSLC_DefaultRootCert_COMODO, NULL); + sslcRootCertChainAddDefaultCert(rootCertChain, SSLC_DefaultRootCert_USERTrust, NULL); + sslcRootCertChainAddDefaultCert(rootCertChain, SSLC_DefaultRootCert_DigiCert_EV, NULL); + + initStateSocket = true; } lua_pushboolean(L, true); @@ -47,11 +92,16 @@ static int socket_init(lua_State *L) { } /*** -Disable the socket module. Must be called before exiting ctrµLua. +Disable the socket module. @function shutdown */ static int socket_shutdown(lua_State *L) { - SOC_Shutdown(); + if (initStateSocket) { + sslcDestroyRootCertChain(rootCertChain); + sslcExit(); + socExit(); + initStateSocket = false; + } return 0; } @@ -59,7 +109,9 @@ static int socket_shutdown(lua_State *L) { /*** Return a TCP socket. @function tcp -@treturn TCPMaster TCP socket +@treturn[1] TCPMaster TCP socket +@treturn[2] nil in case of error +@treturn[2] string error message */ static int socket_tcp(lua_State *L) { socket_userdata *userdata = lua_newuserdata(L, sizeof(*userdata)); @@ -75,9 +127,156 @@ static int socket_tcp(lua_State *L) { userdata->addr.sin_family = AF_INET; + userdata->isSSL = false; + fcntl(userdata->socket, F_SETFL, fcntl(userdata->socket, F_GETFL, 0)|O_NONBLOCK); + return 1; } +/*** +Return an UDP socket. +@function udp +@treturn[1] UDPMaster UDP socket +@treturn[2] nil in case of error +@treturn[2] string error message +*/ +static int socket_udp(lua_State *L) { + socket_userdata *userdata = lua_newuserdata(L, sizeof(*userdata)); + luaL_getmetatable(L, "LSocket"); + lua_setmetatable(L, -2); + + userdata->socket = socket(AF_INET, SOCK_DGRAM, 0); + if (userdata->socket < 0) { + lua_pushnil(L); + lua_pushstring(L, strerror(errno)); + return 2; + } + + userdata->addr.sin_family = AF_INET; + fcntl(userdata->socket, F_SETFL, fcntl(userdata->socket, F_GETFL, 0)|O_NONBLOCK); + + return 1; +} + +/*** +Add a trusted root CA to the certChain. +@function addTrustedRootCA +@tparam string cert DER cert +@treturn[1] boolean `true` if everything went fine +@treturn[2] nil in case of error +@treturn[2] number error code +*/ +static int socket_addTrustedRootCA(lua_State *L) { + size_t size = 0; + const char* cert = luaL_checklstring(L, 1, &size); + + Result ret = sslcAddTrustedRootCA(rootCertChain, (u8*)cert, size, NULL); + if (R_FAILED(ret)) { + lua_pushnil(L); + lua_pushinteger(L, ret); + return 2; + } + + lua_pushboolean(L, true); + return 1; +} + +/*** +All sockets +@section sockets +*/ + +/*** +Bind a socket. The socket object become a socketServer object. +@function :bind +@tparam number port the port to bind the socket on. +*/ +static int socket_bind(lua_State *L) { + socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); + int port = luaL_checkinteger(L, 2); + + userdata->addr.sin_addr.s_addr = gethostid(); + userdata->addr.sin_port = htons(port); + + bind(userdata->socket, (struct sockaddr*)&userdata->addr, sizeof(userdata->addr)); + + return 0; +} + +/*** +Close an existing socket. +@function :close +*/ +static int socket_close(lua_State *L) { + socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); + + if (userdata->isSSL) { + sslcDestroyContext(&userdata->sslContext); + } + + closesocket(userdata->socket); + + return 0; +} + +/*** +Get some informations from a socket. +@function :getpeername +@treturn string IP +@treturn number port +*/ +static int socket_getpeername(lua_State *L) { + socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); + + struct sockaddr_in addr; + socklen_t addrSize = sizeof(addr); + + getpeername(userdata->socket, (struct sockaddr*)&addr, &addrSize); + + lua_pushstring(L, inet_ntoa(addr.sin_addr)); + lua_pushinteger(L, ntohs(addr.sin_port)); + + return 2; +} + +/*** +Get some local informations from a socket. +@function :getsockname +@treturn string IP +@treturn number port +*/ +static int socket_getsockname(lua_State *L) { + socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); + + struct sockaddr_in addr; + socklen_t addrSize = sizeof(addr); + + getsockname(userdata->socket, (struct sockaddr*)&addr, &addrSize); + + lua_pushstring(L, inet_ntoa(addr.sin_addr)); + lua_pushinteger(L, ntohs(addr.sin_port)); + + return 2; +} + +/*** +Set if the socket should be blocking. +@function :setBlocking +@tparam[opt=true] boolean block if `false`, the socket won't block +*/ +static int socket_setBlocking(lua_State *L) { + socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); + bool block = true; + if (lua_isboolean(L, 2)) + block = lua_toboolean(L, 2); + + int flags = fcntl(userdata->socket, F_GETFL, 0); + flags = block?(flags&~O_NONBLOCK):(flags|O_NONBLOCK); + fcntl(userdata->socket, F_SETFL, flags); + + return 0; +} + /*** TCP Sockets @section TCP @@ -94,6 +293,7 @@ static int socket_accept(lua_State *L) { socket_userdata *client = lua_newuserdata(L, sizeof(*client)); luaL_getmetatable(L, "LSocket"); lua_setmetatable(L, -2); + client->isSSL = false; socklen_t addrSize = sizeof(client->addr); client->socket = accept(userdata->socket, (struct sockaddr*)&client->addr, &addrSize); @@ -105,50 +305,26 @@ static int socket_accept(lua_State *L) { return 1; } -/*** -Bind a socket. The TCP object become a TCPServer object. -@function :bind -@tparam number port the port to bind the socket on. -*/ -static int socket_bind(lua_State *L) { - socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); - int port = luaL_checkinteger(L, 2); - - userdata->addr.sin_addr.s_addr = htonl(INADDR_ANY); - userdata->addr.sin_port = htons(port); - - bind(userdata->socket, (struct sockaddr*)&userdata->addr, sizeof(userdata->addr)); - - return 0; -} - -/*** -Close an existing socket. -@function :close -*/ -static int socket_close(lua_State *L) { - socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); - - closesocket(userdata->socket); - - return 0; -} - /*** Connect a socket to a server. The TCP object becomes a TCPClient object. @function :connect @tparam string host address of the host @tparam number port port of the server +@tparam[opt=false] boolean ssl use SSL if `true` +@treturn[1] boolean true if success +@treturn[2] boolean false if failed +@treturn[2] string error string */ static int socket_connect(lua_State *L) { socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); char *addr = (char*)luaL_checkstring(L, 2); int port = luaL_checkinteger(L, 3); + bool ssl = lua_toboolean(L, 4); userdata->host = gethostbyname(addr); if (userdata->host == NULL) { lua_pushnil(L); - lua_pushstring(L, "No such host"); + lua_pushstring(L, strerror(errno)); return 2; } @@ -157,11 +333,23 @@ static int socket_connect(lua_State *L) { if (connect(userdata->socket, (const struct sockaddr*)&userdata->addr, sizeof(userdata->addr)) < 0) { lua_pushnil(L); - lua_pushstring(L, "Connection failed"); + lua_pushstring(L, strerror(errno)); return 2; } - lua_pushinteger(L, 1); + if (ssl) { // SSL context setup + sslcCreateContext(&userdata->sslContext, userdata->socket, SSLCOPT_Default, addr); + sslcContextSetRootCertChain(&userdata->sslContext, rootCertChain); + if (R_FAILED(sslcStartConnection(&userdata->sslContext, NULL, NULL))) { + sslcDestroyContext(&userdata->sslContext); + lua_pushnil(L); + lua_pushstring(L, "SSL connection failed"); + return 2; + } + userdata->isSSL = true; + } + + lua_pushboolean(L, 1); return 1; } @@ -181,26 +369,74 @@ static int socket_listen(lua_State *L) { /*** Receive some data from the socket. +If no data is avaible, it returns an empty string (non-blocking). @function :receive -@tparam number size amount of data to receive; can also be "*a" to receive everything -@treturn string data +@tparam[opt="l"] number/string size amount of bytes to receive; or + "a" to receive everything, + "l" to receive the next line, skipping the end of line, + "L" to receive the next line, keeping the end of line. +@treturn[1] string data +@treturn[2] nil in case of error +@treturn[2] integer error code */ static int socket_receive(lua_State *L) { socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); int count = 0; int flags = 0; + if (lua_isnumber(L, 2)) { count = luaL_checkinteger(L, 2); - } else if (lua_isstring(L, 2) && luaL_checkstring(L, 2) == (char*)&"*a") { - count = SIZE_MAX/2; } else { - lua_pushnil(L); - lua_pushstring(L, ""); - return 2; + const char *p = luaL_optstring(L, 2, "l"); + if (*p == 'a') { + count = SIZE_MAX/2; + + } else if (*p == 'l') { + luaL_Buffer b; + luaL_buffinit(L, &b); + + char buff; + if (!userdata->isSSL) { + while (recv(userdata->socket, &buff, 1, flags) > 0 && buff != '\n') luaL_addchar(&b, buff); + } else { + while (!R_FAILED(sslcRead(&userdata->sslContext, &buff, 1, false)) && buff != '\n') luaL_addchar(&b, buff); + } + + luaL_pushresult(&b); + return 1; + + } else if (*p == 'L') { + luaL_Buffer b; + luaL_buffinit(L, &b); + + char buff; + if (!userdata->isSSL) { + while (buff != '\n' && recv(userdata->socket, &buff, 1, flags) > 0) luaL_addchar(&b, buff); + } else { + while (buff != '\n' && !R_FAILED(sslcRead(&userdata->sslContext, &buff, 1, false))) luaL_addchar(&b, buff); + } + + luaL_pushresult(&b); + return 1; + + } else { + return luaL_argerror(L, 2, "invalid format"); + } } - char *buff = malloc(count); - recv(userdata->socket, buff, count, flags); + char *buff = malloc(count+1); + int len; + if (!userdata->isSSL) { + len = recv(userdata->socket, buff, count, flags); + } else { + len = sslcRead(&userdata->sslContext, buff, count, false); + if (R_FAILED(len)) { + lua_pushnil(L); + lua_pushinteger(L, len); + return 2; + } + } + *(buff+len) = 0x0; // text end lua_pushstring(L, buff); return 1; @@ -210,36 +446,151 @@ static int socket_receive(lua_State *L) { Send some data over the TCP socket. @function :send @tparam string data data to send -@treturn number amount of data sent +@treturn[1] number amount of data sent +@treturn[2] nil in case of error +@treturn[2] integer/string error code/message */ static int socket_send(lua_State *L) { socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); size_t size = 0; char *data = (char*)luaL_checklstring(L, 2, &size); - size_t sent = send(userdata->socket, data, size, 0); + ssize_t sent; + if (!userdata->isSSL) { + sent = send(userdata->socket, data, size, 0); + } else { + sent = sslcWrite(&userdata->sslContext, data, size); + if (R_FAILED(sent)) { + lua_pushnil(L); + lua_pushinteger(L, sent); + return 2; + } + } + + if (sent < 0) { + lua_pushnil(L); + lua_pushstring(L, strerror(errno)); + return 2; + } lua_pushinteger(L, sent); return 1; } -// module functions +/*** +UDP sockets +@section UDP +*/ + +/*** +Receive a datagram from the UDP object. +@function :receivefrom +@tparam[opt=8191] number count maximum amount of bytes to receive from the datagram. Must be lower than 8192. +@treturn[1] string data +@treturn[1] string IP address of the sender +@treturn[1] integer port number of the sender +@treturn[2] nil in case of error or no datagram to receive +@treturn[2] string error message +*/ +static int socket_receivefrom(lua_State *L) { + socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); + int count = luaL_optinteger(L, 2, 8191); + + struct sockaddr_in from; + socklen_t addr_len; + + char* buffer = calloc(1, count+1); + ssize_t n = recvfrom(userdata->socket, buffer, count, 0, (struct sockaddr *)&from, &addr_len); + + if (n == 0) { + free(buffer); + lua_pushnil(L); + lua_pushstring(L, "nothing to receive"); + return 2; + + } else if (n < 0) { + free(buffer); + lua_pushnil(L); + lua_pushstring(L, strerror(n)); + return 2; + } + + lua_pushstring(L, buffer); + lua_pushstring(L, inet_ntoa(from.sin_addr)); + lua_pushinteger(L, ntohs(from.sin_port)); + + free(buffer); + + return 3; +} + +/*** +Send a datagram to the specified IP and port. +@function :sendto +@tparam string data data to send +@tparam string host IP/hostname of the recipient +@tparam number port port number of the recipient +@treturn[1] boolean true in case of success +@treturn[2] boolean false in case of error +@treturn[2] string error message +*/ +static int socket_sendto(lua_State *L) { + socket_userdata *userdata = luaL_checkudata(L, 1, "LSocket"); + size_t datasize; + const char *data = luaL_checklstring(L, 2, &datasize); + const char *hostname = luaL_checkstring(L, 3); + int port = luaL_checkinteger(L, 4); + + struct hostent *hostinfo = gethostbyname(hostname); + if (hostinfo == NULL) { + lua_pushboolean(L, false); + lua_pushstring(L, "unknown host"); + return 2; + } + + struct sockaddr_in to; + to.sin_addr = *(struct in_addr *)hostinfo->h_addr; + to.sin_port = htons(port); + to.sin_family = AF_INET; + + ssize_t n = sendto(userdata->socket, data, datasize, 0, (struct sockaddr *)&to, sizeof(to)); + + if (n < 0) { + lua_pushboolean(L, false); + lua_pushstring(L, strerror(n)); + return 2; + } + + lua_pushboolean(L, true); + + return 1; +} + +// Module functions static const struct luaL_Reg socket_functions[] = { - {"init", socket_init }, - {"shutdown", socket_shutdown}, - {"tcp", socket_tcp }, + { "init", socket_init }, + { "shutdown", socket_shutdown }, + { "tcp", socket_tcp }, + { "udp", socket_udp }, + { "addTrustedRootCA", socket_addTrustedRootCA }, {NULL, NULL} }; -// object +// Object methods static const struct luaL_Reg socket_methods[] = { - {"accept", socket_accept }, - {"bind", socket_bind }, - {"close", socket_close }, - {"connect", socket_connect }, - {"listen", socket_listen }, - {"receive", socket_receive }, - {"send", socket_send }, + { "accept", socket_accept }, + { "bind", socket_bind }, + { "close", socket_close }, + { "setBlocking", socket_setBlocking }, + { "__gc", socket_close }, + { "connect", socket_connect }, + { "listen", socket_listen }, + { "receive", socket_receive }, + { "receivefrom", socket_receivefrom }, + { "send", socket_send }, + { "sendto", socket_sendto }, + { "getpeername", socket_getpeername }, + { "getsockname", socket_getsockname }, {NULL, NULL} }; diff --git a/source/texture.c b/source/texture.c index a369737..d099daa 100644 --- a/source/texture.c +++ b/source/texture.c @@ -12,6 +12,12 @@ The `gfx.texture` module. #include #include +#define STB_IMAGE_IMPLEMENTATION +#include +#define STB_IMAGE_WRITE_IMPLEMENTATION +#include +#include + #include "texture.h" int getType(const char *name) { @@ -32,12 +38,14 @@ int getType(const char *name) { // module functions /*** -Load a texture from a file. Supported formats: PNG, JPEG, BMP. +Load a texture from a file. Supported formats: PNG, JPEG, BMP, GIF, PSD, TGA, HDR, PIC, PNM. @function load @tparam string path path to the image file @tparam[opt=PLACE_RAM] number place where to put the loaded texture -@tparam[opt=auto] number type type of the image -@treturn texture the loaded texture object +@tparam[opt=auto] number type type of the image. This is only used to force loading PNG, JPEG or BMP files with the sfil library; any value between 5 and 250 will force using the stbi library. Leave nil to autodetect the format. +@treturn[1] texture the loaded texture object +@treturn[2] nil in case of error +@treturn[2] string error message */ static int texture_load(lua_State *L) { const char *path = luaL_checkstring(L, 1); @@ -46,10 +54,10 @@ static int texture_load(lua_State *L) { texture_userdata *texture; texture = (texture_userdata *)lua_newuserdata(L, sizeof(*texture)); - + luaL_getmetatable(L, "LTexture"); lua_setmetatable(L, -2); - + if (type==3) type = getType(path); if (type==0) { //PNG texture->texture = sfil_load_PNG_file(path, place); @@ -58,21 +66,27 @@ static int texture_load(lua_State *L) { } else if (type==2) { //BMP texture->texture = sfil_load_BMP_file(path, place); //appears to be broken right now. } else { - lua_pushnil(L); - lua_pushstring(L, "Bad type"); - return 2; + int w, h; + char* data = (char*)stbi_load(path, &w, &h, NULL, 4); + if (data == NULL) { + lua_pushnil(L); + lua_pushstring(L, "Can't open file"); + return 2; + } + texture->texture = sf2d_create_texture_mem_RGBA8(data, w, h, TEXFMT_RGBA8, place); + free(data); } - + if (texture->texture == NULL) { lua_pushnil(L); lua_pushstring(L, "No such file"); return 2; } - + texture->scaleX = 1.0f; texture->scaleY = 1.0f; texture->blendColor = 0xffffffff; - + return 1; } @@ -88,20 +102,20 @@ static int texture_new(lua_State *L) { int w = luaL_checkinteger(L, 1); int h = luaL_checkinteger(L, 2); u8 place = luaL_checkinteger(L, 3); - + texture_userdata *texture; texture = (texture_userdata *)lua_newuserdata(L, sizeof(*texture)); - + luaL_getmetatable(L, "LTexture"); lua_setmetatable(L, -2); - + texture->texture = sf2d_create_texture(w, h, TEXFMT_RGBA8, place); sf2d_texture_tile32(texture->texture); - + texture->scaleX = 1.0f; texture->scaleY = 1.0f; texture->blendColor = 0xffffffff; - + return 1; } @@ -113,35 +127,41 @@ Texture object /*** Draw a texture. @function :draw -@tparam number x X position -@tparam number y Y position -@tparam[opt=0.0] number rad rotation of the texture (in radians) +@tparam integer x X position +@tparam integer y Y position +@tparam[opt=0.0] number rad rotation of the texture around the hotspot (in radians) +@tparam[opt=0.0] number hotspotX the hostpot X coordinate +@tparam[opt=0.0] number hotspotY the hostpot Y coordinate */ static int texture_draw(lua_State *L) { texture_userdata *texture = luaL_checkudata(L, 1, "LTexture"); int x = luaL_checkinteger(L, 2); int y = luaL_checkinteger(L, 3); float rad = luaL_optnumber(L, 4, 0.0f); - + float hotspotX = luaL_optnumber(L, 5, 0.0f); + float hotspotY = luaL_optnumber(L, 6, 0.0f); + if (rad == 0.0f && texture->scaleX == 1.0f && texture->scaleY == 1.0f && texture->blendColor == 0xffffffff) { - sf2d_draw_texture(texture->texture, x, y); + sf2d_draw_texture(texture->texture, x - hotspotX, y - hotspotY); } else { - sf2d_draw_texture_part_rotate_scale_blend(texture->texture, x, y, rad, 0, 0, texture->texture->width, texture->texture->height, texture->scaleX, texture->scaleY, texture->blendColor); + sf2d_draw_texture_rotate_scale_hotspot_blend(texture->texture, x, y, rad, texture->scaleX, texture->scaleY, hotspotX, hotspotY, texture->blendColor); } - + return 0; } /*** Draw a part of the texture @function :drawPart -@tparam number x X position -@tparam number y Y position -@tparam number sx X position of the beginning of the part -@tparam number sy Y position of the beginning of the part -@tparam number w width of the part -@tparam number h height of the part -@tparam[opt=0.0] number rad rotation of the part (in radians) +@tparam integer x X position +@tparam integer y Y position +@tparam integer sx X position of the beginning of the part +@tparam integer sy Y position of the beginning of the part +@tparam integer w width of the part +@tparam integer h height of the part +@tparam[opt=0.0] number rad rotation of the part around the hotspot (in radians) +@tparam[opt=0.0] number hotspotX the hostpot X coordinate +@tparam[opt=0.0] number hotspotY the hostpot Y coordinate */ static int texture_drawPart(lua_State *L) { texture_userdata *texture = luaL_checkudata(L, 1, "LTexture"); @@ -152,9 +172,11 @@ static int texture_drawPart(lua_State *L) { int w = luaL_checkinteger(L, 6); int h = luaL_checkinteger(L, 7); int rad = luaL_optnumber(L, 8, 0.0f); - - sf2d_draw_texture_part_rotate_scale_blend(texture->texture, x, y, rad, sx, sy, w, h, texture->scaleX, texture->scaleY, texture->blendColor); - + float hotspotX = luaL_optnumber(L, 9, 0.0f); + float hotspotY = luaL_optnumber(L, 10, 0.0f); + + sf2d_draw_texture_part_rotate_scale_hotspot_blend(texture->texture, x, y, rad, sx, sy, w, h, texture->scaleX, texture->scaleY, hotspotX, hotspotY, texture->blendColor); + return 0; } @@ -179,12 +201,12 @@ Unload a texture. */ static int texture_unload(lua_State *L) { texture_userdata *texture = luaL_checkudata(L, 1, "LTexture"); - + if (texture->texture == NULL) return 0; sf2d_free_texture(texture->texture); texture->texture = NULL; - + return 0; } @@ -192,16 +214,16 @@ static int texture_unload(lua_State *L) { Rescale the texture. The default scale is `1.0`. @function :scale @tparam number scaleX new scale of the width -@tparam number scaleY new scale of the height +@tparam[opt=scaleX] number scaleY new scale of the height */ static int texture_scale(lua_State *L) { texture_userdata *texture = luaL_checkudata(L, 1, "LTexture"); float sx = luaL_checknumber(L, 2); - float sy = luaL_checknumber(L, 3); - + float sy = luaL_optnumber(L, 3, sx); + texture->scaleX = sx; texture->scaleY = sy; - + return 0; } @@ -216,9 +238,9 @@ static int texture_getPixel(lua_State *L) { texture_userdata *texture = luaL_checkudata(L, 1, "LTexture"); int x = luaL_checkinteger(L, 2); int y = luaL_checkinteger(L, 3); - + lua_pushinteger(L, sf2d_get_pixel(texture->texture, x, y)); - + return 1; } @@ -234,9 +256,9 @@ static int texture_setPixel(lua_State *L) { int x = luaL_checkinteger(L, 2); int y = luaL_checkinteger(L, 3); u32 color = luaL_checkinteger(L, 4); - + sf2d_set_pixel(texture->texture, x, y, color); - + return 0; } @@ -246,14 +268,106 @@ Set the blend color of the texture. @tparam number color new blend color */ static int texture_setBlendColor(lua_State *L) { - texture_userdata *texture = luaL_checkudata(L, 1, "LTexture"); + texture_userdata *texture = luaL_checkudata(L, 1, "LTexture"); u32 color = luaL_checkinteger(L, 2); - + texture->blendColor = color; - + return 0; } +/*** +Get the blend color of the texture. +@function :getBlendColor +@treturn number the blend color +*/ +static int texture_getBlendColor(lua_State *L) { + texture_userdata *texture = luaL_checkudata(L, 1, "LTexture"); + + lua_pushinteger(L, texture->blendColor); + + return 1; +} + +/*** +Save a texture to a file. +@function :save +@tparam string filename path to the file to save the texture to +@tparam[opt=TYPE_PNG] number type type of the image to save. Can be TYPE_PNG or TYPE_BMP +@treturn[1] boolean true on success +@treturn[2] boolean `false` in case of error +@treturn[2] string error message +*/ +static int texture_save(lua_State *L) { + texture_userdata *texture = luaL_checkudata(L, 1, "LTexture"); + const char* path = luaL_checkstring(L, 2); + u8 type = luaL_optinteger(L, 3, 0); + + int result = 0; + if (type == 0) { // PNG + FILE* file = fopen(path, "wb"); + if (file == NULL) { + lua_pushboolean(L, false); + lua_pushstring(L, "Can open file"); + return 2; + } + png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + png_infop infos = png_create_info_struct(png); + setjmp(png_jmpbuf(png)); + png_init_io(png, file); + + png_set_IHDR(png, infos, texture->texture->width, texture->texture->height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); + png_write_info(png, infos); + + png_bytep row = malloc(4 * texture->texture->width * sizeof(png_byte)); + + for(int y=0;ytexture->height;y++) { + for (int x=0;xtexture->width;x++) { + ((u32*)row)[x] = __builtin_bswap32(sf2d_get_pixel(texture->texture, x, y)); + } + png_write_row(png, row); + } + + png_write_end(png, NULL); + + fclose(file); + png_free_data(png, infos, PNG_FREE_ALL, -1); + png_destroy_write_struct(&png, &infos); + free(row); + + result = 1; + + } else if (type == 2) { // BMP + u32* buff = malloc(texture->texture->width * texture->texture->height * 4); + if (buff == NULL) { + lua_pushboolean(L, false); + lua_pushstring(L, "Failed to allocate buffer"); + return 2; + } + for (int y=0;ytexture->height;y++) { + for (int x=0;xtexture->width;x++) { + buff[x+(y*texture->texture->width)] = __builtin_bswap32(sf2d_get_pixel(texture->texture, x, y)); + } + } + result = stbi_write_bmp(path, texture->texture->width, texture->texture->height, 4, buff); + free(buff); + + } else { + lua_pushboolean(L, false); + lua_pushstring(L, "Not a valid type"); + return 2; + } + + if (result == 0) { + lua_pushboolean(L, false); + lua_pushstring(L, "Failed to save the texture"); + return 2; + } + + lua_pushboolean(L, true); + return 1; +} + // object static const struct luaL_Reg texture_methods[] = { { "draw", texture_draw }, @@ -264,6 +378,8 @@ static const struct luaL_Reg texture_methods[] = { { "getPixel", texture_getPixel }, { "setPixel", texture_setPixel }, { "setBlendColor", texture_setBlendColor }, + { "getBlendColor", texture_getBlendColor }, + { "save", texture_save }, { "__gc", texture_unload }, {NULL, NULL} }; diff --git a/source/thread.c b/source/thread.c new file mode 100644 index 0000000..4fc8836 --- /dev/null +++ b/source/thread.c @@ -0,0 +1,160 @@ +/*** +The `thread` module. +@module ctr.thread +@usage local thread = require("ctr.thread") +*/ + +#include +#include +#include + +#include <3ds/types.h> +#include <3ds/thread.h> +#include <3ds/services/apt.h> + +#include +#include + +void load_ctr_lib(lua_State *L); + +typedef struct { + Thread thread; + const char *code; + char *error; +} thread_userdata; + +void entryPoint(void *thread) { + lua_State *T = luaL_newstate(); + luaL_openlibs(T); + load_ctr_lib(T); + + if (luaL_dostring(T, ((thread_userdata*)thread)->code)) { + const char* lerror = luaL_checkstring(T, -1); + ((thread_userdata*)thread)->error = malloc(strlen(lerror)+1); + strcpy(((thread_userdata*)thread)->error, lerror); + } + + int exitCode = 0; + if (lua_isinteger(T, -1)) { + exitCode = lua_tointeger(T, -1); + } + lua_close(T); + threadExit(exitCode); +} + +// module +/*** +Set the maximum CPU time allocated to threads on CPU #1. +@function setCpuLimit +@tparam number time in percents. +*/ +static int thread_setCpuLimit(lua_State *L) { + u32 percent = luaL_checkinteger(L, 1); + APT_SetAppCpuTimeLimit(percent); + + return 0; +} + +/*** +Start a new thread. +@function start +@tparam string code Lua code to load in the new thread. May not work with dumped functions. +@tparam[opt=0] number cpu must be >= 0 and < 2 for 3ds or < 4 for new3ds +@tparam[opt=0x27] number priority must be > 0x18 and < 0x3f; the lower is higher. +@tparam[opt=0x100000] number stacksize size of the stack, increase it in case of OoM +@treturn thread a new thread object +*/ +static int thread_start(lua_State *L) { + const char* code = luaL_checkstring(L, 1); + s32 processor = luaL_optinteger(L, 2, 0); + s32 priority = luaL_optinteger(L, 3, 0x27); + size_t stackSize = luaL_optinteger(L, 4, 0x100000); + + thread_userdata *thread = lua_newuserdata(L, sizeof(thread_userdata*)); + luaL_getmetatable(L, "LThread"); + lua_setmetatable(L, -2); + + thread->code = code; + thread->error = NULL; + thread->thread = threadCreate(entryPoint, thread, stackSize, priority, processor, true); + + return 1; +} + +/*** +Wait for a thread to finish. +@function :join +@tparam[opt=2^32-1] number timeout in ns +@treturn number exit code +@treturn string last error, or nil +*/ +static int thread_join(lua_State *L) { + thread_userdata *thread = luaL_checkudata(L, 1, "LThread"); + u64 timeout = luaL_optinteger(L, 2, 4294967295); + + threadJoin(thread->thread, timeout); + + lua_pushinteger(L, threadGetExitCode(thread->thread)); + if (thread->error != NULL) { + lua_pushstring(L, thread->error); + return 2; + } + return 1; +} + +/*** +Return the last error of a thread. +@function :lastError +@treturn string last error, or nil +*/ +static int thread_lastError(lua_State *L) { + thread_userdata *thread = luaL_checkudata(L, 1, "LThread"); + + if (thread->error == NULL) { + lua_pushnil(L); + } else { + lua_pushstring(L, thread->error); + } + return 1; +} + +/*** +Destroy a finished thread. +@function :destroy +*/ +static int thread_destroy(lua_State *L) { + thread_userdata *thread = luaL_checkudata(L, 1, "LThread"); + + threadFree(thread->thread); + free(thread->error); + + return 0; +} + +static const struct luaL_Reg thread_lib[] = { + {"start", thread_start}, + {"setCpuLimit", thread_setCpuLimit}, + {NULL, NULL} +}; + +static const struct luaL_Reg thread_methods[] = { + {"join", thread_join}, + {"lastError", thread_lastError}, + {"destroy", thread_destroy}, + {"__gc", thread_destroy}, + {NULL, NULL} +}; + +int luaopen_thread_lib(lua_State *L) { + luaL_newmetatable(L, "LThread"); + lua_pushvalue(L, -1); + lua_setfield(L, -2, "__index"); + luaL_setfuncs(L, thread_methods, 0); + + luaL_newlib(L, thread_lib); + return 1; +} + +void load_thread_lib(lua_State *L) { + luaL_requiref(L, "ctr.thread", luaopen_thread_lib, 0); +} diff --git a/source/uds.c b/source/uds.c new file mode 100644 index 0000000..3139fbf --- /dev/null +++ b/source/uds.c @@ -0,0 +1,589 @@ +/*** +The `uds` module. Used for 3DS-to-3DS wireless communication. +The default wlancommID is 0x637472c2. +@module ctr.uds +@usage local uds = require("ctr.uds") +*/ + +#include +#include +#include + +#include <3ds/result.h> +#include <3ds/types.h> +#include <3ds/services/uds.h> + +#include +#include + +bool initStateUDS = false; + +udsBindContext bind = {0}; +udsNetworkStruct network = {0}; +u8 data_channel = 1; + +/*** +Initialize the UDS module. +@function init +@tparam[opt=0x3000] number context size in bytes, must be a multiple of 0x1000 +@tparam[opt=3DS username] string username UTF-8 username on the network +@treturn[1] boolean `true` on success +@treturn[2] boolean `false` on error +@treturn[2] number error code +*/ +static int uds_init(lua_State *L) { + if (!initStateUDS) { + size_t memSize = luaL_optinteger(L, 1, 0x3000); + const char* username = luaL_optstring(L, 2, NULL); + + Result ret = udsInit(memSize, username); + if (R_FAILED(ret)) { + lua_pushboolean(L, false); + lua_pushinteger(L, ret); + return 2; + } + initStateUDS = true; + } + + lua_pushboolean(L, true); + return 1; +} + +/*** +Disable the UDS module. +@function shutdown +*/ +static int uds_shutdown(lua_State *L) { + udsExit(); + initStateUDS = false; + + return 0; +} + +/*** +Scan for network beacons. +@function scan +@tparam[opt=0x637472c2] number commID application local-WLAN unique ID +@tparam[opt=0] number id8 additional ID to use different network types +@tparam[opt=all] string hostMAC if set, only scan networks from this MAC address (format: `XX:XX:XX:XX:XX:XX`, with hexadecimal values) +@treturn[1] table a table containing beacons objects +@treturn[2] nil +@treturn[2] number/string error code +*/ +static int uds_scan(lua_State *L) { + static const size_t tmpbuffSize = 0x4000; + u32* tmpbuff = malloc(tmpbuffSize); + + udsNetworkScanInfo* networks = NULL; + size_t totalNetworks = 0; + + u32 wlanCommID = luaL_optinteger(L, 1, 0x637472c2); + u8 id8 = luaL_optinteger(L, 2, 0); + + // MAC address conversion + const char* hostMACString = luaL_optstring(L, 3, NULL); + u8* hostMAC; + if (hostMACString != NULL) { + hostMAC = malloc(6*sizeof(u8)); + unsigned int tmpMAC[6]; + if (sscanf(hostMACString, "%x:%x:%x:%x:%x:%x", &tmpMAC[0], &tmpMAC[1], &tmpMAC[2], &tmpMAC[3], &tmpMAC[4], &tmpMAC[5]) != 6) { + free(tmpbuff); + free(hostMAC); + lua_pushnil(L); + lua_pushstring(L, "Bad MAC formating"); + return 2; + } + for (int i=0;i<6;i++) { + hostMAC[i] = tmpMAC[i]; + } + } else { + hostMAC = NULL; + } + + udsConnectionStatus status; + udsGetConnectionStatus(&status); + Result ret = udsScanBeacons(tmpbuff, tmpbuffSize, &networks, &totalNetworks, wlanCommID, id8, hostMAC, (status.status!=0x03)); + free(tmpbuff); + free(hostMAC); + if (R_FAILED(ret)) { + lua_pushnil(L); + lua_pushinteger(L, ret); + return 2; + } + + // Convert the networks to a table of userdatas + lua_createtable(L, 0, totalNetworks); + for (int i=1;i<=totalNetworks;i++) { + udsNetworkScanInfo* beacon = lua_newuserdata(L, sizeof(udsNetworkScanInfo)); + luaL_getmetatable(L, "LUDSBeaconScan"); + lua_setmetatable(L, -2); + memcpy(beacon, &networks[0], sizeof(udsNetworkScanInfo)); + lua_seti(L, -3, i); + } + free(networks); + + return 1; +} + +/*** +Check for data in the receive buffer. +@function available +@treturn boolean `true` if there is data to receive, `false` if not +*/ +static int uds_available(lua_State *L) { + lua_pushboolean(L, udsWaitDataAvailable(&bind, false, false)); + return 1; +} + +/*** +Return a packet from the receive buffer. +@function receive +@tparam[opt=maximum] number size maximum size of the data to receive +@treturn string data, can be an empty string +@treturn number source node, 0 if nothing has been received +*/ +static int uds_receive(lua_State *L) { + size_t maxSize = luaL_optinteger(L, 1, UDS_DATAFRAME_MAXSIZE); + char* buff = malloc(maxSize); + if (buff == NULL) luaL_error(L, "Memory allocation error"); + size_t received = 0; + u16 sourceID = 0; + + Result ret = udsPullPacket(&bind, buff, maxSize, &received, &sourceID); + if (R_FAILED(ret)) { + free(buff); + lua_pushnil(L); + lua_pushinteger(L, ret); + return 2; + } + + lua_pushlstring(L, buff, received); + free(buff); + lua_pushinteger(L, sourceID); + return 2; +} + +/*** +Send a packet to a node. +@function send +@tparam string data data to send +@tparam[opt=BROADCAST] number nodeID nodeID to send the packet to +*/ +static int uds_send(lua_State *L) { + size_t size = 0; + const char *buff = luaL_checklstring(L, 1, &size); + u16 nodeID = luaL_optinteger(L, 2, UDS_BROADCAST_NETWORKNODEID); + + udsSendTo(nodeID, data_channel, 0, buff, size); + + return 0; +} + +/*** +Return information about nodes in the networks +@function getNodesInfo +@treturn tablea table containing nodes informations, as tables (not userdatas). +A node table is like: `{ username = "azerty", nodeID = 12 }` +*/ +static int uds_getNodesInfo(lua_State *L) { + lua_newtable(L); + for (int i=0;inetwork, passphrase, passphraseSize, &bind, recvNetworkNodeID, connType, dataChannel, recvBufferSize); + if (R_FAILED(ret)) { + lua_pushnil(L); + lua_pushinteger(L, ret); + return 2; + } + + lua_pushboolean(L, true); + return 1; +} + +/*** +Disconnect from the network. +@function disconnect +*/ +static int uds_disconnect(lua_State *L) { + udsDisconnectNetwork(); + udsUnbind(&bind); + + return 0; +} + +/*** +Server part +@section server +*/ + +/*** +Create a network. +@function createNetwork +@tparam[opt=""] string passphrase passphrase of the network +@tparam[opt=16] number maxNodes maximum number of nodes that can be connected to the network, including the host (max 16) +@tparam[opt=0x637472c2] number commID application local-WLAN unique ID +@tparam[opt=default] number recvBuffSize size of the buffer that receives data +@tparam[opt=1] number dataChannel data channel of the network; this should be 1 +@treturn[1] boolean `true` on success +@treturn[2] boolean `false` on error +@treturn[2] number error code +*/ +static int uds_createNetwork(lua_State *L) { + size_t passSize = 0; + const char *pass = luaL_optlstring(L, 1, "", &passSize); + u8 maxNodes = luaL_optinteger(L, 2, UDS_MAXNODES); + u32 commID = luaL_optinteger(L, 3, 0x637472c2); + u32 recvBuffSize = luaL_optinteger(L, 4, UDS_DEFAULT_RECVBUFSIZE); + u8 dataChannel = luaL_optinteger(L, 5, 1); + + udsGenerateDefaultNetworkStruct(&network, commID, dataChannel, maxNodes); + Result ret = udsCreateNetwork(&network, pass, passSize, &bind, dataChannel, recvBuffSize); + if (R_FAILED(ret)) { + lua_pushboolean(L, false); + lua_pushinteger(L, ret); + return 2; + } + + lua_pushboolean(L, 1); + return 1; +} + +/*** +Set the application data of the created network. +@function setAppData +@tparam string appData application data +@treturn[1] boolean `true` on success +@treturn[2] boolean `false` on error +@treturn[2] number error code +*/ +static int uds_setAppData(lua_State *L) { + size_t size = 0; + const char* data = luaL_checklstring(L, 1, &size); + + Result ret = udsSetApplicationData(data, size); + if (R_FAILED(ret)) { + lua_pushboolean(L, false); + lua_pushinteger(L, ret); + return 2; + } + + lua_pushboolean(L, true); + return 1; +} + +/*** +Destroy the network. +@function destroyNetwork +*/ +static int uds_destroyNetwork(lua_State *L) { + udsDestroyNetwork(); + udsUnbind(&bind); + + return 0; +} + +/*** +Eject all the spectators connected to the network. +@function ejectSpectators +@tparam[opt=false] boolean reallow set to `true` to still allow the spectators to connect +*/ +static int uds_ejectSpectators(lua_State *L) { + bool reallow = false; + if (lua_isboolean(L, 1)) + reallow = lua_toboolean(L, 1); + + udsEjectSpectator(); + + if (reallow) + udsAllowSpectators(); + + return 0; +} + +/*** +Eject a client connected to the network. +@function ejectClient +@tparam[opt=BROADCAST] number nodeID node ID of the client to eject, or `BROADCAST` for all the clients +*/ +static int uds_ejectClient(lua_State *L) { + u16 nodeID = luaL_optinteger(L, 1, UDS_BROADCAST_NETWORKNODEID); + + udsEjectClient(nodeID); + + return 0; +} + +/*** +beaconScan +@section beaconScan +*/ +static const struct luaL_Reg beaconScan_methods[]; + +static int beaconScan___index(lua_State *L) { + udsNetworkScanInfo* beacon = luaL_checkudata(L, 1, "LUDSBeaconScan"); + + if (lua_isstring(L, 2)) { + const char* index = luaL_checkstring(L, 2); + /*** + @tfield integer channel Wifi channel of the beacon + */ + if (!strcmp(index, "channel")) { + lua_pushinteger(L, beacon->datareply_entry.channel); + return 1; + /*** + @tfield string mac MAC address of the beacon (`mac` for lowercase, `MAC` for uppercase) + @usage +beacon.mac -> ab:cd:ef:ab:cd:ef +beacon.MAC -> AB:CD:EF:AB:CD:EF + */ + } else if (!strcmp(index, "mac") && !strcmp(index, "MAC")) { + char* macString = malloc(18); + if (macString == NULL) luaL_error(L, "Out of memory"); + if (index[1] == 'm') { // lowercase + sprintf(macString, "%0x2:%0x2:%0x2:%0x2:%0x2:%0x2", beacon->datareply_entry.mac_address[0], beacon->datareply_entry.mac_address[1], beacon->datareply_entry.mac_address[2], beacon->datareply_entry.mac_address[3], beacon->datareply_entry.mac_address[4], beacon->datareply_entry.mac_address[5]); + } else { + sprintf(macString, "%0X2:%0X2:%0X2:%0X2:%0X2:%0X2", beacon->datareply_entry.mac_address[0], beacon->datareply_entry.mac_address[1], beacon->datareply_entry.mac_address[2], beacon->datareply_entry.mac_address[3], beacon->datareply_entry.mac_address[4], beacon->datareply_entry.mac_address[5]); + } + lua_pushstring(L, macString); + free(macString); + return 1; + /*** + @tfield table nodes a table containing nodes informations, as tables (not userdatas). + A node table is like: `{ username = "azerty", nodeID = 12 }` + */ + } else if (!strcmp(index, "nodes")) { + lua_newtable(L); + for (int i=0;inodes[i])) continue; + lua_createtable(L, 0, 2); + char tmpstr[256]; // 256 is maybe too much ... But we have a lot of RAM. + memset(tmpstr, 0, sizeof(tmpstr)); + udsGetNodeInfoUsername(&beacon->nodes[i], tmpstr); + lua_pushstring(L, tmpstr); + lua_setfield(L, -2, "username"); + lua_pushinteger(L, (&beacon->nodes[i])->NetworkNodeID); + lua_setfield(L, -2, "nodeID"); + + lua_seti(L, -3, i+1); + } + return 1; + /*** + @tfield number id8 id8 of the beacon's network + */ + } else if (!strcmp(index, "id8")) { + lua_pushinteger(L, beacon->network.id8); + return 1; + /*** + @tfield number networkID random ID of the network + */ + } else if (!strcmp(index, "networkID")) { + lua_pushinteger(L, beacon->network.networkID); + return 1; + /*** + @tfield boolean allowSpectators `true` if new spectators are allowed on the network + */ + } else if (!strcmp(index, "allowSpectators")) { + lua_pushboolean(L, !(beacon->network.attributes&UDSNETATTR_DisableConnectSpectators)); + return 1; + /*** + @tfield boolean allowClients `true` if new clients are allowed on the network + */ + } else if (!strcmp(index, "allowClients")) { + lua_pushboolean(L, !(beacon->network.attributes&UDSNETATTR_DisableConnectClients)); + return 1; + // methods + } else { + for (int i=0;beaconScan_methods[i].name;i++) { + if (!strcmp(beaconScan_methods[i].name, index)) { + lua_pushcfunction(L, beaconScan_methods[i].func); + return 1; + } + } + } + } + + lua_pushnil(L); + return 1; +} + +/*** +Return the application data of the beacon +@function :getAppData +@tparam[opt=0x4000] number maxSize maximum application data size to return +@treturn[1] string application data +@treturn[2] nil +@treturn[2] error code +*/ +static int beaconScan_getAppData(lua_State *L) { + udsNetworkScanInfo* beacon = luaL_checkudata(L, 1, "LUDSBeaconScan"); + size_t maxSize = luaL_optinteger(L, 2, 0x4000); + + u8* data = malloc(maxSize); + if (data == NULL) luaL_error(L, "Memory allocation error"); + + size_t size = 0; + udsGetNetworkStructApplicationData(&beacon->network, data, maxSize, &size); + + lua_pushlstring(L, (const char*)data, size); + free(data); + + return 1; +} + +// beaconScan object +static const struct luaL_Reg beaconScan_methods[] = { + {"__index", beaconScan___index }, + {"getAppData", beaconScan_getAppData}, + {NULL, NULL} +}; + +// module functions +static const struct luaL_Reg uds_lib[] = { + {"init", uds_init }, + {"shutdown", uds_shutdown }, + {"scan", uds_scan }, + {"getNodesInfo ", uds_getNodesInfo }, + {"getAppData", uds_getAppData }, + {"connect", uds_connect }, + {"available", uds_available }, + {"send", uds_send }, + {"receive", uds_receive }, + {"disconnect", uds_disconnect }, + {"createNetwork", uds_createNetwork }, + {"setAppData", uds_setAppData }, + {"destroyNetwork", uds_destroyNetwork }, + {"ejectSpectators", uds_ejectSpectators}, + {"ejectClient", uds_ejectClient }, + {NULL, NULL} +}; + +/*** +Constants +@section constants +*/ + +struct { char *name; int value; } uds_constants[] = { + /*** + @field BROADCAST broadcast node ID + */ + {"BROADCAST", UDS_BROADCAST_NETWORKNODEID}, + /*** + @field HOST host node ID + */ + {"HOST", UDS_HOST_NETWORKNODEID }, + /*** + @field CLIENT used to specify a connection as a client + */ + {"CLIENT", UDSCONTYPE_Client }, + /*** + @field SPECTATOR used to specify a connection as a spectator + */ + {"SPECTATOR", UDSCONTYPE_Spectator }, + {NULL, 0} +}; + +int luaopen_uds_lib(lua_State *L) { + luaL_newmetatable(L, "LUDSBeaconScan"); + lua_pushvalue(L, -1); + lua_setfield(L, -2, "__index"); + luaL_setfuncs(L, beaconScan_methods, 0); + + luaL_newlib(L, uds_lib); + + for (int i = 0; uds_constants[i].name; i++) { + lua_pushinteger(L, uds_constants[i].value); + lua_setfield(L, -2, uds_constants[i].name); + } + + return 1; +} + +void load_uds_lib(lua_State *L) { + luaL_requiref(L, "ctr.uds", luaopen_uds_lib, 0); +} + +void unload_uds_lib(lua_State *L) { + if (initStateUDS) { + udsConnectionStatus status; + udsGetConnectionStatus(&status); + switch (status.status) { + case 0x6: // connected as host + udsDestroyNetwork(); + udsUnbind(&bind); + break; + + case 0x9: // connected as client + case 0xA: // connected as spectator + udsDisconnectNetwork(); + udsUnbind(&bind); + break; + + default: + break; + } + udsExit(); + initStateUDS = false; + } +}