refactor jpegdec implementation into libstrat (thanks again, Behemoth!)

This commit is contained in:
Michael Scire 2020-04-20 04:37:08 -07:00
parent 90d754f920
commit 6eb77e69c4
23 changed files with 780 additions and 261 deletions

View file

@ -89,7 +89,7 @@ dist-no-debug: all
cp stratosphere/fatal/fatal.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000034/exefs.nsp
cp stratosphere/creport/creport.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000036/exefs.nsp
cp stratosphere/ro/ro.nsp atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/exefs.nsp
cp stratosphere/jpedec/jpedec.nsp atmosphere-$(AMSVER)/atmosphere/contents/010000000000003C/exefs.nsp
cp stratosphere/jpegdec/jpegdec.nsp atmosphere-$(AMSVER)/atmosphere/contents/010000000000003C/exefs.nsp
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/flags
touch atmosphere-$(AMSVER)/atmosphere/contents/0100000000000032/flags/boot2.flag
mkdir -p atmosphere-$(AMSVER)/atmosphere/contents/0100000000000037/flags

View file

@ -41,6 +41,7 @@
/* At this point, just include the rest alphabetically. */
/* TODO: Figure out optimal order. */
#include <stratosphere/boot2.hpp>
#include <stratosphere/capsrv.hpp>
#include <stratosphere/cfg.hpp>
#include <stratosphere/dmnt.hpp>
#include <stratosphere/erpt.hpp>

View file

@ -0,0 +1,21 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere/capsrv/capsrv_screen_shot_decode_option.hpp>
#include <stratosphere/capsrv/server/capsrv_server_config.hpp>
#include <stratosphere/capsrv/server/capsrv_server_decoder_api.hpp>

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2019-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <vapours.hpp>
namespace ams::capsrv {
enum ScreenShotDecoderFlag : u64 {
ScreenShotDecoderFlag_None = (0 << 0),
ScreenShotDecoderFlag_EnableFancyUpsampling = (1 << 0),
ScreenShotDecoderFlag_EnableBlockSmoothing = (1 << 1),
};
using ScreenShotJpegDecoderFlagType = typename std::underlying_type<ScreenShotDecoderFlag>::type;
struct ScreenShotDecodeOption {
ScreenShotJpegDecoderFlagType flags;
u8 reserved[0x20 - sizeof(ScreenShotJpegDecoderFlagType)];
static constexpr ScreenShotDecodeOption GetDefaultOption() {
return ScreenShotDecodeOption{};
}
constexpr bool HasJpegDecoderFlag(ScreenShotJpegDecoderFlagType flag) const {
return (this->flags & flag) != 0;
}
};
static_assert(sizeof(ScreenShotDecodeOption) == 0x20);
static_assert(sizeof(ScreenShotDecodeOption) == sizeof(::CapsScreenShotDecodeOption));
static_assert(std::is_pod<ScreenShotDecodeOption>::value);
}

View file

