├── .vscode ├── settings.json ├── launch.json ├── c_cpp_properties.json └── tasks.json ├── .gitignore ├── meson.build ├── README.md ├── include ├── nvjpg.hpp └── nvjpg │ ├── nv │ ├── ctrl.hpp │ ├── registers.hpp │ ├── ioctl_types.h │ ├── cmdbuf.hpp │ ├── channel.hpp │ └── map.hpp │ ├── bitstream.hpp │ ├── utils.hpp │ ├── decoder.hpp │ ├── image.hpp │ └── surface.hpp ├── lib ├── surface.cpp ├── image.cpp └── decoder.cpp ├── examples ├── render-rgb-downscale.cpp ├── render-nx.cpp ├── render-rgb.cpp ├── bitmap.hpp ├── render-icons.cpp ├── render-yuv.cpp └── render-deko3d.cpp ├── Makefile └── LICENSE /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.exclude": { 3 | "**/build": true, 4 | "**/out": true, 5 | }, 6 | "files.associations": { 7 | "**/c++/**": "cpp" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.d 2 | *.o 3 | *.map 4 | 5 | *.elf 6 | *.a 7 | *.so* 8 | 9 | *.nso 10 | *.nsp 11 | *.nro 12 | *.nacp 13 | *.npdm 14 | *.dksh 15 | 16 | *.ini 17 | *.log 18 | *.txt 19 | *.bin 20 | 21 | *.png 22 | *.jpg 23 | *.bin 24 | *.rgba 25 | *.yuv 26 | *.log 27 | *.diff 28 | *.txt 29 | 30 | **/build/ 31 | **/release/ 32 | **/debug/ 33 | **/out/ 34 | **/data/ 35 | **/misc/ 36 | **/docs/ 37 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Debug (gdb)", 6 | "type": "cppdbg", 7 | "request": "launch", 8 | "preLaunchTask": "all", 9 | "externalConsole": false, 10 | "program": "${workspaceRoot}/build/render-rgb", 11 | "cwd": "${workspaceRoot}", 12 | "args": [ 13 | "data/test.jpg", 14 | ], 15 | "environment": [ 16 | { "name": "DISPLAY", "value": ":0" }, 17 | ], 18 | "MIMode": "gdb", 19 | "miDebuggerPath": "/usr/bin/gdb", 20 | "setupCommands": [ 21 | { 22 | "description": "Enable pretty-printing for gdb", 23 | "text": "-enable-pretty-printing", 24 | "ignoreFailures": true 25 | } 26 | ] 27 | } 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /meson.build: -------------------------------------------------------------------------------- 1 | project('nvjpg', ['c', 'cpp'], version: '1.1.0', 2 | default_options: [ 3 | 'buildtype=release', 4 | 'default_library=static', 5 | 'b_ndebug=if-release', 6 | 'b_lto=false', 7 | 'strip=false', 8 | 'warning_level=2', 9 | 'c_std=gnu11', 10 | 'cpp_std=gnu++20', 11 | ], 12 | ) 13 | 14 | nvj_inc = include_directories('include') 15 | 16 | nvj_src = files( 17 | 'lib/decoder.cpp', 18 | 'lib/image.cpp', 19 | 'lib/surface.cpp', 20 | ) 21 | 22 | nvj_lib = library('oss-nvjpg', nvj_src, include_directories: nvj_inc) 23 | 24 | nvj_dep = declare_dependency(include_directories: nvj_inc, link_with: nvj_lib) 25 | 26 | ex1 = executable('render-rgb', 27 | 'examples/render-rgb.cpp', 28 | dependencies: [nvj_dep, dependency('SDL2', required: true)], 29 | build_by_default: false, 30 | ) 31 | 32 | ex2 = executable('render-rgb-downscale', 33 | 'examples/render-rgb-downscale.cpp', 34 | dependencies: [nvj_dep, dependency('SDL2', required: true)], 35 | build_by_default: false, 36 | ) 37 | 38 | ex3 = executable('render-yuv', 39 | 'examples/render-yuv.cpp', 40 | dependencies: [nvj_dep, dependency('SDL2', required: true)], 41 | build_by_default: false, 42 | ) 43 | 44 | alias_target('examples', ex1, ex2, ex3) 45 | -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Linux", 5 | "compileCommands": "build/compile_commands.json", 6 | "compilerPath": "/usr/bin/gcc", 7 | "cStandard": "gnu11", 8 | "cppStandard": "gnu++20", 9 | "intelliSenseMode": "gcc-arm64" 10 | }, 11 | { 12 | "name": "DKP Aarch64", 13 | "includePath": [ 14 | "${workspaceFolder}/include", 15 | 16 | "~/Bureau/Switch/libnx/nx/source/**", 17 | "~/Bureau/Switch/libnx/nx/include/**", 18 | 19 | "${DEVKITPRO}/libnx/include", 20 | "${DEVKITPRO}/portlibs/switch/include", 21 | 22 | "${DEVKITPRO}/devkitA64/aarch64-none-elf/include/**", 23 | "${DEVKITPRO}/devkitA64/lib/gcc/aarch64-none-elf/*/include" 24 | ], 25 | "defines": [ 26 | "__aarch64__", 27 | "__SWITCH__", 28 | "DEBUG" 29 | ], 30 | "compilerPath": "${DEVKITPRO}/devkitA64/bin/aarch64-none-elf-gcc", 31 | "cStandard": "gnu11", 32 | "cppStandard": "gnu++20", 33 | "intelliSenseMode": "gcc-arm64" 34 | } 35 | ], 36 | "version": 4 37 | } 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # oss-nvjpg 2 | 3 | The Tegra X1 provides a hardware module dedicated to JPEG encoding/decoding (NVJPG). 4 | 5 | Using this library, images can be rendered to an RGB or YUV (triplanar) surface. YUV➝RGB conversion is handled in hardware. In addition, images can be downscaled to up to 8, also done in hardware. 6 | 7 | Note: only baseline JPEGs are supported. Progressive and arithmetic coded files will return an error. 8 | 9 | ### Performance 10 | 11 | Decoding times are largely faster than those obtained by software rendering, even with SIMD optimizations. The results below were obtained on an Aarch64 Cortex-A57 clocked at max 2.091GHz, by decoding the same image to an RGB surface, averaging 1000 iterations: 12 | | Library | 70Kib 720x1080 | 1.6Mib 3200x1800 | 13 | | --- |:---:|:---:| 14 | | NVJPG | 2.036ms | 15.997ms | 15 | | libjpeg-turbo | 6.127ms | 66.341ms | 16 | | stb_image (with NEON routines) | 16.512ms | 158.474ms | 17 | | Python-pillow | 11.688ms | 114.918ms | 18 | | nanoJPEG | 48.299ms | 531.575ms | 19 | 20 | ## Building 21 | Requires C++20 support. 22 | 23 | ### Linux 24 | ```sh 25 | meson build && meson compile -C build 26 | ``` 27 | Additionally, run `meson compile -C build examples` to build the examples. 28 | 29 | ### devkitA64 30 | ```sh 31 | make -j$(nproc) 32 | ``` 33 | Additionally, run `make examples` to build the examples. 34 | 35 | ## Credits 36 | - The [Ryujinx](https://github.com/Ryujinx/Ryujinx) project for extensive documentation of the Host1x interface 37 | -------------------------------------------------------------------------------- /include/nvjpg.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | namespace nj { 28 | 29 | #ifdef __SWITCH__ 30 | extern "C" std::uint32_t __nx_applet_type; 31 | #endif 32 | 33 | [[maybe_unused]] 34 | static Result initialize() { 35 | #ifdef __SWITCH__ 36 | // Override the applet type, which controls what flavour of nvdrv gets initialized 37 | // To get access to /dev/nvhost-nvjpg, we need nvdrv:a/s/t 38 | auto saved_applet_type = std::exchange(__nx_applet_type, AppletType_LibraryApplet); 39 | NJ_SCOPEGUARD([&saved_applet_type] { __nx_applet_type = saved_applet_type; }); 40 | 41 | NJ_TRY_RET(nvInitialize()); 42 | NJ_TRY_RET(nj::NvMap::initialize()); 43 | NJ_TRY_RET(nj::NvHostCtrl::initialize()); 44 | 45 | NJ_TRY_RET(mmuInitialize()); 46 | #else 47 | NJ_TRY_ERRNO(nj::NvMap::initialize()); 48 | NJ_TRY_ERRNO(nj::NvHostCtrl::initialize()); 49 | #endif 50 | return 0; 51 | } 52 | 53 | [[maybe_unused]] 54 | static Result finalize() { 55 | #ifdef __SWITCH__ 56 | NJ_TRY_RET(nj::NvMap::finalize()); 57 | NJ_TRY_RET(nj::NvHostCtrl::finalize()); 58 | nvExit(); 59 | 60 | mmuExit(); 61 | #else 62 | NJ_TRY_ERRNO(nj::NvMap::finalize()); 63 | NJ_TRY_ERRNO(nj::NvHostCtrl::finalize()); 64 | #endif 65 | return 0; 66 | } 67 | 68 | } // namespace nj 69 | -------------------------------------------------------------------------------- /include/nvjpg/nv/ctrl.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | 22 | #ifdef __SWITCH__ 23 | # include 24 | #else 25 | # include 26 | # include 27 | # include 28 | # include 29 | # include 30 | #endif 31 | 32 | #include 33 | #include 34 | 35 | namespace nj { 36 | 37 | class NvHostCtrl { 38 | public: 39 | static Result initialize() { 40 | #ifdef __SWITCH__ 41 | return nvFenceInit(); 42 | #else 43 | return NvHostCtrl::nvhostctrl_fd = ::open("/dev/nvhost-ctrl", O_RDWR | O_SYNC | O_CLOEXEC); 44 | #endif 45 | } 46 | 47 | static Result finalize() { 48 | #ifdef __SWITCH__ 49 | nvFenceExit(); 50 | return 0; 51 | #else 52 | return ::close(NvHostCtrl::nvhostctrl_fd); 53 | #endif 54 | } 55 | 56 | #ifdef __SWITCH__ 57 | static Result wait(NvFence fence, std::int32_t timeout) { 58 | return nvFenceWait(&fence, timeout); 59 | } 60 | #else 61 | static Result wait(nvhost_ctrl_fence fence, std::int32_t timeout) { 62 | nvhost_ctrl_syncpt_waitex_args args = { 63 | .id = fence.id, 64 | .thresh = fence.value, 65 | .timeout = timeout, 66 | .value = 0, 67 | }; 68 | 69 | return ::ioctl(NvHostCtrl::nvhostctrl_fd, NVHOST_IOCTL_CTRL_SYNCPT_WAITEX, &args); 70 | } 71 | #endif 72 | 73 | private: 74 | #ifndef __SWITCH__ 75 | static inline int nvhostctrl_fd = 0; 76 | #endif 77 | }; 78 | 79 | } // namespace nj 80 | 81 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "gen", 6 | "type": "shell", 7 | "command": "meson", 8 | "args": [ 9 | "build", 10 | "--buildtype", 11 | "debug", 12 | "-Db_lto=false" 13 | ], 14 | "presentation": { 15 | "panel": "shared", 16 | "reveal": "never" 17 | }, 18 | "problemMatcher": [] 19 | }, 20 | { 21 | "label": "all", 22 | "type": "shell", 23 | "command": "ninja", 24 | "args": [ 25 | "all", 26 | "examples", 27 | "-j$(nproc)", 28 | ], 29 | "options": { 30 | "cwd": "${workspaceFolder}/build", 31 | "env": { 32 | "LANG": "en", 33 | } 34 | }, 35 | "presentation": { 36 | "reveal": "always", 37 | "panel": "shared", 38 | "clear": true 39 | }, 40 | "problemMatcher": { 41 | "base": "$gcc", 42 | "fileLocation": ["relative", "${workspaceFolder}/build"] 43 | }, 44 | "group": { 45 | "kind": "build", 46 | "isDefault": true 47 | } 48 | }, 49 | { 50 | "label": "clean", 51 | "type": "shell", 52 | "command": "ninja", 53 | "args": [ 54 | "clean" 55 | ], 56 | "options": { 57 | "cwd": "${workspaceFolder}/build", 58 | }, 59 | "presentation": { 60 | "panel": "shared", 61 | "reveal": "never" 62 | }, 63 | "problemMatcher": [] 64 | }, 65 | { 66 | "label": "run", 67 | "dependsOn": [ 68 | "all", 69 | ], 70 | "type": "shell", 71 | "command": "${workspaceFolder}/build/render-rgb", 72 | "args": [ 73 | "data/test.jpg", 74 | ], 75 | "options": { 76 | "env": { 77 | "DISPLAY": ":0", 78 | } 79 | }, 80 | "presentation": { 81 | "reveal": "always", 82 | "panel": "shared", 83 | "clear": true 84 | }, 85 | "problemMatcher": [] 86 | } 87 | ] 88 | } 89 | -------------------------------------------------------------------------------- /include/nvjpg/bitstream.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | namespace nj { 26 | 27 | class Bitstream { 28 | public: 29 | Bitstream(const std::vector &data): data(data), cur(data.begin()) { } 30 | 31 | template 32 | T get() { 33 | if (this->cur + sizeof(T) >= this->data.end()) { 34 | this->cur = this->data.end(); 35 | return {}; 36 | } 37 | auto tmp = *reinterpret_cast(this->cur.base()); 38 | this->cur += sizeof(T); 39 | return tmp; 40 | } 41 | 42 | template 43 | T get_be() { 44 | if constexpr (sizeof(T) == 1) 45 | return this->get(); 46 | else if constexpr (sizeof(T) == 2) 47 | return __builtin_bswap16(this->get()); 48 | else if constexpr (sizeof(T) == 4) 49 | return __builtin_bswap32(this->get()); 50 | else if constexpr (sizeof(T) == 8) 51 | return __builtin_bswap64(this->get()); 52 | return {}; 53 | } 54 | 55 | void skip(std::size_t size) { 56 | this->cur += size; 57 | } 58 | 59 | void rewind(std::size_t size) { 60 | this->cur -= size; 61 | } 62 | 63 | bool empty() const { 64 | return this->cur >= this->data.end(); 65 | } 66 | 67 | std::size_t size() const { 68 | return this->data.end() - this->cur; 69 | } 70 | 71 | auto current() const { 72 | return this->cur; 73 | } 74 | 75 | private: 76 | const std::vector &data; 77 | std::vector::const_iterator cur; 78 | }; 79 | 80 | } // namespace nj 81 | -------------------------------------------------------------------------------- /include/nvjpg/utils.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | #define _NJ_CAT(x, y) x ## y 25 | #define NJ_CAT(x, y) _NJ_CAT(x, y) 26 | #define _NJ_STR(x) #x 27 | #define NJ_STR(x) _NJ_STR(x) 28 | 29 | #define NJ_ANONYMOUS_VAR NJ_CAT(var, __COUNTER__) 30 | 31 | #define NJ_SCOPEGUARD(f) auto NJ_ANONYMOUS_VAR = ::nj::ScopeGuard(f) 32 | 33 | #ifndef __SWITCH__ 34 | typedef int Result; 35 | #endif 36 | 37 | #define NJ_TRY_RET(expr) \ 38 | if (auto _rc = (expr); _rc) \ 39 | return _rc; 40 | 41 | #define NJ_TRY_ERRNO(expr) \ 42 | if ((expr); errno) \ 43 | return errno; 44 | 45 | #define NJ_UNUSED(...) ::nj::variadic_unused(__VA_ARGS__) 46 | 47 | namespace nj { 48 | 49 | template 50 | consteval void variadic_unused(Args &&...args) { 51 | (static_cast(args), ...); 52 | } 53 | 54 | template 55 | struct [[nodiscard]] ScopeGuard { 56 | ScopeGuard(F &&f): f(std::move(f)) { } 57 | 58 | ScopeGuard(const ScopeGuard &) = delete; 59 | ScopeGuard(ScopeGuard &&) = delete; 60 | ScopeGuard &operator =(const ScopeGuard &) = delete; 61 | ScopeGuard &operator =(ScopeGuard &&) = delete; 62 | 63 | ~ScopeGuard() { 64 | this->f(); 65 | } 66 | 67 | private: 68 | F f; 69 | }; 70 | 71 | constexpr auto bit(std::unsigned_integral auto bits) { 72 | return 1 << bits; 73 | } 74 | 75 | constexpr auto mask(std::unsigned_integral auto bits) { 76 | return (1 << bits) - 1; 77 | } 78 | 79 | template 80 | constexpr T align_down(T val, T align) { 81 | return val & ~(align - 1); 82 | } 83 | 84 | template 85 | constexpr T align_up(T val, T align) { 86 | return (val + align - 1) & ~(align - 1); 87 | } 88 | 89 | template 90 | constexpr bool is_aligned(T val, T align) { 91 | return !(val & (align - 1)); 92 | } 93 | 94 | } // namespace nj 95 | -------------------------------------------------------------------------------- /lib/surface.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #include 19 | 20 | #include 21 | 22 | #include 23 | 24 | namespace nj { 25 | 26 | namespace { 27 | 28 | std::size_t compute_pitch(std::size_t width, std::size_t bpp) { 29 | return align_up(width * bpp, 0x100ul); 30 | } 31 | 32 | std::size_t compute_size(std::size_t pitch, std::size_t height) { 33 | return align_up(pitch * height, 0x20000ul); 34 | } 35 | 36 | } // namespace 37 | 38 | int Surface::allocate() { 39 | this->pitch = compute_pitch(this->width, this->get_bpp()); 40 | NJ_TRY_RET(this->map.allocate(compute_size(this->pitch, this->height), 0x400, 0x1)); 41 | #ifndef __SWITCH__ 42 | NJ_TRY_ERRNO(this->map.map()); 43 | #endif 44 | return 0; 45 | } 46 | 47 | int VideoSurface::allocate() { 48 | auto hsubsamp = 0, vsubsamp = 0; 49 | switch (this->sampling) { 50 | case SamplingFormat::S420: 51 | hsubsamp = 2, vsubsamp = 2; 52 | break; 53 | case SamplingFormat::S422: 54 | hsubsamp = 2, vsubsamp = 1; 55 | break; 56 | case SamplingFormat::S444: 57 | hsubsamp = 1, vsubsamp = 1; 58 | break; 59 | default: 60 | return EINVAL; 61 | } 62 | 63 | this->luma_pitch = compute_pitch(this->width, 1); 64 | this->chroma_pitch = compute_pitch(this->width / hsubsamp, 1); 65 | 66 | auto luma_size = compute_size(this->luma_pitch, this->height); 67 | auto chroma_size = compute_size(this->chroma_pitch, this->height / vsubsamp); 68 | NJ_TRY_RET(this->map.allocate(luma_size + 2 * chroma_size, 0x400, 0x1)); 69 | #ifndef __SWITCH__ 70 | NJ_TRY_ERRNO(this->map.map()); 71 | #endif 72 | 73 | this->luma_data = static_cast(this->map.address()); 74 | this->chromab_data = static_cast(this->map.address()) + luma_size; 75 | this->chromar_data = static_cast(this->map.address()) + luma_size + chroma_size; 76 | return 0; 77 | } 78 | 79 | } // namespace nj 80 | -------------------------------------------------------------------------------- /examples/render-rgb-downscale.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #include "bitmap.hpp" 26 | 27 | // Has to be a power of two and smaller than 8 28 | #define DOWNSCALE_FACTOR 4 29 | 30 | int main(int argc, char **argv) { 31 | if (argc < 2) { 32 | std::fprintf(stderr, "Usage: %s directory\n", argv[0]); 33 | return 1; 34 | } 35 | 36 | if (auto rc = nj::initialize(); rc) { 37 | std::fprintf(stderr, "Failed to initialize library: %d: %s\n", rc, std::strerror(rc)); 38 | return 1; 39 | } 40 | NJ_SCOPEGUARD([] { nj::finalize(); }); 41 | 42 | nj::Decoder decoder; 43 | if (auto rc = decoder.initialize(); rc) { 44 | std::fprintf(stderr, "Failed to initialize decoder: %#x\n", rc); 45 | return rc; 46 | } 47 | NJ_SCOPEGUARD([&decoder] { decoder.finalize(); }); 48 | 49 | nj::Surface surf(0x1000, 0x1000, nj::PixelFormat::BGRA); 50 | if (auto rc = surf.allocate(); rc) { 51 | std::fprintf(stderr, "Failed to allocate surface: %#x\n", rc); 52 | return 1; 53 | } 54 | 55 | std::printf("Surface pitch: %#lx, size %#lx\n", surf.pitch, surf.size()); 56 | 57 | for (auto entry: std::filesystem::directory_iterator(argv[1])) { 58 | if (entry.is_directory()) 59 | continue; 60 | 61 | auto path = entry.path(); 62 | if (path.extension() != ".jpg" && path.extension() != ".jpeg") 63 | continue; 64 | 65 | std::puts(path.c_str()); 66 | 67 | nj::Image image(path.string()); 68 | if (!image.is_valid() || image.parse()) { 69 | std::perror("Invalid file"); 70 | return 1; 71 | } 72 | 73 | std::printf("Image dimensions: %ux%u\n", image.width, image.height); 74 | 75 | auto start = std::chrono::system_clock::now(); 76 | if (auto rc = decoder.render(image, surf, 0, DOWNSCALE_FACTOR); rc) 77 | std::fprintf(stderr, "Failed to render image: %#x (%s)\n", rc, std::strerror(errno)); 78 | 79 | std::size_t read = 0; 80 | decoder.wait(surf, &read); 81 | auto time = std::chrono::system_clock::now() - start; 82 | std::printf("Rendered in %ldµs, read bytes: %lu\n", 83 | std::chrono::duration_cast(time).count(), read); 84 | 85 | nj::Bmp bmp(image.width / DOWNSCALE_FACTOR, image.height / DOWNSCALE_FACTOR); 86 | if (auto rc = bmp.write(surf, path.replace_extension(".bmp").string()); rc) { 87 | std::fprintf(stderr, "Failed to write bmp: %d\n", rc); 88 | return rc; 89 | } 90 | } 91 | 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /examples/render-nx.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | extern "C" void userAppInit() { 25 | socketInitializeDefault(); 26 | nxlinkStdio(); 27 | } 28 | 29 | extern "C" void userAppExit() { 30 | socketExit(); 31 | } 32 | 33 | static void display_image(const nj::Surface &surface) { 34 | constexpr std::size_t fb_width = 1280, fb_height = 720; 35 | Framebuffer fb; 36 | framebufferCreate(&fb, nwindowGetDefault(), fb_width, fb_height, PIXEL_FORMAT_RGBA_8888, 1); 37 | framebufferMakeLinear(&fb); 38 | 39 | auto *framebuf = static_cast(framebufferBegin(&fb, nullptr)); 40 | for (std::size_t i = 0; i < std::min(fb_height, surface.height); ++i) 41 | std::copy_n(surface.data() + i * surface.pitch, std::min(surface.width, fb_width) * surface.get_bpp(), framebuf + i * fb.stride); 42 | framebufferEnd(&fb); 43 | 44 | PadState pad; 45 | padConfigureInput(1, HidNpadStyleTag_NpadHandheld); 46 | padInitializeDefault(&pad); 47 | while (appletMainLoop()) { 48 | padUpdate(&pad); 49 | if (padGetButtonsDown(&pad) & HidNpadButton_Plus) 50 | break; 51 | } 52 | 53 | framebufferClose(&fb); 54 | } 55 | 56 | int main(int argc, char **argv) { 57 | if (auto rc = nj::initialize(); rc) { 58 | std::fprintf(stderr, "Failed to initialize library: %d: %s\n", rc, std::strerror(rc)); 59 | return 1; 60 | } 61 | NJ_SCOPEGUARD([] { nj::finalize(); }); 62 | 63 | nj::Decoder decoder; 64 | if (auto rc = decoder.initialize(); rc) { 65 | std::fprintf(stderr, "Failed to initialize decoder: %#x\n", rc); 66 | return rc; 67 | } 68 | NJ_SCOPEGUARD([&decoder] { decoder.finalize(); }); 69 | 70 | nj::Image image((argc < 2) ? "sdmc:/test.jpg" : argv[1]); 71 | if (!image.is_valid() || image.parse()) { 72 | std::perror("Invalid file"); 73 | return 1; 74 | } 75 | 76 | std::printf("Image dimensions: %ux%u\n", image.width, image.height); 77 | 78 | nj::Surface surf(image.width, image.height, nj::PixelFormat::RGBA); 79 | if (auto rc = surf.allocate(); rc) { 80 | std::fprintf(stderr, "Failed to allocate surface: %#x\n", rc); 81 | return 1; 82 | } 83 | 84 | std::printf("Surface pitch: %#lx, size %#lx\n", surf.pitch, surf.size()); 85 | 86 | auto start = std::chrono::system_clock::now(); 87 | if (auto rc = decoder.render(image, surf, 255); rc) 88 | std::fprintf(stderr, "Failed to render image: %#x (%s)\n", rc, std::strerror(errno)); 89 | 90 | std::size_t read = 0; 91 | decoder.wait(surf, &read); 92 | auto time = std::chrono::system_clock::now() - start; 93 | std::printf("Rendered in %ldµs, read bytes: %lu\n", 94 | std::chrono::duration_cast(time).count(), read); 95 | 96 | std::printf("Press + to exit\n"); 97 | 98 | display_image(surf); 99 | 100 | return 0; 101 | } 102 | -------------------------------------------------------------------------------- /include/nvjpg/decoder.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | #ifdef __SWITCH__ 30 | # include 31 | #endif 32 | 33 | namespace nj { 34 | 35 | class Decoder { 36 | public: 37 | struct RingEntry { 38 | NvMap cmdbuf_map, pic_info_map, read_data_map, scan_data_map; 39 | CmdBuf cmdbuf{cmdbuf_map}; 40 | nvhost_ctrl_fence fence{ 0, -1u }; 41 | }; 42 | 43 | enum class ColorSpace { 44 | BT601, // ITUR BT-601 45 | BT709, // ITUR BT-709 46 | BT601Ex, // ITUR BT-601 extended range (16-235 -> 0-255), JFIF 47 | }; 48 | 49 | constexpr static std::uint32_t class_id = 0xc0; 50 | 51 | public: 52 | ColorSpace colorspace = ColorSpace::BT601Ex; 53 | 54 | public: 55 | Result initialize(std::size_t num_ring_entries = 1, std::size_t capacity = 0x500000); // 5 Mib 56 | Result finalize(); 57 | 58 | Result resize(std::size_t capacity); 59 | 60 | std::size_t capacity() const { 61 | if (this->entries.empty()) 62 | return 0; 63 | return this->entries[0].scan_data_map.size(); 64 | } 65 | 66 | Result render(const Image &image, Surface &surf, std::uint8_t alpha = 0, std::uint32_t downscale = 0); 67 | Result render(const Image &image, VideoSurface &surf, std::uint32_t downscale = 0); 68 | 69 | Result wait(const SurfaceBase &surf, std::size_t *num_read_bytes = nullptr, std::int32_t timeout_us = -1); 70 | 71 | Result wait(auto &&...surfs) requires requires (decltype(surfs) ...args) { (args.width, ...); } { 72 | return (this->wait(surfs, nullptr, -1) | ...); 73 | } 74 | 75 | // In Hz 76 | std::uint32_t get_clock_rate() const { 77 | std::uint32_t rate = 0; 78 | #ifdef __SWITCH__ 79 | std::uint32_t tmp = 0; 80 | if (auto rc = mmuRequestGet(&this->request, &tmp); R_SUCCEEDED(rc)) 81 | rate = tmp; 82 | #else 83 | this->channel.get_clock_rate(Decoder::class_id, rate); 84 | #endif 85 | return rate; 86 | } 87 | 88 | // In Hz 89 | Result set_clock_rate(std::uint32_t rate) const { 90 | #ifdef __SWITCH__ 91 | return mmuRequestSetAndWait(&this->request, rate, -1u); 92 | #else 93 | return this->channel.set_clock_rate(Decoder::class_id, rate); 94 | #endif 95 | } 96 | 97 | private: 98 | RingEntry &get_ring_entry() const; 99 | 100 | NvjpgPictureInfo *build_picture_info_common(RingEntry &entry, const Image &image, std::uint32_t downscale); 101 | 102 | Result render_common(RingEntry &entry, const Image &image, SurfaceBase &surf); 103 | 104 | private: 105 | NvChannel channel; 106 | std::vector entries; 107 | std::vector::iterator next_entry; 108 | 109 | #ifdef __SWITCH__ 110 | MmuRequest request; 111 | #endif 112 | }; 113 | 114 | } // namespace nj 115 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ifeq ($(strip $(DEVKITPRO)),) 2 | $(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") 3 | endif 4 | 5 | TOPDIR ?= $(CURDIR) 6 | 7 | VERSION = 1.1.0 8 | COMMIT = $(shell git rev-parse --short HEAD) 9 | 10 | # ----------------------------------------------- 11 | 12 | TARGET = nvjpg 13 | EXTENSION = a 14 | OUT = out 15 | BUILD = build 16 | SOURCES = lib 17 | INCLUDES = include 18 | CUSTOM_LIBS = 19 | ROMFS = 20 | EXAMPLES = examples/render-nx.cpp examples/render-icons.cpp examples/render-deko3d.cpp 21 | 22 | DEFINES = __SWITCH__ VERSION=\"$(VERSION)\" COMMIT=\"$(COMMIT)\" 23 | ARCH = -march=armv8-a+crc+crypto+simd -mtune=cortex-a57 -mtp=soft -fpie 24 | FLAGS = -Wall -pipe -g -O2 -ffunction-sections -fdata-sections 25 | CFLAGS = -std=gnu11 26 | CXXFLAGS = -std=gnu++20 -fno-rtti -fno-exceptions 27 | ASFLAGS = 28 | LDFLAGS = -Wl,-pie -specs=$(DEVKITPRO)/libnx/switch.specs -g 29 | LINKS = -lnx 30 | 31 | PREFIX = aarch64-none-elf- 32 | CC = $(PREFIX)gcc 33 | CXX = $(PREFIX)g++ 34 | AR = $(PREFIX)ar 35 | LD = $(PREFIX)g++ 36 | 37 | # ----------------------------------------------- 38 | 39 | export PATH := $(DEVKITPRO)/tools/bin:$(DEVKITPRO)/devkitA64/bin:$(PORTLIBS)/bin:$(PATH) 40 | 41 | PORTLIBS = $(DEVKITPRO)/portlibs/switch 42 | LIBNX = $(DEVKITPRO)/libnx 43 | LIBS = $(LIBNX) $(PORTLIBS) 44 | 45 | # ----------------------------------------------- 46 | 47 | CFILES = $(shell find $(SOURCES) -name *.c) 48 | CPPFILES = $(shell find $(SOURCES) -name *.cpp) 49 | SFILES = $(shell find $(SOURCES) -name *.s -or -name *.S) 50 | OFILES = $(CFILES:%=$(BUILD)/%.o) $(CPPFILES:%=$(BUILD)/%.o) $(SFILES:%=$(BUILD)/%.o) 51 | DFILES = $(OFILES:.o=.d) 52 | 53 | LIB_TARGET = $(if $(OUT:=), $(OUT)/lib$(TARGET).$(EXTENSION), .$(OUT)/lib$(TARGET).$(EXTENSION)) 54 | DEFINE_FLAGS = $(addprefix -D,$(DEFINES)) 55 | INCLUDE_FLAGS = $(addprefix -I$(CURDIR)/,$(INCLUDES)) $(foreach dir,$(CUSTOM_LIBS),-I$(CURDIR)/$(dir)/include) \ 56 | $(foreach dir,$(filter-out $(CUSTOM_LIBS),$(LIBS)),-I$(dir)/include) 57 | LIB_FLAGS = $(foreach dir,$(LIBS),-L$(dir)/lib) 58 | 59 | 60 | EXAMPLES_TARGET = $(if $(OUT:=), $(patsubst %, $(OUT)/%.nro, $(basename $(EXAMPLES))), \ 61 | $(patsubst %, .$(OUT)/%.nro, $(basename $(EXAMPLES)))) 62 | EXAMPLES_OFILES = $(EXAMPLES:%=$(BUILD)/%.o) 63 | EXAMPLES_DFILES = $(EXAMPLES_OFILES:.o=.d) 64 | 65 | # ----------------------------------------------- 66 | 67 | .SUFFIXES: 68 | 69 | .PHONY: all clean examples 70 | 71 | all: $(LIB_TARGET) 72 | @: 73 | 74 | examples: $(EXAMPLES_TARGET) $(EXAMPLES_OFILES) 75 | @: 76 | 77 | $(OUT)/%.nro: $(BUILD)/%.cpp.o $(LIB_TARGET) 78 | @mkdir -p $(dir $@) 79 | @echo " NRO " $@ 80 | @$(LD) $(ARCH) $^ -L $(OUT) -L $(DEVKITPRO)/libnx/lib -ldeko3d -l nvjpg -l nx -Wl,-pie -specs=$(DEVKITPRO)/libnx/switch.specs -o $(@:.nro=.elf) 81 | @nacptool --create $(notdir $(@:.nro=)) averne 0.0.0 $(@:.nro=.nacp) 82 | @elf2nro $(@:.nro=.elf) $@ --nacp=$(@:.nro=.nacp) > /dev/null 83 | 84 | $(LIB_TARGET): $(OFILES) 85 | @echo " AR " $@ 86 | @mkdir -p $(dir $@) 87 | @$(AR) rc $@ $^ 88 | 89 | $(BUILD)/%.c.o: %.c 90 | @echo " CC " $@ 91 | @mkdir -p $(dir $@) 92 | @$(CC) -MMD -MP $(ARCH) $(FLAGS) $(CFLAGS) $(DEFINE_FLAGS) $(INCLUDE_FLAGS) -c $(CURDIR)/$< -o $@ 93 | 94 | $(BUILD)/%.cpp.o: %.cpp 95 | @echo " CXX " $@ 96 | @mkdir -p $(dir $@) 97 | @$(CXX) -MMD -MP $(ARCH) $(FLAGS) $(CXXFLAGS) $(DEFINE_FLAGS) $(INCLUDE_FLAGS) -c $(CURDIR)/$< -o $@ 98 | 99 | $(BUILD)/%.s.o: %.s %.S 100 | @echo " AS " $@ 101 | @mkdir -p $(dir $@) 102 | @$(AS) -MMD -MP -x assembler-with-cpp $(ARCH) $(FLAGS) $(ASFLAGS) $(INCLUDE_FLAGS) -c $(CURDIR)/$< -o $@ 103 | 104 | clean: 105 | @echo Cleaning... 106 | @rm -rf $(BUILD) $(OUT) 107 | 108 | -include $(DFILES) $(EXAMPLES_DFILES) 109 | -------------------------------------------------------------------------------- /include/nvjpg/image.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | #include 29 | #include 30 | 31 | namespace nj { 32 | 33 | enum class JpegMarker: std::uint8_t { 34 | Sof0 = 0xc0, 35 | Sof1 = 0xc1, 36 | Sof2 = 0xc2, 37 | Sof15 = 0xcf, 38 | 39 | Dht = 0xc4, 40 | Soi = 0xd8, 41 | Eoi = 0xd9, 42 | Sos = 0xda, 43 | Dqt = 0xdb, 44 | Dri = 0xdd, 45 | 46 | App0 = 0xe0, 47 | App15 = 0xef, 48 | 49 | Magic = 0xff, 50 | }; 51 | 52 | struct JpegSegmentHeader { 53 | JpegMarker magic; 54 | JpegMarker marker; 55 | std::uint16_t size; 56 | }; 57 | 58 | class Image { 59 | public: 60 | struct Component { 61 | std::uint8_t sampling_horiz, sampling_vert; 62 | std::uint8_t quant_table_id; 63 | std::uint8_t hm_ac_table_id, hm_dc_table_id; 64 | }; 65 | 66 | struct QuantizationTable { 67 | std::array table; 68 | }; 69 | 70 | struct HuffmanTable { 71 | std::array codes; 72 | std::array symbols; 73 | }; 74 | 75 | public: 76 | std::uint16_t width = 0; 77 | std::uint16_t height = 0; 78 | std::uint8_t mcu_size_horiz = 0; 79 | std::uint8_t mcu_size_vert = 0; 80 | bool progressive = false; 81 | std::uint8_t num_components = 0; // 1 (grayscale) and 3 (YUV) supported 82 | std::uint8_t sampling_precision = 0; // 8 and 12-bit precision supported 83 | SamplingFormat sampling; 84 | std::uint16_t restart_interval = 0; 85 | std::uint8_t spectral_selection_lo = 0; 86 | std::uint8_t spectral_selection_hi = 0; 87 | 88 | std::array comp_idx = {}; 89 | std::array components = {}; 90 | std::array quant_tables = {}; 91 | std::array hm_ac_tables = {}; 92 | std::array hm_dc_tables = {}; 93 | 94 | std::uint8_t quant_mask = 0, hm_ac_mask = 0, hm_dc_mask = 0; 95 | 96 | public: 97 | Image() = default; 98 | Image(std::shared_ptr> data): data(data) { } 99 | Image(int fd); 100 | Image(FILE *fp): Image(fileno(fp)) { } 101 | Image(std::string_view path): Image(::open(path.data(), O_RDONLY)) { } 102 | 103 | bool is_valid() const { 104 | return this->valid; 105 | } 106 | 107 | int parse(); 108 | 109 | std::span get_scan_data() const { 110 | return std::span(this->data->begin() + this->scan_offset, this->data->size() - this->scan_offset); 111 | } 112 | 113 | private: 114 | JpegSegmentHeader find_next_segment(Bitstream &bs); 115 | 116 | int parse_app(JpegSegmentHeader seg, Bitstream &bs); 117 | int parse_sof(JpegSegmentHeader seg, Bitstream &bs); 118 | int parse_dqt(JpegSegmentHeader seg, Bitstream &bs); 119 | int parse_dht(JpegSegmentHeader seg, Bitstream &bs); 120 | int parse_dri(JpegSegmentHeader seg, Bitstream &bs); 121 | int parse_sos(JpegSegmentHeader seg, Bitstream &bs); 122 | 123 | private: 124 | bool valid = true; 125 | std::uint32_t scan_offset = 0; 126 | std::shared_ptr> data; 127 | }; 128 | 129 | } // namespace nj 130 | -------------------------------------------------------------------------------- /examples/render-rgb.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | static void display_image(const nj::Surface &surface) { 25 | if (SDL_Init(SDL_INIT_VIDEO) < 0) { 26 | std::fprintf(stderr, "Could not initialize sdl2: %s\n", SDL_GetError()); 27 | return; 28 | } 29 | NJ_SCOPEGUARD([] { SDL_Quit(); }); 30 | 31 | auto *window = SDL_CreateWindow("nvjpg", 32 | SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 33 | 1080, 720, SDL_WINDOW_SHOWN); 34 | if (!window) { 35 | std::fprintf(stderr, "Could not create window: %s\n", SDL_GetError()); 36 | return; 37 | } 38 | NJ_SCOPEGUARD([&window] { SDL_DestroyWindow(window); }); 39 | 40 | auto *screen_surf = SDL_GetWindowSurface(window); 41 | if (!screen_surf) { 42 | std::fprintf(stderr, "Could not get window surface: %s\n", SDL_GetError()); 43 | return; 44 | } 45 | NJ_SCOPEGUARD([&screen_surf] { SDL_FreeSurface(screen_surf); }); 46 | 47 | auto *surf = SDL_CreateRGBSurfaceWithFormatFrom(const_cast(surface.data()), 48 | surface.width, surface.height, surface.get_bpp() * 8, surface.pitch, SDL_PIXELFORMAT_RGBA32); 49 | if (!surf) { 50 | std::fprintf(stderr, "Failed to create image surface: %s\n", SDL_GetError()); 51 | return; 52 | } 53 | NJ_SCOPEGUARD([&surf] { SDL_FreeSurface(surf); }); 54 | 55 | auto *converted_surf = SDL_ConvertSurface(surf, screen_surf->format, 0); 56 | if (!converted_surf) { 57 | std::fprintf(stderr, "Could not convert surface: %s\n", SDL_GetError()); 58 | return; 59 | } 60 | NJ_SCOPEGUARD([&converted_surf] { SDL_FreeSurface(converted_surf); }); 61 | 62 | SDL_BlitSurface(converted_surf, nullptr, screen_surf, nullptr); 63 | SDL_UpdateWindowSurface(window); 64 | 65 | SDL_Event e; 66 | while (true) { 67 | if (!SDL_WaitEvent(&e)) { 68 | std::fprintf(stderr, "Error while waiting on an event: %s\n", SDL_GetError()); 69 | return; 70 | } 71 | 72 | if (e.type == SDL_QUIT) 73 | break; 74 | } 75 | } 76 | 77 | int main(int argc, char **argv) { 78 | if (argc < 2) { 79 | std::fprintf(stderr, "Usage: %s jpg\n", argv[0]); 80 | return 1; 81 | } 82 | 83 | if (auto rc = nj::initialize(); rc) { 84 | std::fprintf(stderr, "Failed to initialize library: %d: %s\n", rc, std::strerror(rc)); 85 | return 1; 86 | } 87 | NJ_SCOPEGUARD([] { nj::finalize(); }); 88 | 89 | nj::Decoder decoder; 90 | if (auto rc = decoder.initialize(); rc) { 91 | std::fprintf(stderr, "Failed to initialize decoder: %#x\n", rc); 92 | return rc; 93 | } 94 | NJ_SCOPEGUARD([&decoder] { decoder.finalize(); }); 95 | 96 | nj::Image image(argv[1]); 97 | if (!image.is_valid() || image.parse()) { 98 | std::perror("Invalid file"); 99 | return 1; 100 | } 101 | 102 | std::printf("Image dimensions: %ux%u\n", image.width, image.height); 103 | 104 | nj::Surface surf(image.width, image.height, nj::PixelFormat::RGBA); 105 | if (auto rc = surf.allocate(); rc) { 106 | std::fprintf(stderr, "Failed to allocate surface: %#x\n", rc); 107 | return 1; 108 | } 109 | 110 | std::printf("Surface pitch: %#lx, size %#lx\n", surf.pitch, surf.size()); 111 | 112 | auto start = std::chrono::system_clock::now(); 113 | if (auto rc = decoder.render(image, surf, 255); rc) 114 | std::fprintf(stderr, "Failed to render image: %#x (%s)\n", rc, std::strerror(errno)); 115 | 116 | std::size_t read = 0; 117 | decoder.wait(surf, &read); 118 | auto time = std::chrono::system_clock::now() - start; 119 | std::printf("Rendered in %ldµs, read bytes: %lu\n", 120 | std::chrono::duration_cast(time).count(), read); 121 | 122 | display_image(surf); 123 | 124 | return 0; 125 | } 126 | -------------------------------------------------------------------------------- /examples/bitmap.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | namespace nj { 29 | 30 | class Bmp { 31 | public: 32 | enum class CompressionMethod: std::uint32_t { 33 | Rgb = 0, 34 | Rle8 = 1, 35 | Rle4 = 2, 36 | Bitfields = 3, 37 | Jpeg = 4, 38 | Png = 5, 39 | AlphaBitfields = 6, 40 | Cmyk = 11, 41 | CmykRle8 = 12, 42 | CmykRle4 = 13, 43 | 44 | }; 45 | 46 | struct FileHeader { 47 | char magic[2] = { 'B', 'M' }; 48 | std::uint32_t size; 49 | std::uint16_t reserved_1 = 0; 50 | std::uint16_t reserved_2 = 0; 51 | std::uint32_t offset = sizeof(FileHeader) + sizeof(ImageHeader); 52 | } __attribute__((packed)); 53 | 54 | struct ImageHeader { 55 | std::uint32_t hdr_size = sizeof(ImageHeader); 56 | std::int32_t width; 57 | std::int32_t height; 58 | std::uint16_t num_planes = 1; 59 | std::uint16_t depth = 24; 60 | CompressionMethod compression = CompressionMethod::Rgb; 61 | std::uint32_t size = 0; 62 | std::int32_t resolution_horiz = 0; 63 | std::int32_t resolution_vert = 0; 64 | std::uint32_t num_comps = 0; 65 | std::uint32_t num_comps_2 = 0; 66 | }; 67 | 68 | public: 69 | FileHeader file_header; 70 | ImageHeader image_header; 71 | 72 | public: 73 | Bmp(int width, int height, std::uint32_t num_comps = 3) { 74 | this->image_header.width = width; 75 | this->image_header.height = -height; // Negative height -> top to bottom pixel data layout 76 | this->image_header.num_comps = num_comps; 77 | this->file_header.size = sizeof(FileHeader) + sizeof(ImageHeader) + width * height * num_comps; 78 | } 79 | 80 | int write(const nj::Surface &surf, std::string_view path) { 81 | if (surf.type != nj::PixelFormat::BGRA) // Pixel data is in BGR order 82 | return -1; 83 | 84 | auto *fp = std::fopen(path.data(), "wb"); 85 | if (!fp) 86 | return 1; 87 | 88 | if (auto ret = std::fwrite(&this->file_header, 1, sizeof(FileHeader), fp); ret != sizeof(FileHeader)) 89 | return 2; 90 | 91 | if (auto ret = std::fwrite(&this->image_header, 1, sizeof(ImageHeader), fp); ret != sizeof(ImageHeader)) 92 | return 3; 93 | 94 | auto line_width = nj::align_up(this->image_header.width * this->image_header.num_comps, 4u); 95 | std::vector line_buf(line_width * std::abs(this->image_header.height), 0); 96 | 97 | for (auto i = 0; i < std::abs(this->image_header.height); ++i) { 98 | for (auto j = 0; j < this->image_header.width; ++j) { 99 | auto *src = surf.data() + i * surf.pitch + j * surf.get_bpp(); 100 | auto *dst = line_buf.data() + i * line_width + j * this->image_header.num_comps; 101 | std::copy_n(src, 3, dst); 102 | } 103 | } 104 | 105 | if (auto ret = std::fwrite(line_buf.data(), 1, line_buf.size(), fp); ret != line_buf.size()) 106 | return 4; 107 | 108 | return 0; 109 | } 110 | }; 111 | 112 | } // namespace nj 113 | -------------------------------------------------------------------------------- /include/nvjpg/nv/registers.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | 23 | namespace nj { 24 | 25 | struct NvjpgRegisters { 26 | std::array reserved_x0; 27 | std::uint32_t operation_type; // 1: decode, 2: encode 28 | std::array reserved_x204; 29 | std::uint32_t execute; 30 | std::array reserved_x304; // nvdec registers? 31 | std::uint32_t control_params; // Bitflags of various debugging options 32 | std::uint32_t picture_index; 33 | std::uint32_t picture_info_offset; 34 | std::uint32_t read_info_offset; 35 | std::uint32_t scan_data_offset; 36 | std::uint32_t out_data_offset; 37 | std::uint32_t out_data_2_offset; 38 | std::uint32_t out_data_3_offset; 39 | }; 40 | 41 | struct ThiRegisters { 42 | std::uint32_t incr_syncpt; 43 | std::uint32_t reserved_x4; 44 | std::uint32_t incr_syncpt_err; 45 | std::uint32_t ctxsw_incr_syncpt; 46 | std::array reserved_x10; 47 | std::uint32_t ctxsw; 48 | std::uint32_t reserved_x24; 49 | std::uint32_t cont_syncpt_eof; 50 | std::array reserved_x2c; 51 | std::uint32_t method_0; 52 | std::uint32_t method_1; 53 | std::array reserved_x48; 54 | std::uint32_t int_status; 55 | std::uint32_t int_mask; 56 | }; 57 | 58 | #define NJ_REGPOS(regs, member) (offsetof(regs, member) / sizeof(std::uint32_t)) 59 | 60 | struct NvjpgPictureInfo { 61 | struct alignas(std::uint32_t) Component { 62 | std::uint8_t sampling_horiz, sampling_vert; 63 | std::uint8_t quant_table_id; 64 | std::uint8_t hm_ac_table_id, hm_dc_table_id; 65 | }; 66 | 67 | struct alignas(std::uint32_t) HuffmanTable { 68 | std::array codes; 69 | std::array reserved; // Zero 70 | std::array symbols; 71 | }; 72 | 73 | struct alignas(std::uint32_t) QuantizationTable { 74 | std::array table; 75 | }; 76 | 77 | std::array hm_ac_tables; 78 | std::array hm_dc_tables; 79 | std::array components; 80 | std::array quant_tables; 81 | std::uint32_t restart_interval; 82 | std::uint32_t width, height; 83 | std::uint32_t num_mcu_h, num_mcu_v; 84 | std::uint32_t num_components; 85 | std::uint32_t scan_data_offset; 86 | std::uint32_t scan_data_size; 87 | std::uint32_t scan_data_samp_layout; 88 | std::uint32_t out_data_samp_layout; 89 | std::uint32_t out_surf_type; 90 | std::uint32_t out_luma_surf_pitch; 91 | std::uint32_t out_chroma_surf_pitch; 92 | std::uint32_t alpha; 93 | std::array yuv2rgb_kernel; // Y gain, VR, UG, VG, UB, Y offset 94 | std::uint32_t tile_mode; // 0: pitch linear, 1, block linear 95 | std::uint32_t gob_height; // If tile mode is block linear 96 | std::uint32_t memory_mode; 97 | std::uint32_t downscale_log_2; 98 | std::array reserved_xb1c; 99 | }; 100 | static_assert(sizeof(NvjpgPictureInfo) == 0xb2c); 101 | 102 | struct NvjpgStatus { 103 | std::uint32_t used_bytes; 104 | std::uint32_t mcu_x; 105 | std::uint32_t mcu_y; 106 | std::uint32_t reserved_xc; 107 | std::uint32_t result; 108 | std::uint32_t reserved_x14[3]; 109 | }; 110 | static_assert(sizeof(NvjpgStatus) == 0x20); 111 | 112 | } // namespace nj 113 | -------------------------------------------------------------------------------- /examples/render-icons.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | namespace { 25 | 26 | PadState g_pad; 27 | 28 | constexpr std::size_t fb_width = 256 * 16 / 9, fb_height = 256; // Preserve aspect ratio 29 | Framebuffer g_fb; 30 | 31 | } 32 | 33 | extern "C" void userAppInit() { 34 | socketInitializeDefault(); 35 | nxlinkStdio(); 36 | nsInitialize(); 37 | } 38 | 39 | extern "C" void userAppExit() { 40 | nsExit(); 41 | socketExit(); 42 | } 43 | 44 | static void display_image(const nj::Surface &surface) { 45 | auto *framebuf = static_cast(framebufferBegin(&g_fb, nullptr)); 46 | for (std::size_t i = 0; i < std::min(fb_height, surface.height); ++i) 47 | std::copy_n(surface.data() + i * surface.pitch, std::min(surface.width, fb_width) * surface.get_bpp(), framebuf + i * g_fb.stride); 48 | framebufferEnd(&g_fb); 49 | 50 | while (appletMainLoop()) { 51 | padUpdate(&g_pad); 52 | if (padGetButtonsDown(&g_pad) & (HidNpadButton_A | HidNpadButton_Plus)) 53 | break; 54 | } 55 | } 56 | 57 | int main(int argc, char **argv) { 58 | if (auto rc = nj::initialize(); rc) { 59 | std::fprintf(stderr, "Failed to initialize library: %d: %s\n", rc, std::strerror(rc)); 60 | return 1; 61 | } 62 | NJ_SCOPEGUARD([] { nj::finalize(); }); 63 | 64 | nj::Decoder decoder; 65 | if (auto rc = decoder.initialize(); rc) { 66 | std::fprintf(stderr, "Failed to initialize decoder: %#x\n", rc); 67 | return rc; 68 | } 69 | NJ_SCOPEGUARD([&decoder] { decoder.finalize(); }); 70 | 71 | std::printf("Press A to show the next icon, + to exit\n"); 72 | 73 | padConfigureInput(1, HidNpadStyleSet_NpadStandard); 74 | padInitializeDefault(&g_pad); 75 | 76 | framebufferCreate(&g_fb, nwindowGetDefault(), fb_width, fb_height, PIXEL_FORMAT_RGBA_8888, 2); 77 | framebufferMakeLinear(&g_fb); 78 | 79 | framebufferBegin(&g_fb, nullptr); 80 | framebufferEnd(&g_fb); 81 | 82 | int title_offset = 0; 83 | NsApplicationRecord record; 84 | auto control_data = std::make_shared>(sizeof(NsApplicationControlData)); 85 | while (appletMainLoop()) { 86 | s32 count; 87 | if (R_FAILED(nsListApplicationRecord(&record, 1, title_offset, &count)) || !record.application_id) { 88 | title_offset = 0; 89 | continue; 90 | } 91 | 92 | title_offset++; 93 | 94 | std::printf("Showing icon for %#018lx\n", record.application_id); 95 | 96 | NJ_TRY_RET(nsGetApplicationControlData(NsApplicationControlSource_Storage, record.application_id, 97 | reinterpret_cast(control_data->data()), control_data->size(), nullptr)); 98 | 99 | // We avoid copying the icon data by directly passing the whole control structure 100 | // The JFIF parser will skip the nacp data while looking for the SOI tag 101 | nj::Image image(control_data); 102 | if (!image.is_valid() || image.parse()) { 103 | std::perror("Invalid file"); 104 | return 1; 105 | } 106 | 107 | nj::Surface surf(image.width, image.height, nj::PixelFormat::RGBA); 108 | if (auto rc = surf.allocate(); rc) { 109 | std::fprintf(stderr, "Failed to allocate surface: %#x\n", rc); 110 | return 1; 111 | } 112 | 113 | auto start = std::chrono::system_clock::now(); 114 | if (auto rc = decoder.render(image, surf, 255); rc) 115 | std::fprintf(stderr, "Failed to render image: %#x (%s)\n", rc, std::strerror(errno)); 116 | 117 | std::size_t read = 0; 118 | decoder.wait(surf, &read); 119 | auto time = std::chrono::system_clock::now() - start; 120 | std::printf("Rendered in %ldµs, read bytes: %lu\n", 121 | std::chrono::duration_cast(time).count(), read); 122 | 123 | display_image(surf); 124 | 125 | if (padGetButtonsDown(&g_pad) & HidNpadButton_Plus) 126 | break; 127 | } 128 | 129 | framebufferClose(&g_fb); 130 | 131 | return 0; 132 | } 133 | -------------------------------------------------------------------------------- /include/nvjpg/nv/ioctl_types.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | #include 25 | 26 | #ifdef __SWITCH__ 27 | # include 28 | #else 29 | # include 30 | #endif 31 | 32 | #ifdef __SWITCH__ 33 | 34 | typedef nvioctl_fence nvhost_ctrl_fence; 35 | typedef nvioctl_cmdbuf nvhost_cmdbuf; 36 | typedef nvioctl_syncpt_incr nvhost_syncpt_incr; 37 | 38 | #else 39 | 40 | typedef struct { 41 | uint32_t size; 42 | uint32_t handle; 43 | } nvmap_create_args; 44 | 45 | typedef struct { 46 | uint32_t handle; 47 | uint32_t heap_mask; 48 | uint32_t flags; 49 | uint32_t align; 50 | } nvmap_alloc_args; 51 | 52 | typedef struct { 53 | uint64_t addr; 54 | uint32_t handle; 55 | uint32_t len; 56 | int32_t op; 57 | } nvmap_cache_args; 58 | 59 | #define NVMAP_IOCTL_MAGIC 'N' 60 | #define NVMAP_IOCTL_CREATE _IOWR(NVMAP_IOCTL_MAGIC, 0, nvmap_create_args) 61 | #define NVMAP_IOCTL_ALLOC _IOW (NVMAP_IOCTL_MAGIC, 3, nvmap_alloc_args) 62 | #define NVMAP_IOCTL_FREE _IO (NVMAP_IOCTL_MAGIC, 4) 63 | #define NVMAP_IOCTL_CACHE _IOW (NVMAP_IOCTL_MAGIC, 12, nvmap_cache_args) 64 | 65 | typedef struct { 66 | uint32_t id; 67 | uint32_t value; 68 | } nvhost_ctrl_fence; 69 | 70 | typedef struct { 71 | uint32_t id; 72 | uint32_t thresh; 73 | int32_t timeout; 74 | uint32_t value; 75 | } nvhost_ctrl_syncpt_waitex_args; 76 | 77 | #define NVHOST_IOCTL_MAGIC 'H' 78 | #define NVHOST_IOCTL_CTRL_SYNCPT_WAITEX _IOWR(NVHOST_IOCTL_MAGIC, 6, nvhost_ctrl_syncpt_waitex_args) 79 | 80 | typedef struct { 81 | uint32_t rate; 82 | uint32_t moduleid; 83 | } nvhost_clk_rate_args; 84 | 85 | typedef struct { 86 | uint32_t param; 87 | uint32_t value; 88 | } nvhost_get_param_args; 89 | 90 | typedef struct { 91 | uint32_t mem; 92 | uint32_t offset; 93 | uint32_t words; 94 | } nvhost_cmdbuf; 95 | 96 | typedef struct { 97 | int32_t pre_fence; 98 | uint32_t reserved; 99 | } nvhost_cmdbuf_ext; 100 | 101 | typedef struct { 102 | uint32_t cmdbuf_mem; 103 | uint32_t cmdbuf_offset; 104 | uint32_t target_mem; 105 | uint32_t target_offset; 106 | } nvhost_reloc; 107 | 108 | typedef struct { 109 | uint32_t shift; 110 | } nvhost_reloc_shift; 111 | 112 | typedef struct { 113 | uint32_t reloc_type; 114 | uint32_t padding; 115 | } nvhost_reloc_type; 116 | 117 | typedef struct { 118 | uint32_t mem; 119 | uint32_t offset; 120 | uint32_t syncpt_id; 121 | uint32_t thresh; 122 | } nvhost_waitchk; 123 | 124 | typedef struct { 125 | uint32_t syncpt_id; 126 | uint32_t syncpt_incrs; 127 | } nvhost_syncpt_incr; 128 | 129 | typedef struct { 130 | uint32_t submit_version; 131 | uint32_t num_syncpt_incrs; 132 | uint32_t num_cmdbufs; 133 | uint32_t num_relocs; 134 | uint32_t num_waitchks; 135 | uint32_t timeout; 136 | uint32_t flags; 137 | uint32_t fence; 138 | uintptr_t syncpt_incrs; 139 | uintptr_t cmdbuf_exts; 140 | 141 | uint32_t checksum_methods; 142 | uint32_t checksum_falcon_methods; 143 | 144 | uint64_t pad[1]; 145 | 146 | uintptr_t reloc_types; 147 | uintptr_t cmdbufs; 148 | uintptr_t relocs; 149 | uintptr_t reloc_shifts; 150 | uintptr_t waitchks; 151 | uintptr_t waitbases; 152 | uintptr_t class_ids; 153 | uintptr_t fences; 154 | } nvhost_submit_args; 155 | 156 | #define NVHOST_SUBMIT_VERSION_V2 2 157 | 158 | #define NVHOST_IOCTL_CHANNEL_GET_CLK_RATE _IOWR(NVHOST_IOCTL_MAGIC, 9, nvhost_clk_rate_args) 159 | #define NVHOST_IOCTL_CHANNEL_SET_CLK_RATE _IOW (NVHOST_IOCTL_MAGIC, 10, nvhost_clk_rate_args) 160 | #define NVHOST_IOCTL_CHANNEL_GET_SYNCPOINT _IOWR(NVHOST_IOCTL_MAGIC, 16, nvhost_get_param_args) 161 | #define NVHOST_IOCTL_CHANNEL_SUBMIT _IOWR(NVHOST_IOCTL_MAGIC, 26, nvhost_submit_args) 162 | 163 | #endif 164 | 165 | enum { 166 | NVMAP_CACHE_OP_WB = 0, 167 | NVMAP_CACHE_OP_INV = 1, 168 | NVMAP_CACHE_OP_WB_INV = 2, 169 | }; 170 | 171 | enum { 172 | NVHOST_RELOC_TYPE_DEFAULT = 0, 173 | NVHOST_RELOC_TYPE_PITCH_LINEAR = 1, 174 | NVHOST_RELOC_TYPE_BLOCK_LINEAR = 2, 175 | NVHOST_RELOC_TYPE_NVLINK = 3, 176 | }; 177 | 178 | #ifdef __cplusplus 179 | } 180 | #endif // extern "C" 181 | -------------------------------------------------------------------------------- /examples/render-yuv.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | static void display_image(const nj::VideoSurface &surface) { 25 | if (SDL_Init(SDL_INIT_VIDEO) < 0) { 26 | std::fprintf(stderr, "Could not initialize sdl2: %s\n", SDL_GetError()); 27 | return; 28 | } 29 | NJ_SCOPEGUARD([] { SDL_Quit(); }); 30 | 31 | auto *window = SDL_CreateWindow("nvjpg", 32 | SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 33 | 1080, 720, SDL_WINDOW_SHOWN); 34 | if (!window) { 35 | std::fprintf(stderr, "Could not create window: %s\n", SDL_GetError()); 36 | return; 37 | } 38 | NJ_SCOPEGUARD([&window] { SDL_DestroyWindow(window); }); 39 | 40 | auto *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); 41 | if (!renderer) { 42 | std::fprintf(stderr, "Could not create renderer: %s\n", SDL_GetError()); 43 | return; 44 | } 45 | NJ_SCOPEGUARD([&renderer] { SDL_DestroyRenderer(renderer); }); 46 | 47 | auto *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_YV12, SDL_TEXTUREACCESS_STREAMING, surface.width, surface.height); 48 | if (!texture) { 49 | std::fprintf(stderr, "Could not create texture: %s\n", SDL_GetError()); 50 | return; 51 | } 52 | NJ_SCOPEGUARD([&texture] { SDL_DestroyTexture(texture); }); 53 | 54 | if (auto rc = SDL_UpdateYUVTexture(texture, nullptr, surface.luma_data, surface.luma_pitch, 55 | surface.chromab_data, surface.chroma_pitch, surface.chromar_data, surface.chroma_pitch); rc) { 56 | std::fprintf(stderr, "Failed to update texture: %s\n", SDL_GetError()); 57 | return; 58 | } 59 | 60 | int width, height; 61 | SDL_GetWindowSize(window, &width, &height); 62 | 63 | SDL_Rect rect = { 64 | .x = 0, .y = 0, 65 | .w = std::min(static_cast(surface.width), width), 66 | .h = std::min(static_cast(surface.height), height), 67 | }; 68 | 69 | if (auto rc = SDL_RenderCopy(renderer, texture, &rect, &rect); rc) { 70 | std::fprintf(stderr, "Failed to render texture: %s\n", SDL_GetError()); 71 | return; 72 | } 73 | 74 | SDL_RenderPresent(renderer); 75 | 76 | SDL_Event e; 77 | while (true) { 78 | if (!SDL_WaitEvent(&e)) { 79 | std::fprintf(stderr, "Error while waiting on an event: %s\n", SDL_GetError()); 80 | return; 81 | } 82 | 83 | if (e.type == SDL_QUIT) 84 | break; 85 | } 86 | } 87 | 88 | int main(int argc, char **argv) { 89 | if (argc < 2) { 90 | std::fprintf(stderr, "Usage: %s jpg\n", argv[0]); 91 | return 1; 92 | } 93 | 94 | if (auto rc = nj::initialize(); rc) { 95 | std::fprintf(stderr, "Failed to initialize library: %d: %s\n", rc, std::strerror(rc)); 96 | return 1; 97 | } 98 | NJ_SCOPEGUARD([] { nj::finalize(); }); 99 | 100 | nj::Decoder decoder; 101 | if (auto rc = decoder.initialize(); rc) { 102 | std::fprintf(stderr, "Failed to initialize decoder: %#x\n", rc); 103 | return rc; 104 | } 105 | NJ_SCOPEGUARD([&decoder] { decoder.finalize(); }); 106 | 107 | nj::Image image(argv[1]); 108 | if (!image.is_valid() || image.parse()) { 109 | std::perror("Invalid file"); 110 | return 1; 111 | } 112 | 113 | std::printf("Image dimensions: %ux%u\n", image.width, image.height); 114 | 115 | // Note: SDL only support YV12 so setting the color format to something else will offset the chroma data in the display window 116 | nj::VideoSurface surf(image.width, image.height, nj::SamplingFormat::S420); 117 | if (auto rc = surf.allocate(); rc) { 118 | std::fprintf(stderr, "Failed to allocate surface: %#x\n", rc); 119 | return 1; 120 | } 121 | 122 | std::printf("Surface luma pitch: %#lx, chroma pitch: %#lx, size %#lx\n", surf.luma_pitch, surf.chroma_pitch, surf.size()); 123 | 124 | auto start = std::chrono::system_clock::now(); 125 | if (auto rc = decoder.render(image, surf); rc) 126 | std::fprintf(stderr, "Failed to render image: %#x (%s)\n", rc, std::strerror(errno)); 127 | 128 | std::size_t read = 0; 129 | decoder.wait(surf, &read); 130 | auto time = std::chrono::system_clock::now() - start; 131 | std::printf("Rendered in %ldµs, read bytes: %lu\n", 132 | std::chrono::duration_cast(time).count(), read); 133 | 134 | display_image(surf); 135 | 136 | return 0; 137 | } 138 | -------------------------------------------------------------------------------- /include/nvjpg/nv/cmdbuf.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | #include 25 | #include 26 | #include 27 | 28 | namespace nj { 29 | 30 | struct Host1xOpcode { 31 | std::uint32_t value = 0; 32 | 33 | constexpr inline operator std::uint32_t() const { 34 | return this->value; 35 | } 36 | }; 37 | 38 | struct OpcodeSetClass: public Host1xOpcode { 39 | constexpr OpcodeSetClass(std::uint32_t class_id, std::uint32_t offset = 0, std::uint32_t mask = 0) { 40 | this->value = (0 << 28) | (offset << 16) | (class_id << 6) | mask; 41 | } 42 | }; 43 | 44 | struct OpcodeIncr: public Host1xOpcode { 45 | constexpr OpcodeIncr(std::uint32_t offset, std::uint32_t count) { 46 | this->value = (1 << 28) | (offset << 16) | count; 47 | } 48 | }; 49 | 50 | struct OpcodeNonIncr: public Host1xOpcode { 51 | constexpr OpcodeNonIncr(std::uint32_t offset, std::uint32_t count) { 52 | this->value = (2 << 28) | (offset << 16) | count; 53 | } 54 | }; 55 | 56 | struct OpcodeMask: public Host1xOpcode { 57 | constexpr OpcodeMask(std::uint32_t offset, std::uint32_t mask) { 58 | this->value = (3 << 28) | (offset << 16) | mask; 59 | } 60 | }; 61 | 62 | struct OpcodeImm: public Host1xOpcode { 63 | constexpr OpcodeImm(std::uint32_t offset, std::uint32_t value) { 64 | this->value = (4 << 28) | (offset << 16) | value; 65 | } 66 | }; 67 | 68 | class CmdBuf { 69 | public: 70 | using Word = std::uint32_t; 71 | 72 | public: 73 | CmdBuf(const NvMap &map): map(map), cur_word(static_cast(map.address())) { } 74 | 75 | std::size_t size() const { 76 | return static_cast(this->cur_word - static_cast(this->map.address())); 77 | } 78 | 79 | void begin(std::uint32_t class_id, std::int32_t pre_fence = -1) { 80 | this->bufs.push_back({ this->map.handle(), static_cast(this->size() * sizeof(Word)), 0 }); 81 | 82 | this->cur_buf_begin = this->size(); 83 | 84 | #ifndef __SWITCH__ 85 | this->exts.push_back({ pre_fence, 0 }); 86 | this->class_ids.push_back(class_id); 87 | #endif 88 | } 89 | 90 | void end() { 91 | this->bufs.back().words = this->size() - this->cur_buf_begin; 92 | } 93 | 94 | void clear() { 95 | this->cur_word = static_cast(this->map.address()); 96 | this->bufs .clear(); 97 | #ifndef __SWITCH__ 98 | this->exts .clear(), this->class_ids.clear(); 99 | this->relocs.clear(), this->shifts .clear(), this->types.clear(); 100 | #endif 101 | } 102 | 103 | void push_raw(Word word) { 104 | *this->cur_word++ = word; 105 | } 106 | 107 | void push_value(std::uint32_t offset, std::uint32_t value) { 108 | constexpr auto op = OpcodeIncr(NJ_REGPOS(ThiRegisters, method_0), 2); 109 | 110 | this->push_raw(op); 111 | this->push_raw(offset); 112 | this->push_raw(value); 113 | } 114 | 115 | void push_reloc(std::uint32_t offset, const NvMap &target, std::uint32_t target_offset = 0, 116 | std::uint32_t shift = 8, std::uint32_t type = NVHOST_RELOC_TYPE_DEFAULT) { 117 | #ifdef __SWITCH__ 118 | // On the Switch, resolve relocations on the client side 119 | this->push_value(offset, (target.iova() + target_offset) >> shift); 120 | #else 121 | this->push_value(offset, 0xdeadbeef); // Officially used placeholder value 122 | 123 | this->relocs.push_back({ 124 | .cmdbuf_mem = this->map.handle(), 125 | .cmdbuf_offset = static_cast((this->size() - 1) * sizeof(Word)), 126 | .target_mem = target.handle(), 127 | .target_offset = target_offset, 128 | }); 129 | this->shifts.push_back({ shift }); 130 | this->types.push_back({ type, 0 }); 131 | #endif 132 | } 133 | 134 | #ifdef __SWITCH__ 135 | auto &get_bufs() { 136 | return this->bufs; 137 | } 138 | #else 139 | auto get_bufs() const { 140 | return std::make_tuple(this->bufs, this->exts, this->class_ids); 141 | } 142 | 143 | auto get_relocs() const { 144 | return std::make_tuple(this->relocs, this->shifts, this->types); 145 | } 146 | #endif 147 | 148 | private: 149 | const NvMap ↦ 150 | Word *cur_word; 151 | 152 | std::size_t cur_buf_begin = 0; 153 | 154 | std::vector bufs; 155 | 156 | #ifndef __SWITCH__ 157 | std::vector exts; 158 | std::vector class_ids; 159 | 160 | std::vector relocs; 161 | std::vector shifts; 162 | std::vector types; 163 | #endif 164 | }; 165 | 166 | } // namespace nj 167 | -------------------------------------------------------------------------------- /include/nvjpg/surface.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | #include 25 | #include 26 | 27 | #if defined(__SWITCH__) && __has_include() 28 | # include 29 | #endif 30 | 31 | namespace nj { 32 | 33 | enum class PixelFormat { 34 | YUV = 0, 35 | RGB = 1, 36 | BGR = 2, 37 | RGBA = 3, 38 | BGRA = 4, 39 | ABGR = 5, 40 | ARGB = 6, 41 | }; 42 | 43 | enum class SamplingFormat { 44 | Monochrome = 0, 45 | S420 = 1, 46 | S422 = 2, 47 | S440 = 3, 48 | S444 = 4, 49 | }; 50 | 51 | enum class MemoryMode { 52 | SemiPlanarNv12 = 0, 53 | SemiPlanarNv21 = 1, 54 | SinglyPlanar = 2, 55 | Planar = 3, 56 | }; 57 | 58 | class SurfaceBase { 59 | public: 60 | std::size_t width, height; 61 | PixelFormat type; 62 | 63 | public: 64 | constexpr SurfaceBase(std::size_t width, std::size_t height, PixelFormat type): 65 | width(width), height(height), type(type) { } 66 | 67 | const std::uint8_t *data() const { 68 | return static_cast(this->map.address()); 69 | } 70 | 71 | std::size_t size() const { 72 | return this->map.size(); 73 | } 74 | 75 | const NvMap &get_map() const { 76 | return this->map; 77 | } 78 | 79 | protected: 80 | NvMap map; 81 | 82 | #ifdef __SWITCH__ 83 | NvFence render_fence = {}; 84 | #else 85 | nvhost_ctrl_fence render_fence = {}; 86 | #endif 87 | 88 | friend class Decoder; 89 | }; 90 | 91 | class Surface: public SurfaceBase { 92 | public: 93 | std::size_t pitch; 94 | 95 | public: 96 | constexpr Surface(std::size_t width, std::size_t height, PixelFormat pixel_fmt = PixelFormat::RGBA): 97 | SurfaceBase(width, height, pixel_fmt) { } 98 | 99 | int allocate(); 100 | 101 | constexpr int get_bpp() const { 102 | switch (this->type) { 103 | case PixelFormat::RGB ... PixelFormat::BGR: 104 | return 3; 105 | case PixelFormat::RGBA ... PixelFormat::ARGB: 106 | default: 107 | return 4; 108 | } 109 | } 110 | 111 | #if defined(__SWITCH__) && __has_include() 112 | std::tuple to_deko3d(dk::Device device, std::uint32_t flags = 0) const { 113 | auto map_dk_fmt = [](PixelFormat fmt) { 114 | switch (fmt) { 115 | case PixelFormat::RGB: 116 | return DkImageFormat_RGBX8_Unorm; 117 | case PixelFormat::BGR: 118 | return DkImageFormat_BGRX8_Unorm; 119 | case PixelFormat::RGBA: 120 | default: 121 | return DkImageFormat_RGBA8_Unorm; 122 | case PixelFormat::BGRA: 123 | return DkImageFormat_BGRA8_Unorm; 124 | } 125 | }; 126 | 127 | dk::ImageLayout layout; 128 | dk::ImageLayoutMaker{device} 129 | .setFlags(flags | DkImageFlags_PitchLinear) 130 | .setPitchStride(this->pitch) 131 | .setFormat(map_dk_fmt(this->type)) 132 | .setDimensions(this->width, this->height) 133 | .initialize(layout); 134 | 135 | auto image_size = align_up(static_cast(layout.getSize()), layout.getAlignment()); 136 | auto image_memblock = dk::MemBlockMaker(device, image_size) 137 | .setFlags(DkMemBlockFlags_CpuUncached | DkMemBlockFlags_GpuCached | DkMemBlockFlags_Image) 138 | .setStorage(this->map.address()) 139 | .create(); 140 | 141 | dk::Image image; 142 | image.initialize(layout, image_memblock, 0); 143 | 144 | return { image_memblock, image }; 145 | } 146 | #endif 147 | 148 | constexpr auto get_memory_mode() const { 149 | return MemoryMode::Planar; 150 | } 151 | }; 152 | 153 | class VideoSurface: public SurfaceBase { 154 | public: 155 | SamplingFormat sampling; 156 | std::size_t luma_pitch, chroma_pitch; 157 | const std::uint8_t *luma_data, *chromab_data, *chromar_data; 158 | 159 | public: 160 | constexpr VideoSurface(std::size_t width, std::size_t height, SamplingFormat sampling = SamplingFormat::S420): 161 | SurfaceBase(width, height, PixelFormat::YUV), sampling(sampling) { } 162 | 163 | int allocate(); 164 | 165 | constexpr int get_depth() const { 166 | switch (this->sampling) { 167 | case SamplingFormat::S420: 168 | default: 169 | return 12; 170 | case SamplingFormat::S422: 171 | return 16; 172 | case SamplingFormat::S440: 173 | return 16; 174 | case SamplingFormat::S444: 175 | return 24; 176 | } 177 | } 178 | 179 | constexpr auto get_memory_mode() const { 180 | return MemoryMode::Planar; 181 | } 182 | }; 183 | 184 | } // namespace nj 185 | -------------------------------------------------------------------------------- /include/nvjpg/nv/channel.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #include 19 | #include 20 | 21 | #ifdef __SWITCH__ 22 | # include 23 | #else 24 | # include 25 | # include 26 | # include 27 | # include 28 | # include 29 | #endif 30 | 31 | #include 32 | #include 33 | 34 | namespace nj { 35 | 36 | class NvChannel { 37 | public: 38 | constexpr NvChannel() = default; 39 | 40 | ~NvChannel() { 41 | #ifdef __SWITCH__ 42 | if (this->channel.fd != -1u) 43 | #else 44 | if (this->fd != -1) 45 | #endif 46 | this->close(); 47 | } 48 | 49 | Result open(const char *path) { 50 | #ifdef __SWITCH__ 51 | NJ_TRY_RET(nvChannelCreate(&this->channel, path)); 52 | NJ_TRY_RET(nvioctlChannel_GetSyncpt(this->channel.fd, 0, &this->syncpt)); 53 | return 0; 54 | #else 55 | this->fd = ::open(path, O_RDWR | O_CLOEXEC); 56 | if (this->fd < 0) 57 | return this->fd; 58 | 59 | nvhost_get_param_args args = { 60 | .param = 0, 61 | .value = -1u, 62 | }; 63 | 64 | auto rc = ::ioctl(this->fd, NVHOST_IOCTL_CHANNEL_GET_SYNCPOINT, &args); 65 | if (!rc) 66 | this->syncpt = args.value; 67 | 68 | return this->fd; 69 | #endif 70 | } 71 | 72 | Result close() { 73 | #ifdef __SWITCH__ 74 | nvChannelClose(&this->channel); 75 | return 0; 76 | #else 77 | auto rc = ::close(this->fd); 78 | if (rc != -1) 79 | this->fd = -1; 80 | return rc; 81 | #endif 82 | } 83 | 84 | Result get_clock_rate(std::uint32_t id, std::uint32_t &rate) const { 85 | #ifdef __SWITCH__ 86 | return 0; 87 | #else 88 | nvhost_clk_rate_args args = { 89 | .rate = 0, 90 | .moduleid = id, 91 | }; 92 | 93 | auto rc = ::ioctl(this->fd, NVHOST_IOCTL_CHANNEL_GET_CLK_RATE, &args); 94 | if (!rc) 95 | rate = args.rate; 96 | 97 | return rc; 98 | #endif 99 | } 100 | 101 | Result set_clock_rate(std::uint32_t id, std::uint32_t rate) const { 102 | #ifdef __SWITCH__ 103 | return 0; 104 | #else 105 | nvhost_clk_rate_args args = { 106 | .rate = rate, 107 | .moduleid = id, 108 | }; 109 | 110 | return ::ioctl(this->fd, NVHOST_IOCTL_CHANNEL_SET_CLK_RATE, &args); 111 | #endif 112 | } 113 | 114 | #ifdef __SWITCH__ 115 | Result submit(std::span cmdbufs, std::span relocs, std::span shifts, 116 | std::span incrs, std::span fences) { 117 | return nvioctlChannel_Submit(this->channel.fd, cmdbufs.data(), static_cast(cmdbufs.size()), 118 | relocs.data(), shifts.data(), static_cast(relocs.size()), 119 | incrs.data(), static_cast(incrs.size()), 120 | fences.data(), static_cast(fences.size())); 121 | } 122 | #else 123 | Result submit(std::span cmdbufs, std::span exts, std::span class_ids, 124 | std::span relocs, std::span shifts, std::span types, 125 | std::span incrs, std::span fences, nvhost_ctrl_fence &fence) const { 126 | nvhost_submit_args args = { 127 | .submit_version = NVHOST_SUBMIT_VERSION_V2, 128 | .num_syncpt_incrs = static_cast(incrs.size()), 129 | .num_cmdbufs = static_cast(cmdbufs.size()), 130 | .num_relocs = static_cast(relocs.size()), 131 | .num_waitchks = 0, 132 | .timeout = 0, 133 | .flags = 0, 134 | .fence = 0, 135 | .syncpt_incrs = reinterpret_cast(incrs.data()), 136 | .cmdbuf_exts = reinterpret_cast(exts.data()), 137 | .checksum_methods = 0, 138 | .checksum_falcon_methods = 0, 139 | .pad = { 0 }, 140 | .reloc_types = reinterpret_cast(types.data()), 141 | .cmdbufs = reinterpret_cast(cmdbufs.data()), 142 | .relocs = reinterpret_cast(relocs.data()), 143 | .reloc_shifts = reinterpret_cast(shifts.data()), 144 | .waitchks = reinterpret_cast(nullptr), 145 | .waitbases = reinterpret_cast(nullptr), 146 | .class_ids = reinterpret_cast(class_ids.data()), 147 | .fences = reinterpret_cast(fences.data()), 148 | }; 149 | 150 | auto rc = ::ioctl(this->fd, NVHOST_IOCTL_CHANNEL_SUBMIT, &args); 151 | if (!rc) 152 | fence.value = args.fence; 153 | 154 | return rc; 155 | } 156 | #endif 157 | 158 | Result get_fd() const { 159 | #ifdef __SWITCH__ 160 | return this->channel.fd; 161 | #else 162 | return this->fd; 163 | #endif 164 | } 165 | 166 | std::uint32_t get_syncpt() const { 167 | return this->syncpt; 168 | } 169 | 170 | private: 171 | std::uint32_t syncpt = 0; 172 | 173 | #ifdef __SWITCH__ 174 | ::NvChannel channel = {}; 175 | #else 176 | int fd = 0; 177 | #endif 178 | }; 179 | 180 | } // namespace nj 181 | -------------------------------------------------------------------------------- /include/nvjpg/nv/map.hpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | 23 | #ifdef __SWITCH__ 24 | # include 25 | #else 26 | # include 27 | # include 28 | # include 29 | # include 30 | # include 31 | #endif 32 | 33 | #include 34 | #include 35 | 36 | namespace nj { 37 | 38 | class NvMap { 39 | public: 40 | static Result initialize() { 41 | #ifdef __SWITCH__ 42 | return nvMapInit(); 43 | #else 44 | return NvMap::nvmap_fd = ::open("/dev/nvmap", O_RDWR | O_SYNC | O_CLOEXEC); 45 | #endif 46 | } 47 | 48 | static Result finalize() { 49 | #ifdef __SWITCH__ 50 | nvMapExit(); 51 | return 0; 52 | #else 53 | return ::close(NvMap::nvmap_fd); 54 | #endif 55 | } 56 | 57 | constexpr NvMap() = default; 58 | 59 | ~NvMap() { 60 | #ifdef __SWITCH__ 61 | if (this->addr) 62 | this->unmap(); 63 | 64 | if (this->nvmap.cpu_addr) 65 | this->free(); 66 | #else 67 | if (this->addr) 68 | this->unmap(); 69 | 70 | if (this->hdl) 71 | this->free(); 72 | #endif 73 | } 74 | 75 | Result allocate(std::uint32_t size, std::uint32_t align, std::uint32_t flags) { 76 | #ifdef __SWITCH__ 77 | NJ_UNUSED(flags); 78 | 79 | size = align_up(size, 0x1000u), align = align_up(align, 0x1000u); 80 | auto *mapmem = new (std::align_val_t(align)) std::uint8_t[size]; 81 | if (!mapmem) 82 | return MAKERESULT(Module_Libnx, LibnxError_OutOfMemory); 83 | 84 | return nvMapCreate(&this->nvmap, mapmem, size, align, NvKind_Pitch, false); 85 | #else 86 | nvmap_create_args create = { 87 | .size = size, 88 | .handle = 0, 89 | }; 90 | 91 | auto rc = ::ioctl(NvMap::nvmap_fd, NVMAP_IOCTL_CREATE, &create); 92 | if (rc) 93 | return rc; 94 | 95 | this->sz = size; 96 | this->hdl = create.handle; 97 | 98 | nvmap_alloc_args alloc = { 99 | .handle = this->hdl, 100 | .heap_mask = 0x40000000, 101 | .flags = flags, 102 | .align = align, 103 | }; 104 | 105 | return ::ioctl(NvMap::nvmap_fd, NVMAP_IOCTL_ALLOC, &alloc); 106 | #endif 107 | } 108 | 109 | Result free() { 110 | if (this->addr) 111 | NJ_TRY_RET(this->unmap()); 112 | 113 | #ifdef __SWITCH__ 114 | delete[] static_cast(this->nvmap.cpu_addr); 115 | nvMapClose(&this->nvmap); 116 | return 0; 117 | #else 118 | auto rc = ::ioctl(NvMap::nvmap_fd, NVMAP_IOCTL_FREE, this->hdl); 119 | if (!rc) 120 | this->hdl = 0; 121 | 122 | return rc; 123 | #endif 124 | } 125 | 126 | #ifdef __SWITCH__ 127 | Result map(int channel_fd, bool compressed = false) { 128 | nvioctl_command_buffer_map params = { .handle = this->nvmap.handle }; 129 | NJ_TRY_RET(nvioctlChannel_MapCommandBuffer(channel_fd, ¶ms, 1, compressed)); 130 | this->owner = channel_fd, this->compressed = compressed, this->addr = params.iova; 131 | return 0; 132 | } 133 | #else 134 | void *map(int prot = PROT_READ | PROT_WRITE, int flags = MAP_SHARED) { 135 | return this->addr = ::mmap(nullptr, this->sz, prot, flags, this->hdl, 0); 136 | } 137 | #endif 138 | 139 | Result unmap() { 140 | #ifdef __SWITCH__ 141 | nvioctl_command_buffer_map params = { .handle = this->nvmap.handle }; 142 | NJ_TRY_RET(nvioctlChannel_UnmapCommandBuffer(this->owner, ¶ms, 1, this->compressed)); 143 | this->addr = 0; 144 | return 0; 145 | #else 146 | auto rc = ::munmap(this->addr, sz); 147 | if (!rc) 148 | this->addr = nullptr; 149 | 150 | return rc; 151 | #endif 152 | } 153 | 154 | Result cache(std::size_t size, std::int32_t op = NVMAP_CACHE_OP_WB) const { 155 | #ifdef __SWITCH__ 156 | return 0; 157 | #else 158 | nvmap_cache_args args = { 159 | .addr = reinterpret_cast(this->addr), 160 | .handle = this->hdl, 161 | .len = static_cast(size), 162 | .op = op, 163 | }; 164 | 165 | return ::ioctl(NvMap::nvmap_fd, NVMAP_IOCTL_CACHE, &args); 166 | #endif 167 | } 168 | 169 | Result cache(std::uint32_t op = NVMAP_CACHE_OP_WB) const { 170 | #ifdef __SWITCH__ 171 | return 0; 172 | #else 173 | return this->cache(this->sz, op); 174 | #endif 175 | } 176 | 177 | std::size_t size() const { 178 | #ifdef __SWITCH__ 179 | return this->nvmap.size; 180 | #else 181 | return this->sz; 182 | #endif 183 | } 184 | 185 | std::uint32_t handle() const { 186 | #ifdef __SWITCH__ 187 | return this->nvmap.handle; 188 | #else 189 | return this->hdl; 190 | #endif 191 | } 192 | 193 | void *address() const { 194 | #ifdef __SWITCH__ 195 | return this->nvmap.cpu_addr; 196 | #else 197 | return this->addr; 198 | #endif 199 | } 200 | 201 | #ifdef __SWITCH__ 202 | std::uint32_t iova() const { 203 | return this->addr; 204 | } 205 | #endif 206 | 207 | private: 208 | #ifdef __SWITCH__ 209 | ::NvMap nvmap = {}; 210 | std::uint32_t addr = 0; 211 | std::uint32_t owner = 0; 212 | bool compressed = false; 213 | #else 214 | std::uint32_t sz = 0; 215 | std::uint32_t hdl = 0; 216 | void *addr = nullptr; 217 | 218 | static inline int nvmap_fd; 219 | #endif 220 | }; 221 | 222 | } // namespace nj 223 | -------------------------------------------------------------------------------- /examples/render-deko3d.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | // In this example, we render the decoded data by directly blitting it onto the framebuffer 19 | // For more conventional use of textures within deko3d, see: 20 | // https://github.com/switchbrew/switch-examples/tree/master/graphics/deko3d/deko_examples 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | extern "C" void userAppInit() { 34 | socketInitializeDefault(); 35 | nxlinkStdio(); 36 | } 37 | 38 | extern "C" void userAppExit() { 39 | socketExit(); 40 | } 41 | 42 | namespace { 43 | 44 | constexpr std::uint32_t FB_WIDTH = 1280; 45 | constexpr std::uint32_t FB_HEIGHT = 720; 46 | constexpr std::uint32_t FB_NUM = 2; 47 | constexpr std::size_t CMDBUF_SIZE = 10 * DK_MEMBLOCK_ALIGNMENT; 48 | 49 | dk::UniqueDevice device; 50 | dk::UniqueMemBlock fb_memblock, cmdbuf_memblock, image_memblock; 51 | dk::UniqueSwapchain swapchain; 52 | dk::UniqueCmdBuf cmdbuf; 53 | dk::UniqueQueue queue; 54 | 55 | dk::Image image; 56 | std::array framebuffer_images; 57 | 58 | std::array render_cmdlists; 59 | std::array bind_fb_cmdlists; 60 | 61 | } // namespace 62 | 63 | void deko_init() { 64 | device = dk::DeviceMaker().create(); 65 | 66 | dk::ImageLayout fb_layout; 67 | dk::ImageLayoutMaker(device) 68 | .setFlags(DkImageFlags_UsageRender | DkImageFlags_UsagePresent | DkImageFlags_HwCompression | DkImageFlags_Usage2DEngine) 69 | .setFormat(DkImageFormat_RGBA8_Unorm) 70 | .setDimensions(FB_WIDTH, FB_HEIGHT) 71 | .initialize(fb_layout); 72 | 73 | auto fb_size = nj::align_up(static_cast(fb_layout.getSize()), fb_layout.getAlignment()); 74 | fb_memblock = dk::MemBlockMaker(device, FB_NUM * fb_size) 75 | .setFlags(DkMemBlockFlags_GpuCached | DkMemBlockFlags_Image) 76 | .create(); 77 | 78 | std::array swapchain_images = { 79 | &framebuffer_images[0], &framebuffer_images[1], 80 | }; 81 | 82 | for (std::size_t i = 0; i < framebuffer_images.size(); ++i) 83 | framebuffer_images[i].initialize(fb_layout, fb_memblock, i * fb_size); 84 | 85 | swapchain = dk::SwapchainMaker(device, nwindowGetDefault(), swapchain_images) 86 | .create(); 87 | 88 | queue = dk::QueueMaker(device) 89 | .setFlags(DkQueueFlags_Graphics) 90 | .create(); 91 | 92 | cmdbuf_memblock = dk::MemBlockMaker(device, CMDBUF_SIZE) 93 | .setFlags(DkMemBlockFlags_CpuUncached | DkMemBlockFlags_GpuCached) 94 | .create(); 95 | 96 | cmdbuf = dk::CmdBufMaker(device) 97 | .create(); 98 | 99 | cmdbuf.addMemory(cmdbuf_memblock, 0, cmdbuf_memblock.getSize()); 100 | 101 | for (std::size_t i = 0; i < framebuffer_images.size(); ++i) { 102 | auto view = dk::ImageView(framebuffer_images[i]); 103 | cmdbuf.bindRenderTargets(&view); 104 | bind_fb_cmdlists[i] = cmdbuf.finishList(); 105 | } 106 | } 107 | 108 | void deko_gencmdlist(const nj::Surface &surf) { 109 | std::tie(image_memblock, image) = surf.to_deko3d(device, DkImageFlags_HwCompression | DkImageFlags_Usage2DEngine); 110 | 111 | DkImageRect rect = { 112 | 0, 0, 0, 113 | std::min(static_cast(surf.width), FB_WIDTH), 114 | std::min(static_cast(surf.height), FB_HEIGHT), 115 | 1, 116 | }; 117 | 118 | // TODO: Use dkCmdBufCopyImage, which is not implemented yet 119 | for (std::size_t i = 0; i < framebuffer_images.size(); ++i) { 120 | cmdbuf.setViewports(0, DkViewport(0.0f, 0.0f, FB_WIDTH, FB_HEIGHT, 0.0f, 1.0f)); 121 | cmdbuf.setScissors(0, DkScissor(0, 0, FB_WIDTH, FB_HEIGHT)); 122 | cmdbuf.clearColor(0, DkColorMask_RGBA, 0.1f, 0.1f, 0.1f); 123 | cmdbuf.blitImage(dk::ImageView(image), rect, dk::ImageView(framebuffer_images[i]), rect, 0, 0); 124 | render_cmdlists[i] = cmdbuf.finishList(); 125 | } 126 | } 127 | 128 | void deko_render() { 129 | auto slot = queue.acquireImage(swapchain); 130 | 131 | queue.submitCommands(bind_fb_cmdlists[slot]); 132 | queue.submitCommands(render_cmdlists[slot]); 133 | queue.presentImage(swapchain, slot); 134 | } 135 | 136 | void deko_exit() { 137 | queue.waitIdle(); 138 | 139 | queue.destroy(); 140 | cmdbuf.destroy(); 141 | image_memblock.destroy(); 142 | cmdbuf_memblock.destroy(); 143 | fb_memblock.destroy(); 144 | swapchain.destroy(); 145 | device.destroy(); 146 | } 147 | 148 | int main(int argc, char **argv) { 149 | // Call this before dkDeviceCreate 150 | if (auto rc = nj::initialize(); rc) { 151 | std::fprintf(stderr, "Failed to initialize library: %d: %s\n", rc, std::strerror(rc)); 152 | return 1; 153 | } 154 | NJ_SCOPEGUARD([] { nj::finalize(); }); 155 | 156 | nj::Decoder decoder; 157 | if (auto rc = decoder.initialize(); rc) { 158 | std::fprintf(stderr, "Failed to initialize decoder: %#x\n", rc); 159 | return rc; 160 | } 161 | NJ_SCOPEGUARD([&decoder] { decoder.finalize(); }); 162 | 163 | nj::Image image((argc < 2) ? "sdmc:/test.jpg" : argv[1]); 164 | if (!image.is_valid() || image.parse()) { 165 | std::perror("Invalid file"); 166 | return 1; 167 | } 168 | 169 | std::printf("Image dimensions: %ux%u\n", image.width, image.height); 170 | 171 | nj::Surface surf(image.width, image.height, nj::PixelFormat::BGRA); 172 | if (auto rc = surf.allocate(); rc) { 173 | std::fprintf(stderr, "Failed to allocate surface: %#x\n", rc); 174 | return 1; 175 | } 176 | 177 | std::printf("Surface pitch: %#lx, size %#lx\n", surf.pitch, surf.size()); 178 | 179 | auto start = std::chrono::system_clock::now(); 180 | if (auto rc = decoder.render(image, surf, 255); rc) 181 | std::fprintf(stderr, "Failed to render image: %#x (%s)\n", rc, std::strerror(errno)); 182 | 183 | std::size_t read = 0; 184 | decoder.wait(surf, &read); 185 | auto time = std::chrono::system_clock::now() - start; 186 | std::printf("Rendered in %ldµs, read bytes: %lu\n", 187 | std::chrono::duration_cast(time).count(), read); 188 | 189 | deko_init(); 190 | deko_gencmdlist(surf); 191 | 192 | PadState pad; 193 | padConfigureInput(1, HidNpadStyleSet_NpadStandard); 194 | padInitializeDefault(&pad); 195 | 196 | while (appletMainLoop()) { 197 | padUpdate(&pad); 198 | if (padGetButtonsDown(&pad) & HidNpadButton_Plus) 199 | break; 200 | 201 | deko_render(); 202 | } 203 | 204 | deko_exit(); 205 | 206 | return 0; 207 | } 208 | -------------------------------------------------------------------------------- /lib/image.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | #include 23 | #include 24 | 25 | namespace nj { 26 | 27 | namespace { 28 | 29 | void skip_segment(JpegSegmentHeader seg, Bitstream &bs) { 30 | bs.skip(seg.size - sizeof(seg.size)); 31 | } 32 | 33 | } // namespace 34 | 35 | Image::Image(int fd) { 36 | struct stat st; 37 | if (auto rc = ::fstat(fd, &st); rc == -1) { 38 | this->valid = false; 39 | return; 40 | } 41 | 42 | this->data = std::make_shared>(st.st_size); 43 | if (auto rc = ::read(fd, this->data->data(), this->data->size()); rc == -1) { 44 | this->valid = false; 45 | return; 46 | } 47 | } 48 | 49 | JpegSegmentHeader Image::find_next_segment(Bitstream &bs) { 50 | JpegSegmentHeader hdr; 51 | do 52 | hdr.magic = bs.get(); 53 | while ((hdr.magic != JpegMarker::Magic) && !bs.empty()); 54 | 55 | hdr.marker = bs.get(); 56 | hdr.size = bs.get_be(); 57 | return hdr; 58 | } 59 | 60 | int Image::parse_app(JpegSegmentHeader seg, Bitstream &bs) { 61 | skip_segment(seg, bs); 62 | return 0; 63 | } 64 | 65 | int Image::parse_sof(JpegSegmentHeader seg, Bitstream &bs) { 66 | if (seg.size < 11) 67 | return ENODATA; 68 | 69 | this->progressive = seg.marker == JpegMarker::Sof2; 70 | 71 | this->sampling_precision = bs.get(); 72 | 73 | this->height = bs.get_be(); 74 | this->width = bs.get_be(); 75 | 76 | this->num_components = bs.get(); 77 | if (this->num_components > 3) 78 | return EINVAL; 79 | 80 | std::uint8_t max_samp_h = 0, max_samp_v = 0; 81 | for (std::size_t i = 0; i < this->num_components; ++i) { 82 | auto id = bs.get(); 83 | if (id >= this->components.size()) 84 | return EINVAL; 85 | 86 | this->comp_idx[i] = id; 87 | 88 | auto sampling = bs.get(); 89 | this->components[id].sampling_vert = sampling >> 0 & mask(4u); 90 | this->components[id].sampling_horiz = sampling >> 4 & mask(4u); 91 | 92 | this->components[id].quant_table_id = bs.get(); 93 | 94 | max_samp_h = std::max(max_samp_h, this->components[id].sampling_horiz); 95 | max_samp_v = std::max(max_samp_v, this->components[id].sampling_vert); 96 | } 97 | 98 | this->mcu_size_horiz = 8 * max_samp_h; 99 | this->mcu_size_vert = 8 * max_samp_v; 100 | 101 | if (this->num_components == 3) { 102 | auto id = this->comp_idx[0]; 103 | if ((this->components[id].sampling_vert == 2) && (this->components[id].sampling_horiz == 2)) 104 | this->sampling = SamplingFormat::S420; 105 | if ((this->components[id].sampling_vert == 2) && (this->components[id].sampling_horiz != 2)) 106 | this->sampling = SamplingFormat::S440; 107 | if ((this->components[id].sampling_vert != 2) && (this->components[id].sampling_horiz == 2)) 108 | this->sampling = SamplingFormat::S422; 109 | if ((this->components[id].sampling_vert != 2) && (this->components[id].sampling_horiz != 2)) 110 | this->sampling = SamplingFormat::S444; 111 | } else { 112 | this->sampling = SamplingFormat::Monochrome; 113 | } 114 | 115 | return 0; 116 | } 117 | 118 | int Image::parse_dri(JpegSegmentHeader seg, Bitstream &bs) { 119 | if (seg.size != 4) 120 | return ENODATA; 121 | 122 | this->restart_interval = bs.get_be(); 123 | return 0; 124 | } 125 | 126 | int Image::parse_dqt(JpegSegmentHeader seg, Bitstream &bs) { 127 | if (seg.size < 67) 128 | return ENODATA; 129 | 130 | auto start = bs.current(); 131 | while (bs.current() - start < seg.size - 65) { 132 | auto info = bs.get(); 133 | 134 | auto id = info >> 0 & mask(4u); 135 | auto precision = info >> 8 & mask(4u); 136 | 137 | this->quant_mask |= bit(static_cast(id)); 138 | 139 | if (precision == 0) 140 | for (auto i = 0; i < 0x40; ++i) // 8-bit precision 141 | this->quant_tables[id].table[i] = bs.get(); 142 | else 143 | for (auto i = 0; i < 0x40; ++i) // 16-bit precision 144 | // Discard high byte 145 | this->quant_tables[id].table[i] = bs.get(), bs.get(); 146 | } 147 | 148 | return 0; 149 | } 150 | 151 | int Image::parse_dht(JpegSegmentHeader seg, Bitstream &bs) { 152 | if (seg.size < 18) 153 | return ENODATA; 154 | 155 | auto start = bs.current(); 156 | while (bs.current() - start < seg.size - 16) { 157 | auto info = bs.get(); 158 | 159 | auto id = info >> 0 & mask(4u); 160 | auto type = info >> 4 & mask(1u); 161 | 162 | HuffmanTable *table; 163 | if (type == 0) { 164 | this->hm_ac_mask |= bit(static_cast(id)); 165 | table = &this->hm_ac_tables[id]; 166 | } else { 167 | this->hm_dc_mask |= bit(static_cast(id)); 168 | table = &this->hm_dc_tables[id]; 169 | } 170 | 171 | int num_symbols = 0; 172 | for (auto i = 0; i < 16; ++i) 173 | num_symbols += table->codes[i] = bs.get(); 174 | for (auto i = 0; i < num_symbols; ++i) 175 | table->symbols[i] = bs.get(); 176 | } 177 | 178 | return 0; 179 | } 180 | 181 | int Image::parse_sos(JpegSegmentHeader seg, Bitstream &bs) { 182 | if (seg.size < 8) 183 | return ENODATA; 184 | 185 | auto num_comps = bs.get(); 186 | if (num_comps != this->num_components) 187 | return EINVAL; 188 | 189 | for (std::size_t i = 0; i < num_comps; ++i) { 190 | auto id = bs.get(); 191 | auto info = bs.get(); 192 | if (id >= this->components.size()) 193 | return EINVAL; 194 | 195 | this->components[id].hm_ac_table_id = info >> 0 & mask(4u); 196 | this->components[id].hm_dc_table_id = info >> 4 & mask(4u); 197 | } 198 | 199 | this->spectral_selection_lo = bs.get(); 200 | this->spectral_selection_hi = bs.get(); 201 | 202 | bs.skip(1); 203 | 204 | return 0; 205 | } 206 | 207 | int Image::parse() { 208 | if (!this->valid || !this->data) 209 | return EINVAL; 210 | 211 | auto bs = Bitstream(*this->data); 212 | 213 | // Find SOI 214 | JpegSegmentHeader seg; 215 | do 216 | seg = find_next_segment(bs); 217 | while (!bs.empty() && (seg.marker != JpegMarker::Soi)); 218 | bs.rewind(sizeof(seg.size)); 219 | 220 | while (!bs.empty()) { 221 | seg = find_next_segment(bs); 222 | if (bs.empty()) 223 | return ENODATA; 224 | 225 | switch (seg.marker) { 226 | case JpegMarker::Soi: 227 | bs.rewind(sizeof(seg.size)); 228 | return EINVAL; 229 | 230 | case JpegMarker::App0 ... JpegMarker::App15: 231 | NJ_TRY_RET(this->parse_app(seg, bs)); 232 | break; 233 | 234 | case JpegMarker::Sof0 ... JpegMarker::Sof2: 235 | NJ_TRY_RET(this->parse_sof(seg, bs)); 236 | break; 237 | 238 | case JpegMarker::Dqt: 239 | NJ_TRY_RET(this->parse_dqt(seg, bs)); 240 | break; 241 | 242 | case JpegMarker::Dht: 243 | NJ_TRY_RET(this->parse_dht(seg, bs)); 244 | break; 245 | 246 | case JpegMarker::Dri: 247 | NJ_TRY_RET(this->parse_dri(seg, bs)); 248 | break; 249 | 250 | case JpegMarker::Sos: 251 | NJ_TRY_RET(this->parse_sos(seg, bs)); 252 | this->scan_offset = bs.current() - this->data->begin(); 253 | return 0; 254 | 255 | case JpegMarker::Eoi: 256 | bs.rewind(sizeof(seg.size)); 257 | return ENODATA; 258 | 259 | default: 260 | skip_segment(seg, bs); 261 | break; 262 | } 263 | } 264 | 265 | return ENODATA; 266 | } 267 | 268 | } // namespace nj 269 | -------------------------------------------------------------------------------- /lib/decoder.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2021 averne 2 | // 3 | // This file is part of oss-nvjpg. 4 | // 5 | // oss-nvjpg is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // oss-nvjpg is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with oss-nvjpg. If not, see . 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | #include 32 | 33 | namespace nj { 34 | 35 | namespace { 36 | 37 | constexpr std::uint32_t float_to_fixed(float f) { 38 | return static_cast(f * 65536.0f + 0.5f); 39 | } 40 | 41 | constinit std::array kernel_bt601 = { 42 | float_to_fixed( 1.164f), 43 | float_to_fixed( 1.596f), float_to_fixed(-0.391f), 44 | float_to_fixed(-0.813f), float_to_fixed( 2.018f), 45 | 16u, 46 | }; 47 | 48 | constinit std::array kernel_bt709 = { 49 | float_to_fixed( 1.164f), 50 | float_to_fixed( 1.793f), float_to_fixed(-0.213f), 51 | float_to_fixed(-0.534f), float_to_fixed( 2.115f), 52 | 16u, 53 | }; 54 | 55 | constinit std::array kernel_bt601ex = { 56 | float_to_fixed( 1.000f ), 57 | float_to_fixed( 1.402f ), float_to_fixed(-0.34416f), 58 | float_to_fixed(-0.71415f), float_to_fixed( 1.772f ), 59 | 0u, 60 | }; 61 | 62 | } // namespace 63 | 64 | Result Decoder::initialize(std::size_t num_ring_entries, std::size_t capacity) { 65 | this->entries.resize(num_ring_entries); 66 | 67 | for (auto &entry: this->entries) { 68 | NJ_TRY_RET(entry.cmdbuf_map .allocate(0x8000, 32, 0x1)); 69 | NJ_TRY_RET(entry.pic_info_map .allocate(sizeof(NvjpgPictureInfo), 16, 0x1)); 70 | NJ_TRY_RET(entry.read_data_map.allocate(sizeof(NvjpgStatus), 16, 0x1)); 71 | NJ_TRY_RET(entry.scan_data_map.allocate(capacity, 0x1000, 0x1)); 72 | } 73 | 74 | #ifdef __SWITCH__ 75 | NJ_TRY_RET(this->channel.open("/dev/nvhost-nvjpg")); 76 | 77 | for (auto &entry: this->entries) { 78 | NJ_TRY_RET(entry.cmdbuf_map .map(this->channel.get_fd())); 79 | NJ_TRY_RET(entry.pic_info_map .map(this->channel.get_fd())); 80 | NJ_TRY_RET(entry.read_data_map.map(this->channel.get_fd())); 81 | NJ_TRY_RET(entry.scan_data_map.map(this->channel.get_fd())); 82 | } 83 | 84 | NJ_TRY_RET(mmuRequestInitialize(&this->request, MmuModuleId_Nvjpg, 8, false)); 85 | #else 86 | NJ_TRY_ERRNO(this->channel.open("/dev/nvhost-nvjpg")); 87 | 88 | for (auto &entry: this->entries) { 89 | NJ_TRY_ERRNO(entry.cmdbuf_map .map()); 90 | NJ_TRY_ERRNO(entry.pic_info_map .map()); 91 | NJ_TRY_ERRNO(entry.read_data_map.map()); 92 | NJ_TRY_ERRNO(entry.scan_data_map.map()); 93 | } 94 | #endif 95 | 96 | this->next_entry = this->entries.begin(); 97 | 98 | return 0; 99 | } 100 | 101 | Result Decoder::finalize() { 102 | for (auto &entry: this->entries) { 103 | NJ_TRY_RET(entry.cmdbuf_map .free()); 104 | NJ_TRY_RET(entry.pic_info_map .free()); 105 | NJ_TRY_RET(entry.read_data_map.free()); 106 | NJ_TRY_RET(entry.scan_data_map.free()); 107 | } 108 | 109 | #ifdef __SWITCH__ 110 | NJ_TRY_RET(this->channel.close()); 111 | 112 | NJ_TRY_RET(mmuRequestFinalize(&this->request)); 113 | #else 114 | NJ_TRY_ERRNO(this->channel.close()); 115 | #endif 116 | 117 | return 0; 118 | } 119 | 120 | Result Decoder::resize(std::size_t capacity) { 121 | for (auto &entry: this->entries) { 122 | NJ_TRY_RET(entry.scan_data_map.free()); 123 | NJ_TRY_RET(entry.scan_data_map.allocate(capacity, 0x1000, 0x1)); 124 | 125 | #ifdef __SWITCH__ 126 | NJ_TRY_RET(entry.scan_data_map.map(this->channel.get_fd())); 127 | #else 128 | NJ_TRY_ERRNO(entry.scan_data_map.map()); 129 | #endif 130 | } 131 | 132 | return 0; 133 | } 134 | 135 | Decoder::RingEntry &Decoder::get_ring_entry() const { 136 | auto &entry = *this->next_entry; 137 | 138 | if (entry.fence.value != -1u) 139 | NvHostCtrl::wait(entry.fence, -1); 140 | 141 | return entry; 142 | } 143 | 144 | NvjpgPictureInfo *Decoder::build_picture_info_common(RingEntry &entry, const Image &image, std::uint32_t downscale) { 145 | auto *info = static_cast(entry.pic_info_map.address()); 146 | std::memset(info, 0, sizeof(NvjpgPictureInfo)); 147 | 148 | if (downscale) 149 | downscale = std::clamp(__builtin_ctz(downscale), 0, 3); 150 | 151 | for (std::size_t i = 0; i < image.hm_ac_tables.size(); ++i) { 152 | if (!(image.hm_ac_mask & bit(i))) 153 | continue; 154 | 155 | info->hm_ac_tables[i].codes = image.hm_ac_tables[i].codes; 156 | info->hm_ac_tables[i].symbols = image.hm_ac_tables[i].symbols; 157 | } 158 | 159 | for (std::size_t i = 0; i < image.hm_dc_tables.size(); ++i) { 160 | if (!(image.hm_dc_mask & bit(i))) 161 | continue; 162 | 163 | info->hm_dc_tables[i].codes = image.hm_dc_tables[i].codes; 164 | info->hm_dc_tables[i].symbols = image.hm_dc_tables[i].symbols; 165 | } 166 | 167 | for (std::size_t i = 0; i < image.quant_tables.size(); ++i) { 168 | if (!(image.quant_mask & bit(i))) 169 | continue; 170 | 171 | info->quant_tables[i].table = image.quant_tables[i].table; 172 | } 173 | 174 | for (std::size_t i = 0; i < image.num_components; ++i) { 175 | auto id = image.comp_idx[i]; 176 | info->components[i].sampling_horiz = image.components[id].sampling_horiz; 177 | info->components[i].sampling_vert = image.components[id].sampling_vert; 178 | info->components[i].quant_table_id = image.components[id].quant_table_id; 179 | info->components[i].hm_ac_table_id = image.components[id].hm_ac_table_id; 180 | info->components[i].hm_dc_table_id = image.components[id].hm_dc_table_id; 181 | } 182 | 183 | info->restart_interval = image.restart_interval; 184 | info->width = image.width; 185 | info->height = image.height; 186 | info->num_mcu_h = (image.width + image.mcu_size_horiz - 1) / image.mcu_size_horiz; 187 | info->num_mcu_v = (image.height + image.mcu_size_vert - 1) / image.mcu_size_vert; 188 | info->num_components = image.num_components; 189 | info->scan_data_offset = 0; 190 | info->scan_data_size = image.get_scan_data().size(); 191 | info->scan_data_samp_layout = static_cast(image.sampling); 192 | info->alpha = 0; 193 | info->downscale_log_2 = downscale; 194 | 195 | return info; 196 | } 197 | 198 | Result Decoder::render_common(RingEntry &entry, const Image &image, SurfaceBase &surf) { 199 | if (image.progressive) 200 | return EINVAL; 201 | 202 | if (image.width == 0 || image.height == 0) 203 | return EINVAL; 204 | 205 | if (image.num_components == 1 && (image.components[0].sampling_horiz != 1 || image.components[0].sampling_vert != 1)) 206 | return EINVAL; 207 | 208 | auto scan_data = image.get_scan_data(); 209 | 210 | if (scan_data.size() > entry.scan_data_map.size()) 211 | return ENOMEM; 212 | 213 | std::copy_n(scan_data.begin(), std::min(scan_data.size(), entry.scan_data_map.size()), 214 | static_cast(entry.scan_data_map.address())); 215 | 216 | // Add syncpt increment to signal the end of the processing of our commands 217 | entry.cmdbuf.begin(Decoder::class_id); 218 | entry.cmdbuf.push_raw(OpcodeNonIncr(NJ_REGPOS(ThiRegisters, incr_syncpt), 1)); 219 | entry.cmdbuf.push_raw(this->channel.get_syncpt() | (true << 8)); // Condition: 0 = immediate, 1 = when done 220 | entry.cmdbuf.end(); 221 | 222 | std::array incrs = { 223 | nvhost_syncpt_incr{ 224 | .syncpt_id = this->channel.get_syncpt(), 225 | .syncpt_incrs = 1, 226 | }, 227 | }; 228 | 229 | auto render_fence = nvhost_ctrl_fence{ 230 | .id = this->channel.get_syncpt(), 231 | .value = 0, 232 | }; 233 | 234 | #ifdef __SWITCH__ 235 | NJ_TRY_RET(this->channel.submit(entry.cmdbuf.get_bufs(), {}, {}, incrs, std::span(&render_fence, 1))); 236 | #else 237 | std::array fences = { 238 | 0u, 239 | }; 240 | 241 | auto &&[cmdbufs, exts, class_ids] = entry.cmdbuf.get_bufs(); 242 | auto &&[relocs, shifts, types] = entry.cmdbuf.get_relocs(); 243 | 244 | NJ_TRY_RET(this->channel.submit(cmdbufs, exts, class_ids, relocs, shifts, types, incrs, fences, render_fence)); 245 | #endif 246 | 247 | entry.fence = surf.render_fence = render_fence; 248 | 249 | if (++this->next_entry == this->entries.end()) 250 | this->next_entry = this->entries.begin(); 251 | 252 | return 0; 253 | } 254 | 255 | Result Decoder::render(const Image &image, Surface &surf, std::uint8_t alpha, std::uint32_t downscale) { 256 | #ifdef __SWITCH__ 257 | if (!surf.map.iova()) 258 | NJ_TRY_RET(surf.map.map(this->channel.get_fd())); 259 | #endif 260 | 261 | if (surf.width == 0 || surf.height == 0) 262 | return EINVAL; 263 | 264 | auto &entry = this->get_ring_entry(); 265 | 266 | auto *info = this->build_picture_info_common(entry, image, downscale); 267 | info->out_data_samp_layout = static_cast(image.sampling); 268 | info->out_surf_type = static_cast(surf.type); 269 | info->out_luma_surf_pitch = surf.pitch; 270 | info->out_chroma_surf_pitch = 0; 271 | info->alpha = alpha; 272 | info->memory_mode = static_cast(surf.get_memory_mode()); 273 | 274 | switch (this->colorspace) { 275 | case ColorSpace::BT601: 276 | info->yuv2rgb_kernel = kernel_bt601; 277 | break; 278 | case ColorSpace::BT709: 279 | info->yuv2rgb_kernel = kernel_bt709; 280 | break; 281 | case ColorSpace::BT601Ex: 282 | default: 283 | info->yuv2rgb_kernel = kernel_bt601ex; 284 | break; 285 | } 286 | 287 | entry.cmdbuf.clear(); 288 | entry.cmdbuf.begin(Decoder::class_id); 289 | entry.cmdbuf.push_value(NJ_REGPOS(NvjpgRegisters, operation_type), 1); 290 | entry.cmdbuf.push_reloc(NJ_REGPOS(NvjpgRegisters, picture_info_offset), entry.pic_info_map); 291 | entry.cmdbuf.push_reloc(NJ_REGPOS(NvjpgRegisters, read_info_offset), entry.read_data_map); 292 | entry.cmdbuf.push_reloc(NJ_REGPOS(NvjpgRegisters, scan_data_offset), entry.scan_data_map); 293 | entry.cmdbuf.push_reloc(NJ_REGPOS(NvjpgRegisters, out_data_offset), surf.get_map()); 294 | entry.cmdbuf.push_value(NJ_REGPOS(NvjpgRegisters, execute), 0x100); 295 | entry.cmdbuf.end(); 296 | 297 | return this->render_common(entry, image, surf); 298 | } 299 | 300 | Result Decoder::render(const Image &image, VideoSurface &surf, std::uint32_t downscale) { 301 | #ifdef __SWITCH__ 302 | if (!surf.map.iova()) 303 | NJ_TRY_RET(surf.map.map(this->channel.get_fd())); 304 | #endif 305 | 306 | if (surf.width == 0 || surf.height == 0) 307 | return EINVAL; 308 | 309 | auto &entry = this->get_ring_entry(); 310 | 311 | auto sampling = (image.num_components == 1) ? SamplingFormat::Monochrome : surf.sampling; 312 | 313 | auto *info = this->build_picture_info_common(entry, image, downscale); 314 | info->out_data_samp_layout = static_cast(sampling); 315 | info->out_surf_type = static_cast(surf.type); 316 | info->out_luma_surf_pitch = surf.luma_pitch; 317 | info->out_chroma_surf_pitch = surf.chroma_pitch; 318 | info->memory_mode = static_cast(surf.get_memory_mode()); 319 | 320 | entry.cmdbuf.clear(); 321 | entry.cmdbuf.begin(Decoder::class_id); 322 | entry.cmdbuf.push_value(NJ_REGPOS(NvjpgRegisters, operation_type), 1); 323 | entry.cmdbuf.push_reloc(NJ_REGPOS(NvjpgRegisters, picture_info_offset), entry.pic_info_map); 324 | entry.cmdbuf.push_reloc(NJ_REGPOS(NvjpgRegisters, read_info_offset), entry.read_data_map); 325 | entry.cmdbuf.push_reloc(NJ_REGPOS(NvjpgRegisters, scan_data_offset), entry.scan_data_map); 326 | entry.cmdbuf.push_reloc(NJ_REGPOS(NvjpgRegisters, out_data_offset), surf.get_map(), 0); 327 | entry.cmdbuf.push_reloc(NJ_REGPOS(NvjpgRegisters, out_data_2_offset), surf.get_map(), surf.chromab_data - surf.data()); 328 | entry.cmdbuf.push_reloc(NJ_REGPOS(NvjpgRegisters, out_data_3_offset), surf.get_map(), surf.chromar_data - surf.data()); 329 | entry.cmdbuf.push_value(NJ_REGPOS(NvjpgRegisters, execute), 0x100); 330 | entry.cmdbuf.end(); 331 | 332 | return this->render_common(entry, image, surf); 333 | } 334 | 335 | Result Decoder::wait(const SurfaceBase &surf, std::size_t *num_read_bytes, std::int32_t timeout_us) { 336 | auto it = std::find_if(this->entries.begin(), this->entries.end(), 337 | [&surf](auto &entry) { 338 | return (entry.fence.id == surf.render_fence.id) && (entry.fence.value == surf.render_fence.value); 339 | } 340 | ); 341 | 342 | if (it == this->entries.end()) 343 | return 0; 344 | 345 | NJ_TRY_RET(NvHostCtrl::wait(it->fence, timeout_us)); 346 | if (num_read_bytes) 347 | *num_read_bytes = reinterpret_cast(it->read_data_map.address())->used_bytes; 348 | return 0; 349 | } 350 | 351 | } // namespace nj 352 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------