@ -0,0 +1,30 @@
/*
* Copyright (c) 2019-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <vapours.hpp>
namespace ams::capsrv::server {
constexpr inline int ScreenShotWidth = 1280;
constexpr inline int ScreenShotHeight = 720;
constexpr inline int MovieWidth = 1280;
constexpr inline int MovieHeight = 720;
constexpr inline size_t SoftwareJpegDecoderWorkMemorySize = 16_KB;
}

View file

@ -0,0 +1,27 @@
/*
* Copyright (c) 2019-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <vapours.hpp>
namespace ams::capsrv::server {
Result InitializeForDecoderServer();
void FinalizeForDecoderServer();
void DecoderControlServerThreadFunction(void *);
}

View file

@ -0,0 +1,64 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "decodersrv/decodersrv_decoder_server_object.hpp"
namespace ams::capsrv::server {
namespace {
bool g_initialized = false;
}
Result InitializeForDecoderServer() {
/* Ensure we initialize only once. */
AMS_ABORT_UNLESS(!g_initialized);
/* Clear work memory. */
std::memset(std::addressof(g_work_memory), 0, sizeof(g_work_memory));
/* Initialize the decoder server. */
R_ABORT_UNLESS(g_decoder_control_server_manager.Initialize());
/* Start the server. */
g_decoder_control_server_manager.StartServer();
/* We're initialized. */
g_initialized = true;
return ResultSuccess();
}
void FinalizeForDecoderServer() {
/* Ensure we don't finalize when uninitialized. */
AMS_ABORT_UNLESS(g_initialized);
/* Finalize the server. */
g_decoder_control_server_manager.Finalize();
/* Mark uninitialized. */
g_initialized = false;
}
void DecoderControlServerThreadFunction(void *) {
/* We need to be initialized. */
AMS_ABORT_UNLESS(g_initialized);
/* Run the server. */
g_decoder_control_server_manager.RunServer();
}
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "decodersrv_decoder_server_object.hpp"
namespace ams::capsrv::server {
Result DecoderControlServerManager::Initialize() {
/* Create the objects. */
this->service_holder.emplace();
this->server_manager_holder.emplace();
/* Register the service. */
R_ABORT_UNLESS(this->server_manager_holder->RegisterServer<Service>(ServiceName, MaxSessions, sf::ServiceObjectTraits<Service>::SharedPointerHelper::GetEmptyDeleteSharedPointer(std::addressof(*this->service_holder))));
/* Initialize the idle event, we're idle initially. */
os::InitializeEvent(std::addressof(this->idle_event), true, os::EventClearMode_ManualClear);
return ResultSuccess();
}
void DecoderControlServerManager::Finalize() {
/* Check that the server is idle. */
AMS_ASSERT(os::TryWaitEvent(std::addressof(this->idle_event)));
/* Destroy the server. */
os::FinalizeEvent(std::addressof(this->idle_event));
this->server_manager_holder = std::nullopt;
this->service_holder = std::nullopt;
}
void DecoderControlServerManager::StartServer() {
this->server_manager_holder->ResumeProcessing();
}
void DecoderControlServerManager::StopServer() {
/* Request the server stop, and wait until it does. */
this->server_manager_holder->RequestStopProcessing();
os::WaitEvent(std::addressof(this->idle_event));
}
void DecoderControlServerManager::RunServer() {
/* Ensure that we are allowed to run. */
AMS_ABORT_UNLESS(os::TryWaitEvent(std::addressof(this->idle_event)));
/* Clear the event. */
os::ClearEvent(std::addressof(this->idle_event));
/* Process forever. */
this->server_manager_holder->LoopProcess();
/* Signal that we're idle again. */
os::SignalEvent(std::addressof(this->idle_event));
}
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2019-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
#include "decodersrv_decoder_control_service.hpp"
namespace ams::capsrv::server {
class DecoderControlServerManager {
public:
/* NOTE: Nintendo only allows one session. */
static constexpr inline size_t NumServers = 1;
static constexpr inline size_t MaxSessions = 2;
static constexpr inline sm::ServiceName ServiceName = sm::ServiceName::Encode("caps:dc");
using Service = DecoderControlService;
using ServerOptions = sf::hipc::DefaultServerManagerOptions;
using ServerManager = sf::hipc::ServerManager<NumServers, ServerOptions, MaxSessions>;
private:
std::optional<Service> service_holder;
std::optional<ServerManager> server_manager_holder;
os::EventType idle_event;
public:
constexpr DecoderControlServerManager() : service_holder(), server_manager_holder(), idle_event{} { /* ... */ }
Result Initialize();
void Finalize();
void StartServer();
void StopServer();
void RunServer();
};
}

View file

@ -0,0 +1,81 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "decodersrv_decoder_server_object.hpp"
#include "../jpeg/decodersrv_software_jpeg_decoder.hpp"
namespace ams::capsrv::server {
namespace {
Result DecodeJpegImpl(void *dst, size_t dst_size, const void *src_jpeg, size_t src_jpeg_size, u32 width, u32 height, const ScreenShotDecodeOption &option, void *work, size_t work_size) {
/* Clear the work memory. */
std::memset(work, 0, work_size);
ON_SCOPE_EXIT { std::memset(work, 0, work_size); };
/* Clear the output memory. */
std::memset(dst, 0, dst_size);
auto clear_guard = SCOPE_GUARD { std::memset(dst, 0, dst_size); };
/* Validate parameters. */
R_UNLESS(util::IsAligned(width, 0x10), capsrv::ResultAlbumOutOfRange());
R_UNLESS(util::IsAligned(height, 0x4), capsrv::ResultAlbumOutOfRange());
R_UNLESS(dst != nullptr, capsrv::ResultAlbumReadBufferShortage());
R_UNLESS(dst_size >= 4 * width * height, capsrv::ResultAlbumReadBufferShortage());
R_UNLESS(src_jpeg != nullptr, capsrv::ResultAlbumInvalidFileData());
R_UNLESS(src_jpeg_size != 0, capsrv::ResultAlbumInvalidFileData());
/* Create the input. */
const jpeg::SoftwareJpegDecoderInput decode_input = {
.jpeg = src_jpeg,
.jpeg_size = src_jpeg_size,
.width = width,
.height = height,
.fancy_upsampling = option.HasJpegDecoderFlag(ScreenShotDecoderFlag_EnableFancyUpsampling),
.block_smoothing = option.HasJpegDecoderFlag(ScreenShotDecoderFlag_EnableBlockSmoothing),
};
/* Create the output. */
s32 out_width = 0, out_height = 0;
jpeg::SoftwareJpegDecoderOutput decode_output = {
.out_width = std::addressof(out_width),
.out_height = std::addressof(out_height),
.dst = dst,
.dst_size = dst_size,
};
/* Decode the jpeg. */
R_TRY(jpeg::SoftwareJpegDecoder::DecodeRgba8(decode_output, decode_input, work, work_size));
/* We succeeded, so we shouldn't clear the output memory. */
clear_guard.Cancel();
return ResultSuccess();
}
}
Result DecoderControlService::DecodeJpeg(const sf::OutNonSecureBuffer &out, const sf::InBuffer &in, u32 width, u32 height, const ScreenShotDecodeOption &option) {
/* Get the work buffer. */
void *work = g_work_memory.jpeg_decoder_memory;
size_t work_size = sizeof(g_work_memory.jpeg_decoder_memory);
/* Call the decoder implementation. */
return DecodeJpegImpl(out.GetPointer(), out.GetSize(), in.GetPointer(), in.GetSize(), width, height, option, work, work_size);
}
}

View file

@ -16,16 +16,16 @@
#pragma once
#include <stratosphere.hpp>
namespace ams::jpegdec {
namespace ams::capsrv::server {
class DecodeService final : public sf::IServiceObject {
class DecoderControlService final : public sf::IServiceObject {
protected:
enum class CommandId {
DecodeJpeg = 3001,
};
public:
/* Actual commands. */
virtual Result DecodeJpeg(const sf::OutNonSecureBuffer &out, const sf::InBuffer &in, u32 width, u32 height, const CapsScreenShotDecodeOption &opts);
virtual Result DecodeJpeg(const sf::OutNonSecureBuffer &out, const sf::InBuffer &in, u32 width, u32 height, const ScreenShotDecodeOption &option);
public:
DEFINE_SERVICE_DISPATCH_TABLE {
MAKE_SERVICE_COMMAND_META(DecodeJpeg)

View file

@ -0,0 +1,25 @@
/*
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "decodersrv_decoder_server_object.hpp"
namespace ams::capsrv::server {
/* Instantiate the decoder server globals in a single TU. */
DecoderWorkMemory g_work_memory;
DecoderControlServerManager g_decoder_control_server_manager;
}

View file

@ -0,0 +1,26 @@
/*
* Copyright (c) 2019-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
#include "decodersrv_decoder_work_memory.hpp"
#include "decodersrv_decoder_control_server_manager.hpp"
namespace ams::capsrv::server {
extern DecoderWorkMemory g_work_memory;
extern DecoderControlServerManager g_decoder_control_server_manager;
}

View file

@ -0,0 +1,28 @@
/*
* Copyright (c) 2019-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
namespace ams::capsrv::server {
struct DecoderWorkMemory {
alignas(os::MemoryPageSize) u8 jpeg_decoder_memory[SoftwareJpegDecoderWorkMemorySize];
};
static_assert(sizeof(DecoderWorkMemory) == SoftwareJpegDecoderWorkMemorySize);
static_assert(alignof(DecoderWorkMemory) == os::MemoryPageSize);
static_assert(std::is_pod<DecoderWorkMemory>::value);
}

View file

@ -0,0 +1,55 @@
/*
* Copyright (c) 2019-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
#include <csetjmp>
#include "capsrv_server_jpeg_library_types.hpp"
namespace ams::capsrv::server::jpeg {
struct JpegErrorHandler : public JpegLibraryType::jpeg_error_mgr {
public:
std::jmp_buf jmp_buf;
Result result;
public:
static void HandleError(JpegLibraryType::jpeg_common_struct *common) {
/* Retrieve the handler. */
JpegErrorHandler *handler = reinterpret_cast<JpegErrorHandler *>(common->err);
/* Set the result. */
handler->result = GetResult(handler->msg_code, handler->msg_parm.i[0]);
/* Return to the caller. */
longjmp(handler->jmp_buf, -1);
}
static Result GetResult(int msg_code, int msg_param) {
switch (msg_code) {
case JpegLibraryType::J_MESSAGE_CODE::JERR_BUFFER_SIZE:
case JpegLibraryType::J_MESSAGE_CODE::JERR_NO_BACKING_STORE:
case JpegLibraryType::J_MESSAGE_CODE::JERR_OUT_OF_MEMORY:
case JpegLibraryType::J_MESSAGE_CODE::JERR_TFILE_CREATE:
case JpegLibraryType::J_MESSAGE_CODE::JERR_TFILE_READ:
case JpegLibraryType::J_MESSAGE_CODE::JERR_TFILE_SEEK:
case JpegLibraryType::J_MESSAGE_CODE::JERR_TFILE_WRITE:
return capsrv::ResultInternalJpegWorkMemoryShortage();
default:
return capsrv::ResultInternalJpegEncoderError();
}
}
};
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 2019-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
#include <jpeglib.h>
#include <jerror.h>
namespace ams::capsrv::server::jpeg {
class JpegLibraryType {
public:
using jpeg_common_struct = ::jpeg_common_struct;
using jpeg_compress_struct = ::jpeg_compress_struct;
using jpeg_decompress_struct = ::jpeg_decompress_struct;
using jpeg_error_mgr = ::jpeg_error_mgr;
using jpeg_destination_mgr = ::jpeg_destination_mgr;
using j_common_ptr = ::j_common_ptr;
using j_compress_ptr = ::j_compress_ptr;
using boolean = ::boolean;
using JOCTET = ::JOCTET;
using JDIMENSION = ::JDIMENSION;
using JSAMPARRAY = ::JSAMPARRAY;
using JSAMPROW = ::JSAMPROW;
using J_COLOR_SPACE = ::J_COLOR_SPACE;
using J_DCT_METHOD = ::J_DCT_METHOD;
using J_MESSAGE_CODE = ::J_MESSAGE_CODE;
};
}

View file

@ -0,0 +1,185 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "decodersrv_software_jpeg_decoder.hpp"
#include "capsrv_server_jpeg_library_types.hpp"
#include "capsrv_server_jpeg_error_handler.hpp"
namespace ams::capsrv::server::jpeg {
#define CAPSRV_ABORT_UNLESS(expr) do { \
const bool __capsrv_assert_res = (expr); \
AMS_ASSERT(__capsrv_assert_res); \
AMS_ABORT_UNLESS(__capsrv_assert_res); \
} while (0)
#define CAPSRV_ASSERT(expr) do { \
const bool __capsrv_assert_res = (expr); \
AMS_ASSERT(__capsrv_assert_res); \
R_UNLESS(__capsrv_assert_res, capsrv::ResultAlbumError()); \
} while (0)
namespace {
constexpr s32 ImageSizeHorizonalUnit = 0x10;
constexpr s32 ImageSizeVerticalUnit = 0x4;
constexpr s32 RgbColorComponentCount = 3;
constexpr s32 RgbaColorComponentCount = 4;
Result GetRgbBufferSize(size_t *out_size, size_t *out_stride, s32 width, size_t work_size) {
/* Calculate the space we need and verify we have enough. */
const size_t rgb_width = util::AlignUp(static_cast<size_t>(width), ImageSizeHorizonalUnit);
const size_t rgb_stride = rgb_width * RgbColorComponentCount;
const size_t rgb_size = rgb_stride * ImageSizeVerticalUnit;
R_UNLESS(work_size >= rgb_size, capsrv::ResultInternalJpegWorkMemoryShortage());
/* Return the output to the caller. */
*out_size = rgb_size;
*out_stride = rgb_stride;
return ResultSuccess();
}
}
Result SoftwareJpegDecoder::DecodeRgba8(SoftwareJpegDecoderOutput &output, const SoftwareJpegDecoderInput &input, void *work, size_t work_size) {
CAPSRV_ABORT_UNLESS(util::IsAligned(input.width, ImageSizeHorizonalUnit));
CAPSRV_ABORT_UNLESS(util::IsAligned(input.height, ImageSizeVerticalUnit));
CAPSRV_ABORT_UNLESS(output.dst != nullptr);
CAPSRV_ABORT_UNLESS(output.dst_size >= static_cast<size_t>(RgbaColorComponentCount * input.width * input.height));
CAPSRV_ABORT_UNLESS(output.out_width != nullptr);
CAPSRV_ABORT_UNLESS(output.out_height != nullptr);
/* Determine work buffer extents. */
char *work_start = static_cast<char *>(work);
char *work_end = work_start + work_size;
/* Determine the buffer extents for our linebuffers. */
u8 *rgb_buffer = static_cast<u8 *>(static_cast<void *>(work_start));
size_t rgb_buffer_size;
size_t rgb_buffer_stride;
R_TRY(GetRgbBufferSize(std::addressof(rgb_buffer_size), std::addressof(rgb_buffer_stride), input.width, work_size));
/* The start of the workbuffer is reserved for linebuffer space. */
work_start += rgb_buffer_size;
/* Create our decompression structure. */
JpegLibraryType::jpeg_decompress_struct cinfo = {};
/* Here nintendo creates a work buffer structure containing work_start + work_size. */
/* This seems to be a custom patch for/to libjpeg-turbo. */
/* It would be desirable for us to mimic this, because it gives Nintendo strong */
/* fixed memory usage guarantees. */
/* TODO: Determine if it is feasible for us to recreate this ourselves, */
/* Either by adding support to the devkitPro libjpeg-turbo portlib or otherwise. */
AMS_UNUSED(work_end);
/* Create our error manager. */
JpegErrorHandler jerr = {
.result = ResultSuccess(),
};
jerr.error_exit = JpegErrorHandler::HandleError,
/* Link our error manager to our decompression structure. */
cinfo.err = jpeg_std_error(std::addressof(jerr));
/* Use setjmp, so that on error our handler will longjmp to return an error result. */
if (setjmp(jerr.jmp_buf) == 0) {
/* Create our decompressor. */
jpeg_create_decompress(std::addressof(cinfo));
ON_SCOPE_EXIT { jpeg_destroy_decompress(std::addressof(cinfo)); };
/* Setup our memory reader, ensure the header is correct. */
jpeg_mem_src(std::addressof(cinfo), const_cast<unsigned char *>(static_cast<const unsigned char *>(input.jpeg)), input.jpeg_size);
R_UNLESS(jpeg_read_header(std::addressof(cinfo), true) == JPEG_HEADER_OK, capsrv::ResultAlbumInvalidFileData());
/* Ensure width and height are correct. */
R_UNLESS(cinfo.image_width == input.width, capsrv::ResultAlbumInvalidFileData());
R_UNLESS(cinfo.image_height == input.height, capsrv::ResultAlbumInvalidFileData());
/* Set output parameters. */
cinfo.out_color_space = JpegLibraryType::J_COLOR_SPACE::JCS_RGB;
cinfo.dct_method = JpegLibraryType::J_DCT_METHOD::JDCT_ISLOW;
cinfo.do_fancy_upsampling = input.fancy_upsampling;
cinfo.do_block_smoothing = input.block_smoothing;
/* Start decompression. */
R_UNLESS(jpeg_start_decompress(&cinfo) == TRUE, capsrv::ResultAlbumInvalidFileData());
/* Check the parameters. */
CAPSRV_ASSERT(cinfo.output_width == input.width);
CAPSRV_ASSERT(cinfo.output_height == input.height);
CAPSRV_ASSERT(cinfo.out_color_components == RgbColorComponentCount);
CAPSRV_ASSERT(cinfo.output_components == RgbColorComponentCount);
/* Parse the scanlines. */
{
/* Convert our destination to a writable u8 buffer. */
u8 *dst = static_cast<u8 *>(output.dst);
/* Create our linebuffer structure. */
JpegLibraryType::JSAMPROW linebuffers[ImageSizeVerticalUnit] = {};
for (int i = 0; i < ImageSizeVerticalUnit; i++) {
linebuffers[i] = rgb_buffer + rgb_buffer_stride * i;
}
/* While we still have scanlines, parse! */
while (cinfo.output_scanline < input.height) {
/* Decode scanlines. */
int num_scanlines = jpeg_read_scanlines(std::addressof(cinfo), linebuffers, ImageSizeVerticalUnit);
CAPSRV_ASSERT(num_scanlines <= ImageSizeVerticalUnit);
/* Write out line by line. */
for (s32 i = 0; i < num_scanlines; i++) {
const u8 *src = linebuffers[i];
for (s32 j = 0; j < static_cast<s32>(input.width); j++) {
/* Write the output. */
/* First R, */
*(dst++) = *(src++);
/* Then G, */
*(dst++) = *(src++);
/* Then B, */
*(dst++) = *(src++);
/* Then A. */
*(dst++) = 0xFF;
}
}
}
}
/* Finish the decompression. */
R_UNLESS(jpeg_finish_decompress(&cinfo) == TRUE, capsrv::ResultAlbumInvalidFileData());
} else {
/* Some unknown error was caught by our handler. */
return capsrv::ResultAlbumInvalidFileData();
}
/* Write the size we decoded to output. */
*output.out_width = static_cast<s32>(cinfo.output_width);
*output.out_width = static_cast<s32>(cinfo.output_height);
return ResultSuccess();
}
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
* Copyright (c) 2019-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
@ -16,10 +16,10 @@
#pragma once
#include <stratosphere.hpp>
namespace ams::jpegdec::impl {
namespace ams::capsrv::server::jpeg {
struct DecodeInput {
const u8 *jpeg;
struct SoftwareJpegDecoderInput {
const void *jpeg;
size_t jpeg_size;
u32 width;
u32 height;
@ -27,17 +27,16 @@ namespace ams::jpegdec::impl {
bool block_smoothing;
};
struct DecodeOutput {
u32 *width;
u32 *height;
u8 *bmp;
size_t bmp_size;
struct SoftwareJpegDecoderOutput {
s32 *out_width;
s32 *out_height;
void *dst;
size_t dst_size;
};
struct Dimensions {
u32 width, height;
class SoftwareJpegDecoder {
public:
static Result DecodeRgba8(SoftwareJpegDecoderOutput &output, const SoftwareJpegDecoderInput &input, void *work, size_t work_size);
};
Result DecodeJpeg(DecodeOutput &out, const DecodeInput &in, u8 *work, size_t work_size);
}

View file

@ -52,6 +52,7 @@ namespace ams::capsrv {
R_DEFINE_ERROR_RESULT(NotSupported, 1023);
R_DEFINE_ERROR_RANGE(InternalError, 1024, 2047);
R_DEFINE_ERROR_RESULT(InternalJpegEncoderError, 1210);
R_DEFINE_ERROR_RESULT(InternalJpegWorkMemoryShortage, 1212);
R_DEFINE_ERROR_RANGE(InternalFileDataVerificationError, 1300, 1399);

View file

@ -1,4 +1,4 @@
MODULES := loader ncm pm sm boot ams_mitm spl eclct.stub ro creport fatal dmnt boot2 erpt jpegdec
MODULES := loader ncm pm sm boot ams_mitm spl eclct.stub ro creport fatal dmnt boot2 erpt pgl jpegdec
SUBFOLDERS := $(MODULES)

View file

@ -1,148 +0,0 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "jpegdec_turbo.hpp"
#include <jpeglib.h>
namespace ams::jpegdec::impl {
#define CAPSRV_ABORT_UNLESS(expr) do { \
const bool __capsrv_assert_res = (expr); \
AMS_ASSERT(__capsrv_assert_res); \
AMS_ABORT_UNLESS(__capsrv_assert_res); \
} while (0)
#define CAPSRV_ASSERT(expr) do { \
const bool __capsrv_assert_res = (expr); \
AMS_ASSERT(__capsrv_assert_res); \
R_UNLESS(__capsrv_assert_res, capsrv::ResultAlbumError()); \
} while (0)
namespace {
constexpr size_t LinebufferCount = 4;
constexpr size_t ColorComponents = 3;
constexpr int ImageSizeHorizonalUnit = 0x10;
constexpr int ImageSizeVerticalUnit = 0x4;
struct RGB {
u8 r, g, b;
};
struct RGBX {
u8 r, g, b, x;
};
void JpegErrorExit(j_common_ptr cinfo) {
/* ? */
}
}
Result DecodeJpeg(DecodeOutput &out, const DecodeInput &in, u8 *work, size_t work_size) {
CAPSRV_ABORT_UNLESS(util::IsAligned(in.width, ImageSizeHorizonalUnit));
CAPSRV_ABORT_UNLESS(util::IsAligned(in.height, ImageSizeVerticalUnit));
CAPSRV_ABORT_UNLESS(out.bmp != nullptr);
CAPSRV_ABORT_UNLESS(out.bmp_size >= 4 * in.width * in.height);
CAPSRV_ABORT_UNLESS(out.width != nullptr);
CAPSRV_ABORT_UNLESS(out.height != nullptr);
const size_t linebuffer_size = ColorComponents * in.width;
const size_t total_linebuffer_size = LinebufferCount * linebuffer_size;
R_UNLESS(work_size >= total_linebuffer_size, capsrv::ResultInternalJpegWorkMemoryShortage());
jpeg_decompress_struct cinfo;
std::memset(&cinfo, 0, sizeof(cinfo));
jpeg_error_mgr jerr;
std::memset(&jerr, 0, sizeof(jerr));
cinfo.err = jpeg_std_error(&jerr);
jerr.error_exit = JpegErrorExit;
/* TODO: Here Nintendo uses setjmp, on longjmp to error ResultAlbumInvalidFileData is returned. */
jpeg_create_decompress(&cinfo);
ON_SCOPE_EXIT {
jpeg_destroy_decompress(&cinfo);
};
jpeg_mem_src(&cinfo, in.jpeg, in.jpeg_size);
R_UNLESS(jpeg_read_header(&cinfo, true) == JPEG_HEADER_OK, capsrv::ResultAlbumInvalidFileData());
R_UNLESS(cinfo.image_width == in.width, capsrv::ResultAlbumInvalidFileData());
R_UNLESS(cinfo.image_height == in.height, capsrv::ResultAlbumInvalidFileData());
cinfo.out_color_space = JCS_RGB;
cinfo.dct_method = JDCT_ISLOW;
cinfo.do_fancy_upsampling = in.fancy_upsampling;
cinfo.do_block_smoothing = in.block_smoothing;
R_UNLESS(jpeg_start_decompress(&cinfo) == TRUE, capsrv::ResultAlbumInvalidFileData());
CAPSRV_ASSERT(cinfo.output_width == in.width);
CAPSRV_ASSERT(cinfo.output_height == in.height);
CAPSRV_ASSERT(cinfo.out_color_components == ColorComponents);
CAPSRV_ASSERT(cinfo.output_components == ColorComponents);
/* Pointer to output. */
RGBX *bmp = reinterpret_cast<RGBX *>(out.bmp);
/* Decode 4 lines at once. */
u8 *linebuffer[4] = {
work + 0 * linebuffer_size,
work + 1 * linebuffer_size,
work + 2 * linebuffer_size,
work + 3 * linebuffer_size,
};
/* While we still have scanlines, parse! */
while (cinfo.output_scanline < cinfo.output_height) {
/* Decode scanlines. */
int parsed = jpeg_read_scanlines(&cinfo, linebuffer, 4);
CAPSRV_ASSERT(parsed <= ImageSizeVerticalUnit);
/* Line by line */
for (int index = 0; index < parsed; index++) {
u8 *buffer = linebuffer[index];
const RGB* rgb = reinterpret_cast<RGB *>(buffer);
for (u32 i = 0; i < in.width; i++) {
/* Fill output. */
bmp->r = rgb->r;
bmp->g = rgb->g;
bmp->b = rgb->b;
bmp->x = 0xFF;
/* Traverse buffer. */
bmp++;
rgb++;
}
}
}
R_UNLESS(jpeg_finish_decompress(&cinfo) == TRUE, capsrv::ResultAlbumInvalidFileData());
*out.width = cinfo.output_width;
*out.height = cinfo.output_height;
return ResultSuccess();
}
}

View file

@ -1,79 +0,0 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "jpegdec_decode_service.hpp"
#include "impl/jpegdec_turbo.hpp"
namespace ams::jpegdec {
namespace {
/* Enough for four linebuffers RGB. */
u8 g_workmem[0x3C00];
}
Result DecodeService::DecodeJpeg(const sf::OutNonSecureBuffer &out, const sf::InBuffer &in, u32 width, u32 height, const CapsScreenShotDecodeOption &opts) {
u8 *bmp = out.GetPointer();
size_t bmp_size = out.GetSize();
const u8 *jpeg = in.GetPointer();
size_t jpeg_size = in.GetSize();
/* Clear the work memory and out buffer. */
std::memset(g_workmem, 0, sizeof(g_workmem));
std::memset(bmp, 0, bmp_size);
/* Clear output memory on decode failure. */
auto clear_guard = SCOPE_GUARD { std::memset(bmp, 0, bmp_size); };
R_UNLESS(util::IsAligned(width, 0x10), capsrv::ResultAlbumOutOfRange());
R_UNLESS(util::IsAligned(height, 0x4), capsrv::ResultAlbumOutOfRange());
R_UNLESS(bmp != nullptr, capsrv::ResultAlbumReadBufferShortage());
R_UNLESS(bmp_size >= 4 * width * height, capsrv::ResultAlbumReadBufferShortage());
R_UNLESS(jpeg != nullptr, capsrv::ResultAlbumInvalidFileData());
R_UNLESS(jpeg_size != 0, capsrv::ResultAlbumInvalidFileData());
impl::DecodeInput decode_input = {
.jpeg = jpeg,
.jpeg_size = jpeg_size,
.width = width,
.height = height,
.fancy_upsampling = bool(opts.fancy_upsampling),
.block_smoothing = bool(opts.block_smoothing),
};
/* Official software ignores output written to this struct. */
impl::Dimensions dims = {};
impl::DecodeOutput decode_output = {
.width = &dims.width,
.height = &dims.height,
.bmp = bmp,
.bmp_size = bmp_size,
};
/* Decode the jpeg. */
R_TRY(impl::DecodeJpeg(decode_output, decode_input, g_workmem, sizeof(g_workmem)));
clear_guard.Cancel();
/* Clear the work memory. */
std::memset(g_workmem, 0, sizeof(g_workmem));
return ResultSuccess();
}
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018-2019 Atmosphère-NX
* Copyright (c) 2018-2020 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
@ -13,7 +13,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "jpegdec_decode_service.hpp"
#include <stratosphere.hpp>
extern "C" {
extern u32 __start__;
@ -72,16 +72,6 @@ void __appExit(void) {
/* ... */
}
namespace {
constexpr size_t NumServers = 1;
sf::hipc::ServerManager<NumServers> g_server_manager;
/* NOTE: Official code only allows for one session. */
constexpr sm::ServiceName DecodeServiceName = sm::ServiceName::Encode("caps:dc");
constexpr size_t DecodeMaxSessions = 2;
}
int main(int argc, char **argv)
{
/* Set thread name. */
@ -92,11 +82,14 @@ int main(int argc, char **argv)
os::ChangeThreadPriority(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_PRIORITY(jpegdec, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(jpegdec, Main));
/* Create service. */
R_ASSERT(g_server_manager.RegisterServer<jpegdec::DecodeService>(DecodeServiceName, DecodeMaxSessions));
/* Initialize the capsrv library. */
R_ABORT_UNLESS(capsrv::server::InitializeForDecoderServer());
/* Loop forever, servicing our services. */
g_server_manager.LoopProcess();
/* Service the decoder server. */
capsrv::server::DecoderControlServerThreadFunction(nullptr);
/* Finalize the capsrv library. */
capsrv::server::FinalizeForDecoderServer();
/* Cleanup */
return 0;