Init mpv-joc

This commit is contained in:
TheM14 committed 2026-10-18 21:31:38 +08:00
commit 126e2cd233
52 files changed
+11035

No files matched your search

+544
View File
@@ -0,0 +1,544 @@
#include "container_scan.h"
#include <windows.h>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <vector>
#include "log.h"
#include "win_path.h"
namespace joc_container {
namespace {
// A library scan probes every container in the library, and most of them are
// declined; they also mostly share a directory, so the path would spend the log's
// byte budget repeating the same prefix once per file. The file name is what
// identifies the line. Files this component claims are logged with their full
// path by the caller.
std::string file_name_of(const std::string& path) {
const std::string::size_type slash = path.find_last_of("\\/");
return (slash == std::string::npos) ? path : path.substr(slash + 1);
}
// A bounded, read-only view of the file. Every accessor returns false instead of
// throwing, so a truncated or hostile file simply fails the probe.
class Window {
public:
bool open(const std::string& path) {
const std::wstring wide = joc_path::to_wide_extended(path);
handle_ = CreateFileW(wide.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (handle_ == INVALID_HANDLE_VALUE) {
handle_ = nullptr;
return false;
}
LARGE_INTEGER size{};
if (GetFileSizeEx(handle_, &size) == FALSE) return false;
size_ = static_cast<std::uint64_t>(size.QuadPart);
return true;
}
~Window() {
if (handle_ != nullptr) CloseHandle(handle_);
}
std::uint64_t size() const { return size_; }
// Reads at an absolute offset; false when the range is not fully available.
bool read(std::uint64_t offset, void* destination, std::size_t bytes) const {
if (offset + bytes > size_) return false;
LARGE_INTEGER position{};
position.QuadPart = static_cast<LONGLONG>(offset);
if (SetFilePointerEx(handle_, position, nullptr, FILE_BEGIN) == FALSE) return false;
std::size_t done = 0;
auto* target = static_cast<std::uint8_t*>(destination);
while (done < bytes) {
const DWORD chunk = static_cast<DWORD>(
(bytes - done) > 0x10000u ? 0x10000u : (bytes - done));
DWORD got = 0;
if (ReadFile(handle_, target + done, chunk, &got, nullptr) == FALSE || got == 0) {
return false;
}
done += got;
}
return true;
}
bool load(std::uint64_t offset, std::size_t bytes, std::vector<std::uint8_t>* out) const {
out->assign(bytes, 0);
return bytes == 0 || read(offset, out->data(), bytes);
}
private:
HANDLE handle_ = nullptr;
std::uint64_t size_ = 0;
};
// Set JOC_SCAN_TRACE=1 to have the walk printed: the practical way to see where a
// container's structure stops matching what the probe expects.
bool trace_enabled() {
static const bool enabled = [] {
return GetEnvironmentVariableA("JOC_SCAN_TRACE", nullptr, 0) != 0;
}();
return enabled;
}
void trace(const char* format, ...) {
if (!trace_enabled()) return;
va_list arguments;
va_start(arguments, format);
std::vfprintf(stdout, format, arguments);
va_end(arguments);
std::fflush(stdout);
}
std::uint32_t be32(const std::uint8_t* p) {
return (static_cast<std::uint32_t>(p[0]) << 24) | (static_cast<std::uint32_t>(p[1]) << 16) |
(static_cast<std::uint32_t>(p[2]) << 8) | static_cast<std::uint32_t>(p[3]);
}
std::string fourcc(const std::uint8_t* p) { return std::string(reinterpret_cast<const char*>(p), 4); }
bool is_audio_sample_entry(const std::string& format) {
// E-AC-3 is "ec-3"; "ac-3" is plain Dolby Digital and is *not* ours.
return format == "ec-3" || format == "ec3 " || format == "EAC3";
}
bool is_ac3_sample_entry(const std::string& format) { return format == "ac-3" || format == "ac3 "; }
// --- MP4 / ISO base media -------------------------------------------------
// Walks the boxes inside [begin, end) and hands each to the visitor.
template <typename Fn>
bool walk_boxes(const Window& file, std::uint64_t begin, std::uint64_t end,
std::size_t depth, Fn visitor) {
std::uint64_t offset = begin;
std::uint8_t header[8];
while (offset + 8 <= end) {
if (!file.read(offset, header, sizeof(header))) return false;
std::uint64_t size = be32(header);
const std::string type = fourcc(header + 4);
std::uint64_t payload = offset + 8;
if (size == 1) {
std::uint8_t extended[8];
if (!file.read(offset + 8, extended, sizeof(extended))) return false;
size = (static_cast<std::uint64_t>(be32(extended)) << 32) | be32(extended + 4);
payload = offset + 16;
} else if (size == 0) {
size = end - offset; // "to the end of the file"
}
trace("%*sbox %s size=%llu\n", static_cast<int>(depth) * 2, "", type.c_str(), static_cast<unsigned long long>(size));
if (size < 8 || offset + size > end) return false;
if (!visitor(type, payload, offset + size, depth)) return false;
offset += size;
}
return true;
}
// One trak: is it an audio track, and which sample entry does it use?
struct TrackInfo {
bool audio = false;
std::string format;
};
bool scan_stbl(const Window& file, std::uint64_t begin, std::uint64_t end, TrackInfo* info) {
return walk_boxes(file, begin, end, 0, [&](const std::string& type, std::uint64_t payload,
std::uint64_t box_end, std::size_t) {
(void)box_end;
if (type == "stsd") {
std::uint8_t head[16];
if (file.read(payload, head, sizeof(head))) {
// version+flags(4) entry_count(4), then the first sample entry:
// size(4) format(4).
info->format = fourcc(head + 12);
trace("%*sstsd format=%s\n", 8, "", info->format.c_str());
}
return false; // one sample entry is all the probe needs
}
return true;
});
}
// minf -> stbl -> stsd
bool scan_minf(const Window& file, std::uint64_t begin, std::uint64_t end, TrackInfo* info) {
return walk_boxes(file, begin, end, 0, [&](const std::string& type, std::uint64_t payload,
std::uint64_t box_end, std::size_t) {
if (type == "stbl") scan_stbl(file, payload, box_end, info);
return true;
});
}
// mdia: the track handler says whether this is audio, minf leads to the sample entry.
bool scan_mdia(const Window& file, std::uint64_t begin, std::uint64_t end, TrackInfo* info) {
return walk_boxes(file, begin, end, 0, [&](const std::string& type, std::uint64_t payload,
std::uint64_t box_end, std::size_t) {
if (type == "hdlr") {
std::uint8_t head[12];
if (file.read(payload, head, sizeof(head))) {
info->audio = fourcc(head + 8) == "soun";
trace("%*shdlr handler=%s audio=%d\n", 6, "", fourcc(head + 8).c_str(),
info->audio ? 1 : 0);
}
} else if (type == "minf") {
scan_minf(file, payload, box_end, info);
}
return true;
});
}
// trak -> mdia
bool scan_trak(const Window& file, std::uint64_t begin, std::uint64_t end, TrackInfo* info) {
return walk_boxes(file, begin, end, 0, [&](const std::string& type, std::uint64_t payload,
std::uint64_t box_end, std::size_t) {
if (type == "mdia") scan_mdia(file, payload, box_end, info);
return true;
});
}
Result scan_mp4(const Window& file, std::size_t max_bytes) {
Result result;
result.kind = Kind::kMp4;
// moov is usually at the start for streamed files and at the end otherwise. The
// walk reads box headers where they lie and steps over mdat in one go, so the
// whole file is walked from the top: a fixed prefix window cannot reach a moov
// that is larger than the window, which is what an MP4 with its cover art stored
// as a video track produces (a 4.9 MB moov against a 4 MiB window). The tail
// range stays as a fallback for a file whose leading boxes do not parse.
struct Range {
std::uint64_t begin;
std::uint64_t end;
};
std::vector<Range> ranges{{0, file.size()}};
if (file.size() > max_bytes) {
ranges.push_back({file.size() - max_bytes, file.size()});
}
// An oversized moov is a file this probe cannot describe, and walking it would be
// unbounded work; it is reported instead of entered.
constexpr std::uint64_t kMaxMoovBytes = 64ull * 1024ull * 1024ull;
bool oversized_moov = false;
unsigned audio_seen = 0;
bool found_any_audio = false;
std::string first_audio_format;
for (const Range& range : ranges) {
walk_boxes(file, range.begin, range.end, 0,
[&](const std::string& type, std::uint64_t payload, std::uint64_t box_end,
std::size_t) {
if (type != "moov") return true;
if (box_end - payload > kMaxMoovBytes) {
oversized_moov = true;
return true;
}
walk_boxes(file, payload, box_end, 1,
[&](const std::string& inner, std::uint64_t inner_payload,
std::uint64_t inner_end, std::size_t) {
if (inner == "mvhd") {
// version(1) flags(3) then either
// creation/modification/timescale/duration (32-bit)
// or the 64-bit variant.
std::uint8_t header[32];
if (file.read(inner_payload, header, sizeof(header))) {
const bool wide = header[0] == 1;
const std::uint32_t timescale =
wide ? be32(header + 20) : be32(header + 12);
const std::uint64_t duration =
wide ? ((static_cast<std::uint64_t>(
be32(header + 24))
<< 32) |
be32(header + 28))
: be32(header + 16);
if (timescale != 0) {
result.duration_seconds =
static_cast<double>(duration) /
static_cast<double>(timescale);
}
}
return true;
}
if (inner != "trak") return true;
TrackInfo info;
scan_trak(file, inner_payload, inner_end, &info);
if (!info.audio) return true;
if (!found_any_audio) {
found_any_audio = true;
first_audio_format = info.format;
}
if (is_audio_sample_entry(info.format)) {
result.eac3 = true;
result.audio_index = audio_seen;
result.codec = info.format;
} else if (is_ac3_sample_entry(info.format)) {
result.codec = info.format;
}
++audio_seen;
return !result.eac3; // stop once found
});
return !result.eac3;
});
if (result.eac3) break;
}
if (result.eac3) {
result.detail = "mp4: E-AC-3 audio track " + std::to_string(result.audio_index);
} else if (found_any_audio) {
result.detail = "mp4: first audio track is " +
(first_audio_format.empty() ? std::string("unknown")
: first_audio_format);
} else if (oversized_moov) {
result.detail = "mp4: moov is larger than the scan limit";
} else {
result.detail = "mp4: no audio track found in the scanned window";
}
return result;
}
// --- Matroska / WebM ------------------------------------------------------
struct EbmlReader {
const std::uint8_t* data = nullptr;
std::size_t size = 0;
std::size_t position = 0;
bool at_end() const { return position >= size; }
// Element IDs keep their leading bits; sizes drop the marker bit.
bool read_id(std::uint64_t* id) {
if (at_end()) return false;
const std::uint8_t first = data[position];
int length = 1;
for (int bit = 0x80; bit != 0; bit >>= 1, ++length) {
if ((first & bit) != 0) break;
}
if (length > 4 || position + static_cast<std::size_t>(length) > size) return false;
std::uint64_t value = 0;
for (int i = 0; i < length; ++i) value = (value << 8) | data[position + i];
position += static_cast<std::size_t>(length);
*id = value;
return true;
}
bool read_size(std::uint64_t* value, bool* unknown) {
*unknown = false;
if (at_end()) return false;
const std::uint8_t first = data[position];
int length = 1;
for (int bit = 0x80; bit != 0; bit >>= 1, ++length) {
if ((first & bit) != 0) break;
}
if (length > 8 || position + static_cast<std::size_t>(length) > size) return false;
std::uint64_t result = first & (0xFFu >> length);
bool all_ones = (first & (0xFFu >> length)) == (0xFFu >> length);
for (int i = 1; i < length; ++i) {
const std::uint8_t byte = data[position + i];
all_ones = all_ones && byte == 0xFFu;
result = (result << 8) | byte;
}
position += static_cast<std::size_t>(length);
*unknown = all_ones;
*value = result;
return true;
}
};
Result scan_matroska(const Window& file, std::size_t max_bytes) {
Result result;
result.kind = Kind::kMatroska;
std::vector<std::uint8_t> data;
if (!file.load(0, static_cast<std::size_t>(
(std::min<std::uint64_t>)(file.size(), max_bytes)),
&data)) {
result.detail = "matroska: cannot read the header";
return result;
}
unsigned audio_seen = 0;
std::string first_audio_codec;
bool saw_tracks = false;
bool found = false;
double timestamp_scale_ns = 1000000.0; // Matroska default: 1 ms per tick
double duration_ticks = 0.0;
// Only the two levels that matter are walked: Tracks, then TrackEntry.
auto walk = [&](std::size_t begin, std::size_t end, int depth,
auto&& self) -> void {
EbmlReader reader{data.data(), end, begin};
while (!reader.at_end() && !found) {
const std::size_t element_start = reader.position;
std::uint64_t id = 0;
std::uint64_t size = 0;
bool unknown = false;
if (!reader.read_id(&id) || !reader.read_size(&size, &unknown)) break;
std::size_t payload = reader.position;
std::size_t payload_end =
unknown ? end : (std::min<std::size_t>)(end, payload + static_cast<std::size_t>(size));
if (payload_end < payload) break;
switch (id) {
case 0x1654AE6Bu: // Tracks
saw_tracks = true;
self(payload, payload_end, depth + 1, self);
break;
case 0x1549A966u: { // Info: carries the segment duration
EbmlReader inner{data.data(), payload_end, payload};
while (!inner.at_end()) {
std::uint64_t child_id = 0;
std::uint64_t child_size = 0;
bool child_unknown = false;
if (!inner.read_id(&child_id) ||
!inner.read_size(&child_size, &child_unknown)) {
break;
}
const std::size_t child_payload = inner.position;
const std::size_t child_end =
child_unknown ? payload_end
: (std::min<std::size_t>)(
payload_end,
child_payload + static_cast<std::size_t>(child_size));
// TimestampScale (ns per tick, default 1 ms) and Duration (ticks).
if (child_id == 0x2AD7B1u && child_size >= 1 && child_size <= 8) {
std::uint64_t scale = 0;
for (std::size_t i = 0; i < child_size; ++i) {
scale = (scale << 8) | data[child_payload + i];
}
if (scale != 0) timestamp_scale_ns = scale;
} else if (child_id == 0x4489u && (child_size == 4 || child_size == 8)) {
// Duration is a big-endian float: 4 or 8 bytes, both occur.
const std::uint8_t* field = data.data() + child_payload;
if (child_size == 4) {
const std::uint32_t bits = be32(field);
float value = 0.0f;
std::memcpy(&value, &bits, sizeof(value));
duration_ticks = static_cast<double>(value);
} else {
const std::uint64_t bits =
(static_cast<std::uint64_t>(be32(field)) << 32) | be32(field + 4);
double value = 0.0;
std::memcpy(&value, &bits, sizeof(value));
duration_ticks = value;
}
}
inner.position = child_end;
}
break;
}
case 0xAEu: { // TrackEntry
// Read this track's type and codec.
std::uint64_t track_type = 0;
std::string codec;
EbmlReader inner{data.data(), payload_end, payload};
while (!inner.at_end()) {
std::uint64_t child_id = 0;
std::uint64_t child_size = 0;
bool child_unknown = false;
if (!inner.read_id(&child_id) ||
!inner.read_size(&child_size, &child_unknown)) {
break;
}
const std::size_t child_payload = inner.position;
const std::size_t child_end =
child_unknown ? payload_end
: (std::min<std::size_t>)(
payload_end,
child_payload + static_cast<std::size_t>(child_size));
if (child_id == 0x83u && child_size >= 1) { // TrackType
track_type = data[child_payload];
} else if (child_id == 0x86u) { // CodecID
codec.assign(reinterpret_cast<const char*>(data.data() + child_payload),
child_end - child_payload);
}
inner.position = child_end;
}
if (track_type == 2u) { // audio
if (first_audio_codec.empty()) first_audio_codec = codec;
if (codec == "A_EAC3") {
result.eac3 = true;
result.audio_index = audio_seen;
result.codec = codec;
found = true;
}
++audio_seen;
}
break;
}
case 0x18538067u: // Segment: descend, the size may be unknown
self(payload, payload_end, depth + 1, self);
break;
default:
break;
}
if (found) break;
reader.position = payload_end;
if (payload_end == element_start) break; // no progress: stop
}
};
walk(0, data.size(), 0, walk);
if (duration_ticks > 0.0 && timestamp_scale_ns > 0.0) {
result.duration_seconds = duration_ticks * timestamp_scale_ns / 1.0e9;
}
if (result.eac3) {
result.detail = "matroska: E-AC-3 audio track " + std::to_string(result.audio_index);
} else if (saw_tracks) {
result.detail = "matroska: first audio track is " +
(first_audio_codec.empty() ? std::string("unknown") : first_audio_codec);
} else {
result.detail = "matroska: no track list in the scanned window";
}
return result;
}
} // namespace
const char* kind_name(Kind kind) {
switch (kind) {
case Kind::kMp4: return "mp4";
case Kind::kMatroska: return "matroska";
default: return "none";
}
}
bool is_container_extension(const char* extension) {
if (extension == nullptr) return false;
static const char* const kExtensions[] = {"mp4", "m4a", "m4b", "m4p", "m4r",
"mov", "mkv", "mka", "webm"};
for (const char* candidate : kExtensions) {
if (_stricmp(extension, candidate) == 0) return true;
}
return false;
}
Result scan(const std::string& path, std::size_t max_bytes) {
Result result;
Window file;
if (!file.open(path)) {
result.detail = "cannot open the file";
return result;
}
if (file.size() < 16) {
result.detail = "file too small to be a container";
return result;
}
std::uint8_t head[16];
if (!file.read(0, head, sizeof(head))) {
result.detail = "cannot read the file header";
return result;
}
// Matroska starts with the EBML header element (0x1A45DFA3); ISO base media
// starts with a box whose type is at offset 4 ("ftyp" for a normal file).
if (head[0] == 0x1A && head[1] == 0x45 && head[2] == 0xDF && head[3] == 0xA3) {
result = scan_matroska(file, max_bytes);
} else {
result = scan_mp4(file, max_bytes);
}
joc_log::line("container: %s -> %s (eac3=%d audio#%u codec=%s)", file_name_of(path).c_str(),
result.detail.c_str(), result.eac3 ? 1 : 0, result.audio_index,
result.codec.empty() ? "-" : result.codec.c_str());
return result;
}
} // namespace joc_container
+47
View File
@@ -0,0 +1,47 @@
// Cheap structural probe of container files, to answer one question: does this
// file hold an E-AC-3 audio track, and if so which one?
//
// It exists so that a Media Library scan does not pay for an ffmpeg launch on
// every MP4 in the collection. The probe reads a bounded window of the file and
// walks only the headers it needs:
//
// MP4 / MOV top-level boxes -> moov -> trak -> hdlr(mdia) + stsd sample entry.
// moov may sit at the end (no faststart), so the tail is checked too.
// Matroska EBML header -> Segment -> Tracks -> TrackEntry -> CodecID.
//
// The E-AC-3 bitstream itself is never demuxed here: ffmpeg extracts it when the
// file is actually decoded, which keeps this file small and lets every container
// ffmpeg understands work without a demuxer of our own.
#pragma once
#include <cstdint>
#include <string>
namespace joc_container {
enum class Kind {
kNone,
kMp4,
kMatroska,
};
const char* kind_name(Kind kind);
struct Result {
Kind kind = Kind::kNone;
bool eac3 = false; // an E-AC-3 audio track is present
unsigned audio_index = 0; // which audio track it is, 0-based
double duration_seconds = 0.0; // from the container header, 0 when not stated
std::string codec; // codec identifier found, for the log
std::string detail;
};
// True when the extension belongs to a container this component looks inside.
bool is_container_extension(const char* extension);
// Reads at most max_bytes of header (plus the same amount at the end for MP4) and
// reports what it found. Missing files, empty files and unknown containers come
// back as Kind::kNone with a detail string.
Result scan(const std::string& path, std::size_t max_bytes = 4u * 1024u * 1024u);
} // namespace joc_container
+570
View File
@@ -0,0 +1,570 @@
// mpv C plugin: E-AC-3 JOC (Dolby Atmos) playback.
//
// mpv decodes the file's video and its E-AC-3 bed normally; this plugin adds a
// second audio track that carries the object-audio rendering. The rendering
// itself is the same kernel, the same engine and the same settings as the
// upstream frontends, so the delivered samples match them bit for bit.
//
// The track is served over a loopback HTTP range endpoint backed by the
// renderer: mpv reads it as an ordinary seekable WAV, which is what lets its
// demuxer, cache, A/V sync, WASAPI output and seeking all keep working.
#include <winsock2.h>
#include <windows.h>
// Every mpv_* call goes through the host's exported symbol table: a cplugin
// must not link against libmpv.
#ifndef MPV_CPLUGIN_DYNAMIC_SYM
#define MPV_CPLUGIN_DYNAMIC_SYM
#endif
#include <mpv/client.h>
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <memory>
#include <string>
#include "container_scan.h"
#include "joc_decode.h"
#include "log.h"
#include "win_path.h"
#include "plugin/audio_source.h"
#include "plugin/config.h"
#include "plugin/http_server.h"
#include "plugin/wav.h"
namespace {
constexpr const char* kResource = "/joc.wav";
std::string plugin_directory() { return joc_decode::component_directory(); }
bool file_exists(const std::string& path) {
std::wstring wide;
const int needed = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
if (needed <= 1) return false;
wide.resize(static_cast<std::size_t>(needed));
MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wide.data(), needed);
const DWORD attributes = GetFileAttributesW(wide.c_str());
return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
// The default HRTF lives next to the plugin, or one level up when the plugin
// sits in <mpv>\scripts and the data in <mpv> itself.
std::string default_hrtf_file(const joc_mpv::Config& config) {
const char* name = (config.hrtf_source == 0) ? "binaural.sofa"
: "binaural.personalized_headphone";
const std::string directory = plugin_directory();
const std::string candidates[] = {directory + "\\HRTF\\" + name,
directory + "\\..\\HRTF\\" + name};
for (const std::string& candidate : candidates) {
if (file_exists(candidate)) return candidate;
}
return {};
}
// Sent as a node array rather than a command string: an error message carries
// backslashes and non-ASCII text, which the command parser would mangle.
void osd(mpv_handle* mpv, const std::string& text) {
mpv_node values[3];
values[0].format = MPV_FORMAT_STRING;
values[0].u.string = const_cast<char*>("show-text");
values[1].format = MPV_FORMAT_STRING;
values[1].u.string = const_cast<char*>(text.c_str());
values[2].format = MPV_FORMAT_STRING;
values[2].u.string = const_cast<char*>("3000");
mpv_node_list list{};
list.num = 3;
list.values = values;
mpv_node command{};
command.format = MPV_FORMAT_NODE_ARRAY;
command.u.list = &list;
mpv_command_node(mpv, &command, nullptr);
}
// Byte offset of the first syncframe. A bare stream may start with an ID3v2
// tag, which the renderer refuses to parse as audio.
std::uint64_t leading_tag_bytes(const std::string& path) {
FILE* file = _wfopen(joc_path::to_wide_extended(path).c_str(), L"rb");
if (file == nullptr) return 0;
unsigned char header[10] = {};
const std::size_t got = std::fread(header, 1, sizeof(header), file);
std::fclose(file);
if (got != sizeof(header) || std::memcmp(header, "ID3", 3) != 0) return 0;
auto synchsafe = [](unsigned char a, unsigned char b, unsigned char c, unsigned char d) {
return (static_cast<std::uint64_t>(a & 0x7F) << 21) |
(static_cast<std::uint64_t>(b & 0x7F) << 14) |
(static_cast<std::uint64_t>(c & 0x7F) << 7) |
static_cast<std::uint64_t>(d & 0x7F);
};
const std::uint64_t size = synchsafe(header[6], header[7], header[8], header[9]);
// The footer flag (0x10) adds another 10 bytes after the tag body.
const std::uint64_t footer = (header[5] & 0x10) != 0 ? 10u : 0u;
return 10u + size + footer;
}
std::string format_channels(unsigned channels, const std::string& layout, int output) {
if (output == 0) return "binaural 2ch";
return layout + " " + std::to_string(channels) + "ch";
}
// The WAV the plugin serves: header plus the rendered data chunk.
struct Stream {
std::shared_ptr<joc_mpv::Source> source;
std::string header;
std::uint64_t total_bytes = 0;
std::size_t write_bytes = 65536;
bool verbose = false;
// Only the newest request may read from the renderer: a request that mpv
// replaces (a seek closes the old stream and opens a new one) has to stop
// instead of pulling the renderer back to its own position.
std::atomic<unsigned> generation{0};
};
// Streams the requested part of the file until the client closes the
// connection or the audio ends. mpv seeks by reopening the URL with a new
// Range, which becomes a renderer seek.
void serve_request(const std::shared_ptr<Stream>& stream, const joc_mpv::HttpRequest& request,
joc_mpv::HttpResponse* response) {
if (request.method != "GET") {
response->status = 400;
return;
}
if (request.target.compare(0, std::strlen(kResource), kResource) != 0) {
response->status = 404;
return;
}
const std::uint64_t header_size = stream->header.size();
const std::uint64_t total = stream->total_bytes;
const std::uint64_t start = request.has_range ? request.range_start : 0;
if (start >= total) {
response->status = 416;
response->headers = "Content-Range: bytes */" + std::to_string(total) + "\r\n";
return;
}
response->status = request.has_range ? 206 : 200;
response->headers = "Content-Type: audio/wav\r\n";
response->headers += "Accept-Ranges: bytes\r\n";
if (request.has_range) {
response->headers += "Content-Range: bytes " + std::to_string(start) + "-" +
std::to_string(total - 1) + "/" + std::to_string(total) + "\r\n";
}
if (stream->verbose) {
joc_log::line("http: %s %s from %llu of %llu", request.method.c_str(),
request.target.c_str(), static_cast<unsigned long long>(start),
static_cast<unsigned long long>(total));
}
const unsigned generation = stream->generation.fetch_add(1) + 1;
const std::uint64_t last =
(request.has_range && request.has_range_end)
? std::min<std::uint64_t>(request.range_end, total - 1)
: total - 1;
response->stream = [stream, start, last, header_size, total, generation](
joc_mpv::ResponseWriter& writer) {
const unsigned frame_bytes = stream->source->bytes_per_frame();
std::vector<std::uint8_t> buffer(stream->write_bytes);
std::uint64_t offset = start;
// The WAV header is one chunk of its own: from the first data byte on,
// every offset is a whole number of frames, so the renderer never has to
// reposition just because a write did not end on a frame boundary.
if (offset < header_size) {
const std::size_t take = static_cast<std::size_t>(
std::min<std::uint64_t>(header_size - offset, last + 1 - offset));
if (!writer.write(stream->header.data() + offset, take)) return;
offset += take;
}
while (offset <= last) {
if (stream->generation.load() != generation) break;
std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(buffer.size(), last + 1 - offset));
want -= want % frame_bytes;
if (want == 0) break;
std::string error;
const std::size_t got =
stream->source->read(offset - header_size, buffer.data(), want, &error);
if (got == 0) {
if (stream->verbose) {
joc_log::line("http: stream ended at %llu: %s",
static_cast<unsigned long long>(offset), error.c_str());
}
break;
}
if (!writer.write(buffer.data(), got)) break;
offset += got;
}
};
}
struct Plugin {
mpv_handle* mpv = nullptr;
joc_mpv::Config config;
std::unique_ptr<joc_mpv::HttpServer> server;
std::shared_ptr<Stream> stream;
std::string current_path; // the file a stream was prepared for
std::string url;
// The last file a probe answered for, so a rejected input is not probed a
// second time at file-loaded.
std::string probed_path;
bool probed_joc = false;
std::string config_dir;
// The file's own audio is muted (when the configuration asks for it) from
// the first sample until the rendered track takes over, so the opening of a
// JOC file is never the plain bed. The player's own mute state is restored.
bool muted_by_us = false;
bool saved_mute = false;
void stop_stream() {
if (stream) stream->generation.fetch_add(1);
if (server) server->stop();
if (stream && stream->source) stream->source->close();
stream.reset();
server.reset();
current_path.clear();
url.clear();
}
bool muted_state() {
int flag = 0;
if (mpv_get_property(mpv, "mute", MPV_FORMAT_FLAG, &flag) < 0) return false;
return flag != 0;
}
void set_muted(bool muted) {
int flag = muted ? 1 : 0;
mpv_set_property(mpv, "mute", MPV_FORMAT_FLAG, &flag);
}
void suppress_bed() {
if (!config.mute_until_ready || muted_by_us) return;
saved_mute = muted_state();
if (saved_mute) return; // the player is already silent; nothing to restore
set_muted(true);
muted_by_us = true;
}
void restore_bed() {
if (!muted_by_us) return;
set_muted(saved_mute);
muted_by_us = false;
}
// Only inputs that can carry E-AC-3 JOC are worth silencing before the
// probe answers; anything else would lose its first moments to a mute.
static bool candidate(const std::string& path) {
const std::size_t dot = path.find_last_of('.');
if (dot == std::string::npos) return false;
std::string extension = path.substr(dot + 1);
for (char& ch : extension) {
if (ch >= 'A' && ch <= 'Z') ch = static_cast<char>(ch - 'A' + 'a');
}
static const char* const kExtensions[] = {"eac3", "ec3", "ac3", "mp4", "m4a", "m4b",
"mov", "mkv", "mka", "webm"};
for (const char* known : kExtensions) {
if (extension == known) return true;
}
return false;
}
bool probe(const std::string& path, joc_decode::Settings* settings, double* duration) {
const std::uint64_t tag_bytes = leading_tag_bytes(path);
const joc_decode::FileProbe bare = joc_decode::probe_file(path, 0, tag_bytes);
if (bare.readable && bare.joc) {
settings->input_kind = joc_decode::InputKind::kBare;
settings->stream_start_bytes = tag_bytes;
*duration = bare.duration_seconds;
joc_log::line("probe: %s is a JOC stream (%llu frames, %.3f s)", path.c_str(),
static_cast<unsigned long long>(bare.frames), *duration);
return true;
}
const joc_container::Result container = joc_container::scan(path);
if (container.kind == joc_container::Kind::kNone || !container.eac3) {
joc_log::line("probe: %s is not an E-AC-3 JOC input (%s)", path.c_str(),
container.detail.c_str());
return false;
}
bool verdict = false;
std::string detail;
if (!joc_decode::probe_container_joc(config.ffmpeg, path, container.audio_index, &verdict,
&detail) ||
!verdict) {
joc_log::line("probe: container %s track %u is not JOC (%s)", path.c_str(),
container.audio_index, detail.c_str());
return false;
}
settings->input_kind = joc_decode::InputKind::kContainer;
settings->audio_index = container.audio_index;
*duration = container.duration_seconds;
joc_log::line("probe: %s carries JOC in audio track %u (%.3f s)", path.c_str(),
container.audio_index, *duration);
return true;
}
// Starts the renderer and its endpoint for a file, without touching the
// player yet: at start-file the entry is not loaded, so audio-add could only
// be applied to the previous one. Returns true when a stream is ready.
bool prepare(const std::string& path) {
stop_stream();
probed_path = path;
probed_joc = false;
if (!config.enabled) return false;
joc_decode::Settings settings;
settings.output = (config.output == 0) ? joc_decode::Output::kBinaural
: joc_decode::Output::kSpeaker;
settings.speaker_layout = config.layout;
settings.hrtf_source = (config.hrtf_source == 0) ? joc_decode::HrtfSource::kSofa
: joc_decode::HrtfSource::kRosella;
settings.hrtf_file = config.hrtf_file;
if (settings.hrtf_file.empty() && settings.output == joc_decode::Output::kBinaural) {
settings.hrtf_file = default_hrtf_file(config);
}
settings.binaural_mode = static_cast<std::uint32_t>(config.binaural_mode);
settings.gain_db = config.gain_db;
settings.tail_seconds = config.tail_seconds;
settings.force_int24 = config.force_int24;
settings.object_delay_samples = config.object_delay_samples;
settings.native_threads = config.native_threads;
settings.ffmpeg_path = config.ffmpeg;
settings.core_path = config.core_dll;
// The compiled SOFA field is the dominant part of the startup cost;
// keeping it on disk makes every later file (and every seek restart-free
// start) skip that work.
if (config.verbose) {
joc_log::line("config: hrtf-cache=%s dir=%s", config.hrtf_cache.c_str(),
config.hrtf_cache_dir.c_str());
}
if (config.hrtf_cache == "none") {
settings.hrtf_cache_policy = 0;
} else if (config.hrtf_cache == "memory") {
settings.hrtf_cache_policy = 1;
} else {
// disk and auto: the config directory is the natural place for a
// cache; without one the renderer compiles in memory as before.
std::string directory = config.hrtf_cache_dir;
if (directory.empty() && !config_dir.empty()) {
directory = config_dir + "\\joc-hrtf-cache";
}
if (!directory.empty()) {
settings.hrtf_cache_policy = 2;
settings.hrtf_cache_dir = directory;
} else {
settings.hrtf_cache_policy = 1;
}
}
settings.pipeline_delay_samples = joc_decode::kJocSeekPipelineDelaySamples;
settings.seek_preroll_frames = joc_decode::kJocSeekPrerollFrames;
double duration = 0.0;
if (!probe(path, &settings, &duration)) return false;
// A container header may not state a duration; the player knows it.
if (!(duration > 0.0)) {
double from_player = 0.0;
if (mpv_get_property(mpv, "duration", MPV_FORMAT_DOUBLE, &from_player) >= 0) {
duration = from_player;
}
}
if (!(duration > 0.0)) {
joc_log::line("start: no duration for %s, leaving the input to mpv", path.c_str());
osd(mpv, "JOC: unknown duration, plugin skipped");
return false;
}
settings.length_seconds = duration;
auto source = std::make_shared<joc_mpv::Source>();
std::string error;
if (!source->open(path, settings, duration, &error)) {
// A disk cache that cannot be used must not cost playback: retry the
// way this worked before the cache existed.
if (settings.hrtf_cache_policy == 2) {
joc_log::line("prepare: disk HRTF cache unusable (%s); retrying in memory",
error.c_str());
settings.hrtf_cache_policy = 1;
settings.hrtf_cache_dir.clear();
error.clear();
}
if (!source->open(path, settings, duration, &error)) {
joc_log::line("start: renderer failed for %s: %s", path.c_str(), error.c_str());
osd(mpv, "JOC: " + error);
return false;
}
}
auto created = std::make_shared<Stream>();
created->source = source;
const std::string mask_layout = (config.output == 0) ? "2.0" : config.layout;
created->header = joc_mpv::wav_header(
source->channels(), source->bits_per_sample(),
joc_mpv::channel_mask(mask_layout, source->channels()), source->data_bytes());
created->total_bytes = created->header.size() + source->data_bytes();
const double per_write = config.chunk_seconds * 48000.0 *
static_cast<double>(source->bytes_per_frame());
created->write_bytes = static_cast<std::size_t>(
std::min(4.0 * 1024.0 * 1024.0, std::max(16.0 * 1024.0, per_write)));
created->verbose = config.verbose;
auto http = std::make_unique<joc_mpv::HttpServer>();
unsigned short port = 0;
const std::shared_ptr<Stream> captured = created;
if (!http->start(
[captured](const joc_mpv::HttpRequest& request, joc_mpv::HttpResponse* response) {
serve_request(captured, request, response);
},
&port, &error)) {
joc_log::line("start: %s", error.c_str());
osd(mpv, "JOC: " + error);
source->close();
return false;
}
stream = created;
server = std::move(http);
current_path = path;
url = "http://127.0.0.1:" + std::to_string(port) + kResource;
probed_joc = true;
joc_log::line("prepare: %s -> %s (%s, %s)", path.c_str(), url.c_str(),
format_channels(source->channels(), config.layout, config.output).c_str(),
config.ffmpeg.c_str());
return true;
}
// Adds the prepared stream as a selected audio track and lets the player's
// own audio come back.
void attach() {
if (!stream || current_path.empty()) return;
if (!config.attach) {
joc_log::line("attach: disabled (joc-attach=no); serving %s", url.c_str());
restore_bed();
return;
}
const std::string title =
"JOC " + (config.output == 0 ? std::string("binaural") : config.layout);
const char* arguments[] = {"audio-add", url.c_str(), "select", title.c_str(), nullptr};
const int result = mpv_command(mpv, arguments);
if (result < 0) {
joc_log::line("attach: audio-add failed: %s", mpv_error_string(result));
osd(mpv, std::string("JOC: audio-add failed: ") + mpv_error_string(result));
stop_stream();
restore_bed();
return;
}
restore_bed();
const std::string summary =
"JOC: " + format_channels(stream->source->channels(), config.layout, config.output) +
(config.force_int24 ? " int24" : " float32");
joc_log::line("attach: %s (%s)", current_path.c_str(), summary.c_str());
osd(mpv, summary);
}
};
std::string read_string_property(mpv_handle* mpv, const char* name) {
char* value = mpv_get_property_string(mpv, name);
if (value == nullptr) return {};
std::string text(value);
mpv_free(value);
return text;
}
std::wstring to_wide(const std::string& text) {
if (text.empty()) return {};
const int needed = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), -1, nullptr, 0);
if (needed <= 1) return {};
std::wstring wide(static_cast<std::size_t>(needed), L'\0');
MultiByteToWideChar(CP_UTF8, 0, text.c_str(), -1, wide.data(), needed);
wide.resize(static_cast<std::size_t>(needed - 1));
return wide;
}
// Diagnostics must not land in the directory mpv scans for scripts: every file
// there is offered to the script loader. The player's config directory is the
// natural place; one level above the plugin is the fallback.
void configure_log_directory(mpv_handle* mpv, const joc_mpv::Config& config) {
std::string path = config.log_path;
if (path.empty()) {
std::string directory = read_string_property(mpv, "options/config-dir");
if (directory.empty()) directory = plugin_directory() + "\\..";
path = directory + "\\joc_decoder.log";
}
const std::wstring wide = to_wide(path);
if (!wide.empty()) SetEnvironmentVariableW(L"JOC_LOG", wide.c_str());
}
void configure_output(mpv_handle* mpv, const joc_mpv::Config& config) {
if (config.wasapi == "yes") {
const int result = mpv_set_property_string(mpv, "ao", "wasapi");
joc_log::line("output: ao=wasapi -> %s", result < 0 ? mpv_error_string(result) : "ok");
}
if (config.exclusive) {
const int result = mpv_set_property_string(mpv, "audio-exclusive", "yes");
joc_log::line("output: audio-exclusive=yes -> %s",
result < 0 ? mpv_error_string(result) : "ok");
}
}
} // namespace
extern "C" __declspec(dllexport) int mpv_open_cplugin(mpv_handle* handle) {
Plugin plugin;
plugin.mpv = handle;
std::string warnings;
const std::string script_opts = read_string_property(handle, "options/script-opts");
plugin.config = joc_mpv::parse_config(script_opts, &warnings);
plugin.config_dir = read_string_property(handle, "options/config-dir");
configure_log_directory(handle, plugin.config);
if (!warnings.empty()) joc_log::line("config: %s", warnings.c_str());
joc_log::line("plugin: joc_mpv loaded (libmpv %lu, dir %s)",
static_cast<unsigned long>(mpv_client_api_version()),
plugin_directory().c_str());
configure_output(handle, plugin.config);
for (;;) {
mpv_event* event = mpv_wait_event(handle, -1);
if (event == nullptr) continue;
switch (event->event_id) {
case MPV_EVENT_START_FILE: {
// The renderer starts here, while mpv is still opening the file,
// and the file's own audio is silenced first so the opening
// moments are not the plain bed.
plugin.restore_bed();
const std::string path = read_string_property(handle, "path");
if (path.empty() || path.find("://") != std::string::npos) break;
if (Plugin::candidate(path)) plugin.suppress_bed();
if (!plugin.prepare(path)) plugin.restore_bed();
break;
}
case MPV_EVENT_FILE_LOADED: {
const std::string path = read_string_property(handle, "path");
if (path.empty() || path.find("://") != std::string::npos) break;
if (plugin.current_path != path) {
// No start-file notification (a reload, for instance), or a
// file the probe rejected there.
if (plugin.probed_path == path && !plugin.probed_joc) {
plugin.restore_bed();
break;
}
if (!plugin.prepare(path)) {
plugin.restore_bed();
break;
}
}
plugin.attach();
break;
}
case MPV_EVENT_END_FILE:
plugin.stop_stream();
plugin.restore_bed();
break;
case MPV_EVENT_SHUTDOWN:
plugin.stop_stream();
plugin.restore_bed();
joc_log::line("plugin: shutting down");
return 0;
default:
break;
}
}
}
+453
View File
@@ -0,0 +1,453 @@
#include "eac3_scan.h"
#include <cstring>
namespace joc_eac3 {
namespace {
constexpr std::uint16_t kEac3Syncword = 0x0B77;
constexpr std::uint16_t kEmdfSyncword = 0x5838;
constexpr std::uint8_t kIdOamd = 11;
constexpr std::uint8_t kIdJoc = 14;
constexpr std::size_t kMaxPayloads = 16;
// MSB-first bit reader with an explicit limit, matching the core's reader
// semantics (reads past the limit fail rather than returning zeros).
class BitReader {
public:
BitReader(const std::uint8_t* data, std::size_t limit_bits, std::size_t start_bit)
: data_(data), limit_(limit_bits), position_(start_bit) {}
std::uint32_t read(unsigned count) {
std::uint32_t value = 0;
for (unsigned i = 0; i < count; ++i) {
if (position_ >= limit_) {
failed_ = true;
return 0;
}
const unsigned byte = data_[position_ >> 3];
value = (value << 1) | ((byte >> (7u - (position_ & 7u))) & 1u);
++position_;
}
return value;
}
bool skip(std::size_t count) {
if (position_ + count > limit_) {
failed_ = true;
return false;
}
position_ += count;
return true;
}
// value, then a continuation bit; an unterminated chain is a syntax error.
bool variable_bits(unsigned width, unsigned max_groups, std::uint32_t* out) {
std::uint32_t value = 0;
for (unsigned group = 0; group < max_groups; ++group) {
value += read(width);
if (failed_) return false;
const std::uint32_t more = read(1);
if (failed_) return false;
if (more == 0u) {
if (out != nullptr) *out = value;
return true;
}
value = (value + 1u) << width;
}
failed_ = true;
return false;
}
std::size_t position() const { return position_; }
bool failed() const { return failed_; }
void set_failed() { failed_ = true; }
private:
const std::uint8_t* data_ = nullptr;
std::size_t limit_ = 0;
std::size_t position_ = 0;
bool failed_ = false;
};
struct Payload {
std::uint8_t id = 0;
std::size_t bit_offset = 0;
std::size_t size = 0;
};
struct Container {
std::size_t start_bit = 0;
std::size_t raw_size = 0;
std::size_t payload_count = 0;
Payload payloads[kMaxPayloads] = {};
bool has(std::uint8_t id) const {
for (std::size_t i = 0; i < payload_count; ++i) {
if (payloads[i].id == id) return true;
}
return false;
}
};
bool parse_container(const std::uint8_t* data, std::size_t size_bits, std::size_t start_bit,
Container* out) {
if (start_bit + 16u > size_bits) return false;
BitReader reader(data, size_bits, start_bit);
if (reader.read(16) != kEmdfSyncword) return false;
const std::uint32_t length = reader.read(16);
const std::size_t body_start = reader.position();
const std::size_t body_end = body_start + static_cast<std::size_t>(length) * 8u;
if (reader.failed() || body_end > size_bits) return false;
BitReader body(data, body_end, body_start);
std::uint32_t version = body.read(2);
if (body.failed()) return false;
if (version == 3u) {
std::uint32_t extra = 0;
if (!body.variable_bits(2, 8, &extra)) return false;
version += extra;
}
std::uint32_t key_id = body.read(3);
if (body.failed()) return false;
if (key_id == 7u) {
std::uint32_t extra = 0;
if (!body.variable_bits(3, 8, &extra)) return false;
key_id += extra;
}
// TS 103 420 JOC is version 0 / key_id 0; the strict check also rejects
// false 0x5838 markers that happen to sit inside audio data.
if (version != 0u || key_id != 0u) return false;
Container container;
container.start_bit = start_bit;
bool terminated = false;
while (body.position() + 5u <= body_end) {
std::uint32_t payload_id = body.read(5);
if (body.failed()) return false;
if (payload_id == 0u) {
terminated = true;
break;
}
if (payload_id == 0x1Fu) {
std::uint32_t extra = 0;
if (!body.variable_bits(5, 8, &extra)) return false;
payload_id += extra;
}
for (std::size_t i = 0; i < container.payload_count; ++i) {
if (container.payloads[i].id == static_cast<std::uint8_t>(payload_id)) return false;
}
if (container.payload_count >= kMaxPayloads) return false;
const std::uint32_t has_sample_offset = body.read(1);
if (body.failed()) return false;
if (has_sample_offset != 0u) {
(void)body.read(12);
}
if (body.read(1) != 0u) {
std::uint32_t ignored = 0;
if (!body.variable_bits(11, 8, &ignored)) return false;
}
if (body.read(1) != 0u) {
std::uint32_t ignored = 0;
if (!body.variable_bits(2, 8, &ignored)) return false;
}
if (body.read(1) != 0u) {
if (!body.skip(8)) return false;
}
if (body.failed()) return false;
if (body.read(1) == 0u) {
bool frame_aligned = false;
if (has_sample_offset == 0u) {
frame_aligned = body.read(1) != 0u;
if (frame_aligned && !body.skip(2)) return false;
}
if ((has_sample_offset != 0u || frame_aligned) && !body.skip(7)) return false;
}
if (body.failed()) return false;
std::uint32_t payload_size = 0;
if (!body.variable_bits(8, 8, &payload_size)) return false;
const std::size_t payload_bits = static_cast<std::size_t>(payload_size) * 8u;
if (body.position() + payload_bits > body_end) return false;
Payload& entry = container.payloads[container.payload_count++];
entry.id = static_cast<std::uint8_t>(payload_id);
entry.bit_offset = body.position();
entry.size = payload_size;
if (!body.skip(payload_bits)) return false;
}
if (!terminated) return false;
container.raw_size = 4u + static_cast<std::size_t>(length);
*out = container;
return true;
}
// Candidate 0x5838 positions over the eight bit alignments, ascending.
void marker_offsets(const std::uint8_t* data, std::size_t size, std::size_t* out,
std::size_t capacity, std::size_t* count) {
*count = 0;
if (size < 4u) return;
for (std::size_t shift = 0; shift < 8u; ++shift) {
const std::size_t aligned_len = (shift == 0u) ? size : (size - 1u);
for (std::size_t i = 0; i + 1u < aligned_len; ++i) {
std::uint8_t first = 0;
std::uint8_t second = 0;
if (shift == 0u) {
first = data[i];
second = data[i + 1u];
} else {
first = static_cast<std::uint8_t>(
((static_cast<std::uint16_t>(data[i]) << shift) |
(static_cast<std::uint16_t>(data[i + 1u]) >> (8u - shift))) &
0xFFu);
second = static_cast<std::uint8_t>(
((static_cast<std::uint16_t>(data[i + 1u]) << shift) |
(static_cast<std::uint16_t>(data[i + 2u]) >> (8u - shift))) &
0xFFu);
}
if (first == 0x58u && second == 0x38u) {
if (*count < capacity) out[(*count)++] = i * 8u + shift;
}
}
}
}
bool contains_payload(const std::uint8_t* frame, std::size_t size, std::uint8_t wanted,
std::size_t* first_bit) {
for (std::size_t at = 0; at + 1u < size; ++at) {
if (frame[at] != 0x58u || frame[at + 1u] != 0x38u) continue;
Container container;
if (parse_container(frame, size * 8u, at * 8u, &container) && container.has(wanted)) {
if (first_bit != nullptr) *first_bit = at * 8u;
return true;
}
}
for (std::size_t shift = 1; shift < 8u; ++shift) {
const std::size_t aligned_len = size - 1u;
for (std::size_t i = 0; i + 1u < aligned_len; ++i) {
const std::uint8_t first = static_cast<std::uint8_t>(
((static_cast<std::uint16_t>(frame[i]) << shift) |
(static_cast<std::uint16_t>(frame[i + 1u]) >> (8u - shift))) &
0xFFu);
const std::uint8_t second = static_cast<std::uint8_t>(
((static_cast<std::uint16_t>(frame[i + 1u]) << shift) |
(static_cast<std::uint16_t>(frame[i + 2u]) >> (8u - shift))) &
0xFFu);
if (first != 0x58u || second != 0x38u) continue;
Container container;
if (parse_container(frame, size * 8u, i * 8u + shift, &container) &&
container.has(wanted)) {
if (first_bit != nullptr) *first_bit = i * 8u + shift;
return true;
}
}
}
return false;
}
} // namespace
namespace {
std::uint32_t read_bits(const std::uint8_t* data, std::size_t start, std::size_t count) {
std::uint32_t value = 0;
for (std::size_t index = start; index < start + count; ++index) {
value = (value << 1) | ((data[index >> 3] >> (7u - (index & 7u))) & 1u);
}
return value;
}
// AC-3 syncframe length in 16-bit words, indexed by fscod then frmsizecod.
const std::uint16_t kAc3FrameWords[3][38] = {
{64, 64, 80, 80, 96, 96, 112, 112, 128, 128, 160, 160, 192, 192, 224, 224,
256, 256, 320, 320, 384, 384, 448, 448, 512, 512, 640, 640, 768, 768,
896, 896, 1024, 1024, 1152, 1152, 1280, 1280},
{69, 70, 87, 88, 104, 105, 121, 122, 139, 140, 174, 175, 208, 209, 243, 244,
278, 278, 348, 348, 417, 418, 487, 487, 557, 557, 696, 696, 835, 835,
975, 975, 1114, 1114, 1253, 1253, 1393, 1393},
{96, 96, 120, 120, 144, 144, 168, 168, 192, 192, 240, 240, 288, 288, 336, 336,
384, 384, 480, 480, 576, 576, 672, 672, 768, 768, 960, 960, 1152, 1152,
1344, 1344, 1536, 1536, 1728, 1728, 1920, 1920},
};
} // namespace
std::size_t frame_header_at(const std::uint8_t* data, std::size_t size, std::size_t offset,
FrameHeader* out) {
if (data == nullptr || offset + 6u > size) return 0;
const std::uint16_t syncword =
static_cast<std::uint16_t>((static_cast<std::uint16_t>(data[offset]) << 8) | data[offset + 1]);
if (syncword != kEac3Syncword) return 0;
const std::size_t base = offset * 8u;
const std::uint32_t bsid = read_bits(data, base + 40u, 5u);
if (bsid <= 8u) {
const std::uint32_t fscod = read_bits(data, base + 32u, 2u);
const std::uint32_t frmsizecod = read_bits(data, base + 34u, 6u);
if (fscod > 2u || frmsizecod >= 38u) return 0;
if (out != nullptr) {
out->frame_bytes = static_cast<std::size_t>(kAc3FrameWords[fscod][frmsizecod]) * 2u;
out->offset = offset;
out->codec = 0;
out->strmtyp = 0;
out->substreamid = 0;
}
return static_cast<std::size_t>(kAc3FrameWords[fscod][frmsizecod]) * 2u;
}
const std::size_t words =
(static_cast<std::size_t>(data[offset + 2] & 0x07u) << 8) | data[offset + 3];
if (out != nullptr) {
out->frame_bytes = (words + 1u) * 2u;
out->offset = offset;
out->codec = 1;
out->strmtyp = static_cast<std::uint8_t>(read_bits(data, base + 16u, 2u));
out->substreamid = static_cast<std::uint8_t>(read_bits(data, base + 18u, 3u));
}
return (words + 1u) * 2u;
}
std::size_t frame_bytes_at(const std::uint8_t* data, std::size_t size, std::size_t offset) {
return frame_header_at(data, size, offset, nullptr);
}
std::size_t audio_frame_bytes_at(const std::uint8_t* data, std::size_t size, std::size_t offset,
bool end_of_stream) {
constexpr std::size_t kMaxSubstreams = 8;
FrameHeader seen[kMaxSubstreams];
std::size_t count = 0;
std::size_t consumed = 0;
while (count < kMaxSubstreams) {
FrameHeader header;
const std::size_t bytes = frame_header_at(data, size, offset + consumed, &header);
if (bytes == 0 || offset + consumed + bytes > size) break;
bool repeats = false;
for (std::size_t index = 0; index < count; ++index) {
if (seen[index].same_stream(header)) {
repeats = true;
break;
}
}
if (repeats) return consumed;
seen[count++] = header;
consumed += bytes;
}
if (count != 0u && consumed != 0u && end_of_stream) return consumed;
return 0;
}
bool joc_config_idx(const std::uint8_t* frame, std::size_t frame_bytes, unsigned* out) {
if (out == nullptr || frame == nullptr || frame_bytes < 8u) return false;
std::size_t offsets[4096];
std::size_t count = 0;
marker_offsets(frame, frame_bytes, offsets, 4096, &count);
for (std::size_t i = 0; i < count; ++i) {
Container candidate;
if (!parse_container(frame, frame_bytes * 8u, offsets[i], &candidate)) continue;
if (!candidate.has(kIdOamd) || !candidate.has(kIdJoc)) continue;
for (std::size_t p = 0; p < candidate.payload_count; ++p) {
if (candidate.payloads[p].id != kIdJoc) continue;
// joc_dmx_config_idx is the first 3 bits of the JOC payload, followed by
// joc_num_objects_bits (6) and joc_ext_config_idx (3).
const std::size_t bit = candidate.payloads[p].bit_offset;
std::uint32_t value = 0;
for (unsigned index = 0; index < 3u; ++index) {
const std::size_t position = bit + index;
if (position / 8u >= frame_bytes) return false;
value = (value << 1) | ((frame[position / 8u] >> (7u - (position % 8u))) & 1u);
}
*out = value;
return true;
}
}
return false;
}
bool frame_has_joc(const std::uint8_t* frame, std::size_t frame_bytes) {
if (frame == nullptr || frame_bytes < 8u) return false;
std::size_t offsets[4096];
std::size_t count = 0;
marker_offsets(frame, frame_bytes, offsets, 4096, &count);
Container matches[16];
std::size_t match_count = 0;
for (std::size_t i = 0; i < count; ++i) {
Container candidate;
if (!parse_container(frame, frame_bytes * 8u, offsets[i], &candidate)) continue;
if (candidate.has(kIdOamd) && candidate.has(kIdJoc)) {
if (match_count < 16) matches[match_count++] = candidate;
}
}
if (match_count == 0) return false;
// A payload may contain bytes that look like another container; only
// top-level ones count.
Container top_level[16];
std::size_t top_count = 0;
for (std::size_t i = 0; i < match_count; ++i) {
bool nested = false;
for (std::size_t j = 0; j < top_count; ++j) {
if (top_level[j].start_bit < matches[i].start_bit &&
matches[i].start_bit < top_level[j].start_bit + top_level[j].raw_size * 8u) {
nested = true;
break;
}
}
if (!nested && top_count < 16) top_level[top_count++] = matches[i];
}
// Exactly one is what the core requires; more than one is ambiguous there.
return top_count == 1u;
}
ScanResult scan(const std::uint8_t* data, std::size_t size, std::size_t max_frames) {
ScanResult result;
if (data == nullptr || size < 8u) {
result.detail = "buffer too small";
return result;
}
std::size_t offset = 0;
std::size_t frames = 0;
std::size_t with_joc = 0;
bool first = true;
while (frames < max_frames) {
const std::size_t frame_bytes = frame_bytes_at(data, size, offset);
if (frame_bytes == 0) {
result.detail = frames == 0 ? "no E-AC-3 syncword at the start" : "stream walk ended";
break;
}
if (offset + frame_bytes > size) {
result.detail = "buffer ends inside a syncframe";
break;
}
if (first) {
result.first_frame_bytes = frame_bytes;
first = false;
} else if (frame_bytes != result.first_frame_bytes) {
result.all_frames_same_size = false;
}
if (frame_has_joc(data + offset, frame_bytes)) ++with_joc;
++frames;
offset += frame_bytes;
}
result.frames_examined = frames;
result.frames_with_joc = with_joc;
if (frames == 0) {
result.joc = JocState::kUnknown;
if (result.detail[0] == '\0') result.detail = "no syncframes";
} else if (with_joc != 0) {
result.joc = JocState::kYes;
result.detail = (with_joc == frames)
? "every examined syncframe carries the JOC EMDF container"
: "the JOC EMDF container is present in part of the examined "
"audio frames (dependent substream or a late first frame)";
} else {
result.joc = JocState::kNo;
result.detail = "no examined syncframe carries a JOC EMDF container";
}
return result;
}
} // namespace joc_eac3
+83
View File
@@ -0,0 +1,83 @@
// E-AC-3 syncframe walking and JOC detection.
//
// The plugin must decide "is this file E-AC-3 JOC" from the bitstream alone,
// because container metadata (MP4 dec3, Matroska A_EAC3) says only "E-AC-3" and
// the JOC flag inside it is frequently missing.
//
// A syncframe carries JOC when it holds exactly one top-level EMDF container
// (syncword 0x5838, any of the eight bit alignments) whose payload list contains
// both ID11 (OAMD) and ID14 (JOC) — the same per-frame test the rendering core
// applies. The stream counts as JOC when at least one examined audio frame
// carries one: in a 7-channel program the JOC payload lives in the dependent
// substream while the independent substream is a plain 5.1 core, and an AC-3
// core may precede it, so "every syncframe carries JOC" is not a valid rule.
// The first audio frame may also carry no metadata at all.
#pragma once
#include <cstddef>
#include <cstdint>
namespace joc_eac3 {
// Syncframe header fields the plugin needs. codec/strmtyp/substreamid identify
// the substream: within one audio frame each combination appears once, which is
// what turns a syncframe stream into audio frames.
struct FrameHeader {
std::size_t frame_bytes = 0;
std::size_t offset = 0;
std::uint8_t codec = 0; // 0 = AC-3, 1 = E-AC-3
std::uint8_t strmtyp = 0;
std::uint8_t substreamid = 0;
bool same_stream(const FrameHeader& other) const {
return codec == other.codec && strmtyp == other.strmtyp &&
substreamid == other.substreamid;
}
};
enum class JocState {
kYes, // at least one examined syncframe carried a JOC EMDF container
kNo, // no examined syncframe carried one
kUnknown, // not enough data, or the stream is not walkable ac3/eac3
};
struct ScanResult {
JocState joc = JocState::kUnknown;
std::size_t frames_examined = 0;
std::size_t frames_with_joc = 0;
std::size_t first_frame_bytes = 0;
bool all_frames_same_size = true;
const char* detail = "";
};
// Walks up to `max_frames` syncframes of `data` and classifies the stream.
ScanResult scan(const std::uint8_t* data, std::size_t size, std::size_t max_frames);
// Length of the syncframe starting at data[offset], or 0 when there is no valid
// header there. AC-3 and E-AC-3 are told apart by bsid exactly as the core does:
// bsid <= 8 sizes the frame from fscod/frmsizecod, anything above uses frmsiz.
std::size_t frame_bytes_at(const std::uint8_t* data, std::size_t size, std::size_t offset);
// Same, and fills the substream identity. Returns 0 when no header is there.
std::size_t frame_header_at(const std::uint8_t* data, std::size_t size, std::size_t offset,
FrameHeader* out);
// Length of the whole audio frame starting at data[offset]: every syncframe up to
// (and excluding) the first repeated (codec, strmtyp, substreamid) combination.
// A 7-channel program interleaves an independent and a dependent substream, so one
// audio frame is two syncframes and one bed frame.
//
// Returns 0 when the group is still open inside the buffer -- the caller has to ask
// again with more data -- unless `end_of_stream` says no more bytes will arrive, in
// which case the trailing group is complete by definition.
std::size_t audio_frame_bytes_at(const std::uint8_t* data, std::size_t size, std::size_t offset,
bool end_of_stream);
// Reads joc_dmx_config_idx (the first 3 bits of the JOC payload) out of one
// syncframe. False when the frame carries no JOC payload.
bool joc_config_idx(const std::uint8_t* frame, std::size_t frame_bytes, unsigned* out);
// True when this single syncframe carries the JOC EMDF container.
bool frame_has_joc(const std::uint8_t* frame, std::size_t frame_bytes);
} // namespace joc_eac3
+1472
View File
File diff suppressed because it is too large. Load diff
+206
View File
@@ -0,0 +1,206 @@
// Decode engine: E-AC-3 JOC file -> rendered PCM, without any host-specific types.
//
// Kept free of fb2k headers on purpose: the same code is what a headless harness
// drives when the output has to be compared byte for byte against joc_cli.
//
// Two inputs are needed to render, and they come from different places:
// * the E-AC-3 syncframes -- the metadata stream -- read straight from the file;
// * the 5.1 core PCM of those same frames -- the rendering core does not decode
// the core (it has no AC-3 decoder at all), so ffmpeg produces it.
//
// The core is the C++ kernel under kernel/, compiled into this component and called
// through its public C API via the CoreApi table. No DLL is shipped or loaded: the
// table is filled with the linked entry points and start-up only checks the ABI
// version.
#pragma once
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
namespace joc_decode {
// Delay of the rendering pipeline itself, in output samples: in a run that began
// at source sample 0, output sample k carries the rendering of source sample
// k - this value. A seek starts the inputs this much earlier and drops the
// samples before the target. Measured as 0: the renderer's own filter-bank
// latency and its metadata delay are inside the renderer, not delays of the
// delivered stream. It stays a named, overridable constant so the measurement can
// be repeated.
constexpr std::uint32_t kJocSeekPipelineDelaySamples = 0;
// Syncframes fed before the frame the target sits in. The renderer's state is
// rebuilt from the frames it is given, so a restart needs a moment to converge and
// the delivered part has to be past that. Two things converge at different rates:
// the metadata state (object positions, matrix interpolation, gain ramps), which
// the measured 3008-sample window covers, and the binaural room tail, which is
// recursive and can only be approached -- two syncframes are enough for the speaker
// path, and the tail keeps improving with more, which is why this is 64.
constexpr std::uint32_t kJocSeekPrerollFrames = 64;
enum class Output {
kBinaural = 0, // 2 channels, HRTF rendering
kSpeaker = 1, // N channels, named layout
};
// Which HRTF to render with. Both inputs are user-facing model/data files; how
// the renderer gets from them to its internal filter field is its own business.
enum class HrtfSource {
kSofa = 0,
kRosella = 1,
};
// Where the E-AC-3 syncframes come from. A bare stream is read straight from the
// file; inside a container the track has to be extracted first (ffmpeg, stream copy).
enum class InputKind {
kBare = 0,
kContainer = 1,
};
struct Settings {
Output output = Output::kBinaural;
InputKind input_kind = InputKind::kBare;
// Which of the container's audio tracks holds the E-AC-3 stream, 0-based.
unsigned audio_index = 0;
std::string speaker_layout = "7.1";
HrtfSource hrtf_source = HrtfSource::kSofa;
// Empty means the default file in the default folder, see resolve_hrtf_file().
std::string hrtf_file;
std::string hrtf_cache_dir; // SOFA compile cache (disk policy)
unsigned hrtf_cache_policy = 1; // 0 none, 1 memory, 2 disk
double hrtf_radius_m = 1.0; // SOFA measurement-radius shell
std::uint32_t binaural_mode = 3; // JOC_BINAURAL_MID
double gain_db = 0.0;
double tail_seconds = 5.0;
// Duration of the file, in seconds. The renderer ends a binaural stream with a
// room tail, which would be played as time the file does not have; the delivered
// stream is cut at exactly this much audio instead. Zero means "no limit".
double length_seconds = 0.0;
std::uint32_t object_delay_samples = 1473;
std::uint32_t native_threads = 0;
std::string ffmpeg_path = "ffmpeg";
// Where joc_core.dll lives; empty means the renderer's default lookup
// (the plugin's own directory first).
std::string core_path;
// Bytes in front of the first syncframe -- a leading ID3v2 tag. The renderer
// rejects a stream that does not begin on a syncword, so both the walk and the
// feed start here.
std::uint64_t stream_start_bytes = 0;
// Samples of pipeline delay a seek compensates for, and syncframes it pre-rolls
// before the target: the calibrated constants above, unless the comparison
// harness overrides them to measure those constants.
std::uint32_t pipeline_delay_samples = kJocSeekPipelineDelaySamples;
std::uint32_t seek_preroll_frames = kJocSeekPrerollFrames;
// Stop feeding the renderer after this many input syncframes and flush, which
// is what the reference CLI's --duration does. Zero means "the whole file".
// Only the comparison harness sets it; playback leaves it at zero.
std::uint64_t input_frame_limit = 0;
// Deliver 24-bit fixed-point PCM instead of float32. The renderer itself is
// always float32 and this does not change it: the flag says how the *caller*
// hands the samples on, and the quantisation happens once, where the format is
// decided (see pack_int24 below). It exists because the streaming interface
// has no int24 output -- the core's int24 rule lives in its file-writing path
// (kernel/src/io/wav_writer.cpp), which the component cannot reach, so the
// rule is reproduced here instead. Out-of-range samples follow the core's
// JOC_CLIP_CONTINUE policy: truncated to the edge, and reported.
bool force_int24 = false;
};
// Channel count of a named layout, or 0 when the layout is not one of the
// layouts the core accepts.
unsigned speaker_channels(const std::string& layout);
// Directory this component's DLL was loaded from. The default HRTF folder is
// <that directory>\HRTF, the same place the reference CLI looks next to its exe.
std::string component_directory();
// The HRTF file a configuration will actually use: the configured path, or the
// default file in the default folder when none is configured. Empty when the
// component directory cannot be determined.
std::string resolve_hrtf_file(const Settings& settings);
// Every layout the core accepts, in the order a settings page should list them.
const char* const* speaker_layouts(std::size_t* count);
// Result of examining a file without rendering anything.
struct FileProbe {
bool readable = false;
bool joc = false; // every examined syncframe carries JOC
std::uint32_t sample_rate = 0;
std::uint32_t channels = 0; // core 5.1 layout, i.e. 6 (including LFE)
std::uint64_t frames = 0; // E-AC-3 syncframes in the file
double duration_seconds = 0.0;
std::string detail;
};
// Walks the file's syncframes. Cheap enough for a Media Library scan: it only
// does pointer arithmetic over the stream, no decoding, no HRTF work. The walk
// starts at `start_offset`, which is where the stream begins behind a tag area.
FileProbe probe_file(const std::string& path, std::size_t max_scan_bytes = 0,
std::uint64_t start_offset = 0);
// Decides whether the E-AC-3 track of a container file carries JOC, without
// rendering anything: ffmpeg copies a short prefix of that track out (stream copy,
// so the syncframes are the stored ones) and the same bitstream test is applied.
// The verdict is cached per file, because the information and the decode pass would
// otherwise each launch ffmpeg for it.
bool probe_container_joc(const std::string& ffmpeg_path, const std::string& path,
unsigned audio_index, bool* joc, std::string* detail);
// ---- forced int24 delivery ------------------------------------------------
//
// The core's own int24 rule, reproduced byte for byte from
// kernel/src/io/wav_writer.cpp: clip to [-1, 1], multiply by 8388607, truncate
// toward zero (the core's comment: the int32 conversion is "identical to NumPy's
// float32 -> int32 cast after clipping"), write the low three bytes, little
// endian; a non-finite sample becomes 0, exactly as the core writes it.
//
// Sample values that have been through this are what a 24-bit host import
// gives back, i.e. n / 2^23. That is the scale
// a caller should use when it wants to check what the host received.
constexpr double kInt24ImportScale = 8388608.0;
struct Int24Block {
std::size_t clipped = 0; // samples that were outside [-1, 1]
std::int32_t peak = 0; // largest magnitude actually written
};
// Packs `count` interleaved float32 samples into `out`, which must hold
// count * 3 bytes, and reports what the clip caught.
Int24Block pack_int24(const float* interleaved, std::size_t count, std::uint8_t* out);
class Engine {
public:
Engine();
~Engine();
Engine(const Engine&) = delete;
Engine& operator=(const Engine&) = delete;
bool start(const std::string& input_path, const Settings& settings, std::string* error);
// Interleaved float32; returns frames produced per channel, 0 means end of stream.
std::size_t read(float* destination, std::size_t frames, std::string* error);
unsigned channels() const;
void stop();
// Duration of the file, in seconds, for a caller that learns it after start()
// (reported duration of the track); zero means "no limit".
void set_length(double seconds);
// Repositions so that the next sample read() returns is the rendering of source
// sample round(seconds * 48000): the inputs restart at the syncframe holding
// that sample and the output before it is dropped. Seeking at or past
// `total_seconds` (0 when the duration is unknown) succeeds and makes the next
// read() return 0, as the decoder contract requires. start() must have run.
bool seek(double seconds, double total_seconds, std::string* error);
// Polled while the syncframe index is being walked, so a long seek stays
// interruptible; returning false aborts the seek.
void set_abort_check(std::function<bool()> check);
private:
struct Impl;
Impl* impl_;
};
} // namespace joc_decode
+169
View File
@@ -0,0 +1,169 @@
#include "log.h"
#include <windows.h>
#include <cstdarg>
#include <cstdio>
#include <ctime>
#include <mutex>
#include <string>
#include "win_path.h"
namespace joc_log {
namespace {
std::mutex g_mutex;
FILE* g_file = nullptr;
bool g_opened = false;
std::string g_path; // UTF-8, for reporting
std::wstring g_wide_path; // for _wfopen
std::wstring g_wide_rolled; // g_wide_path with the .1 suffix
unsigned long long g_bytes = 0;
// A Media Library scan calls into us for every file it walks, so the cap has to
// be on bytes: the lines a scan produces run from 40 to 2048 bytes each, and a
// cap on their number leaves the file they build unpredictable by a factor of
// fifty. Sixteen mebibytes per file, one previous file kept, so the component
// never holds more than 32 MiB of log.
constexpr unsigned long long kMaxBytes = 16ull << 20;
// The lines recorded between header_begin() and header_end(): the version
// banner, a handful of lines written once per process.
bool g_recording = false;
std::string g_header;
std::wstring module_directory() {
HMODULE module = nullptr;
if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&module_directory), &module)) {
return {};
}
wchar_t buffer[4096] = {};
const DWORD length = GetModuleFileNameW(module, buffer, static_cast<DWORD>(4096));
if (length == 0) return {};
std::wstring dir(buffer, length);
const std::wstring::size_type slash = dir.find_last_of(L"\\/");
if (slash != std::wstring::npos) dir.resize(slash);
return dir;
}
void open_locked() {
g_opened = true;
wchar_t from_env[4096] = {};
const DWORD env_length = GetEnvironmentVariableW(L"JOC_LOG", from_env,
static_cast<DWORD>(4096));
std::wstring plain;
if (env_length > 0 && env_length < 4096) {
plain.assign(from_env, env_length);
} else {
const std::wstring dir = module_directory();
if (dir.empty()) return;
plain = dir + L"\\joc_decoder.log";
}
// g_path is the one the component reports and a user reads; the handles work on
// the extended form, because a portable install can sit deeper than MAX_PATH.
g_path = joc_path::to_utf8(plain);
g_wide_path = joc_path::to_wide_extended(plain);
g_wide_rolled = g_wide_path + L".1";
g_file = _wfopen(g_wide_path.c_str(), L"wb");
if (g_file == nullptr) {
g_path.clear();
return;
}
// Unbuffered: the log stays readable while the process is running.
std::setvbuf(g_file, nullptr, _IONBF, 0);
}
// Composes one line with its timestamp, writes it, and accounts for it. Returns
// the bytes written, 0 when there was nowhere to write them.
unsigned long long write_locked(const char* text) {
if (g_file == nullptr) return 0;
SYSTEMTIME now;
GetLocalTime(&now);
char composed[2100];
const int length =
std::snprintf(composed, sizeof(composed), "%02u:%02u:%02u.%03u [t%05lu] %s\n", now.wHour,
now.wMinute, now.wSecond, now.wMilliseconds,
static_cast<unsigned long>(GetCurrentThreadId()), text);
if (length <= 0) return 0;
// snprintf reports the length it would have needed, which for a truncated
// line is past the end of the buffer.
const std::size_t size = (static_cast<std::size_t>(length) < sizeof(composed))
? static_cast<std::size_t>(length)
: sizeof(composed) - 1;
std::fwrite(composed, 1, size, g_file);
g_bytes += size;
if (g_recording) g_header.append(composed, size);
return size;
}
// Moves the full file aside and starts an empty one. Called with the mutex held,
// once the budget is spent. The banner is written again afterwards, so a log
// that has rolled still opens with the versions it was produced by.
void roll_locked() {
std::fclose(g_file);
g_file = nullptr;
// One previous window, replaced rather than chained: a chain of rolls would
// be the same unbounded log under another name. A move that fails -- the .1
// file held open by a reader -- leaves the truncation below to bound the file
// anyway, at the cost of the window that would have been kept.
MoveFileExW(g_wide_path.c_str(), g_wide_rolled.c_str(), MOVEFILE_REPLACE_EXISTING);
g_file = _wfopen(g_wide_path.c_str(), L"wb");
if (g_file == nullptr) return;
std::setvbuf(g_file, nullptr, _IONBF, 0);
g_bytes = 0;
write_locked("[log rolled: the previous window is in the .1 file beside this one]");
if (!g_header.empty()) {
std::fwrite(g_header.c_str(), 1, g_header.size(), g_file);
g_bytes += g_header.size();
}
}
} // namespace
void open() {
std::lock_guard<std::mutex> guard(g_mutex);
if (!g_opened) open_locked();
}
const char* path() {
std::lock_guard<std::mutex> guard(g_mutex);
return g_path.c_str();
}
unsigned long long budget_bytes() { return kMaxBytes; }
void line_v(const char* fmt, va_list args) {
char text[2048];
std::vsnprintf(text, sizeof(text), fmt, args);
std::lock_guard<std::mutex> guard(g_mutex);
if (!g_opened) open_locked();
if (g_file == nullptr) return;
if (write_locked(text) != 0 && g_bytes >= kMaxBytes) roll_locked();
}
void line(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
line_v(fmt, args);
va_end(args);
}
void header_begin() {
std::lock_guard<std::mutex> guard(g_mutex);
g_header.clear();
g_recording = true;
}
void header_end() {
std::lock_guard<std::mutex> guard(g_mutex);
g_recording = false;
}
} // namespace joc_log
+46
View File
@@ -0,0 +1,46 @@
// Line-oriented diagnostic log for the component.
//
// Deliberately free of SDK/PFC dependencies so it can be reused by the offline
// harness and so that it is safe to call from any thread the core queries us on.
//
// Path: %JOC_LOG% if set, otherwise <directory of this DLL>\joc_decoder.log.
// The file is truncated once per process, unbuffered, and every line is written
// straight out so the log can be read while the host is still running.
//
// Size: what is bounded is bytes, not lines. A line is anywhere between 40 and
// 2048 bytes, so a cap on the number of lines leaves the size of the file
// unpredictable by a factor of fifty. A file that reaches budget_bytes() is
// moved to <path>.1 -- replacing any previous roll, so there is never a chain of
// them -- and a fresh one is started. Two files of the budget is therefore the
// most the component ever holds, and the newest lines are always the ones in
// <path>. Lines written between header_begin() and header_end() are written
// again at the top of every window, so a rolled log still says which build
// produced it.
#pragma once
#include <cstdarg>
namespace joc_log {
// Opens (truncating) the log. Called lazily by line(); call it explicitly to
// get the banner before anything else in the process logs.
void open();
// Absolute path of the log file, or "" when it could not be opened.
const char* path();
// Bytes one file holds before it is rolled to <path>.1.
unsigned long long budget_bytes();
// printf-style, thread safe, appends one line.
void line(const char* fmt, ...);
// The va_list form, for a wrapper that forwards its own arguments.
void line_v(const char* fmt, va_list args);
// Remembers the lines written in between and writes them again after every roll.
// Meant for the version banner: a handful of lines, written once.
void header_begin();
void header_end();
} // namespace joc_log
+130
View File
@@ -0,0 +1,130 @@
#include "audio_source.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include "log.h"
namespace joc_mpv {
namespace {
constexpr std::size_t kBlockFrames = 1536; // one E-AC-3 frame
}
Source::Source() = default;
Source::~Source() { close(); }
bool Source::open(const std::string& path, const joc_decode::Settings& settings,
double duration_seconds, std::string* error) {
close();
std::lock_guard<std::mutex> guard(mutex_);
int24_ = settings.force_int24;
duration_ = duration_seconds;
if (!(duration_ > 0.0)) {
if (error != nullptr) *error = "the input duration is unknown";
return false;
}
if (!engine_.start(path, settings, error)) {
engine_.stop();
return false;
}
channels_ = engine_.channels();
if (channels_ == 0) {
if (error != nullptr) *error = "the renderer produced no output channels";
engine_.stop();
return false;
}
total_samples_ = static_cast<std::uint64_t>(std::llround(duration_ * 48000.0));
produced_bytes_ = 0;
carry_.clear();
skip_bytes_ = 0;
block_.assign(kBlockFrames * channels_, 0.0f);
if (int24_) packed_.assign(kBlockFrames * channels_ * 3u, 0);
open_ = true;
return true;
}
void Source::close() {
std::lock_guard<std::mutex> guard(mutex_);
if (open_) engine_.stop();
open_ = false;
channels_ = 0;
total_samples_ = 0;
produced_bytes_ = 0;
carry_.clear();
skip_bytes_ = 0;
}
std::size_t Source::read(std::uint64_t data_byte_offset, std::uint8_t* out, std::size_t count,
std::string* error) {
std::lock_guard<std::mutex> guard(mutex_);
if (!open_) {
if (error != nullptr) *error = "the renderer is not running";
return 0;
}
const std::uint64_t total = data_bytes();
if (data_byte_offset >= total) return 0;
count = static_cast<std::size_t>(std::min<std::uint64_t>(count, total - data_byte_offset));
const unsigned frame_bytes = bytes_per_frame();
// What the renderer has produced but the caller has not taken yet.
const std::uint64_t deliverable = produced_bytes_ - carry_.size();
if (data_byte_offset != deliverable) {
const std::uint64_t sample = data_byte_offset / frame_bytes;
const std::size_t intra = static_cast<std::size_t>(data_byte_offset % frame_bytes);
joc_log::line("source: reposition to sample %llu (was byte %llu, byte %llu)",
static_cast<unsigned long long>(sample),
static_cast<unsigned long long>(deliverable),
static_cast<unsigned long long>(data_byte_offset));
if (!engine_.seek(static_cast<double>(sample) / 48000.0, duration_, error)) return 0;
produced_bytes_ = sample * frame_bytes;
carry_.clear();
skip_bytes_ = intra;
}
std::size_t written = 0;
// Leftovers from an earlier block come first: a block is a whole number of
// frames and the caller may have asked for a smaller piece.
if (!carry_.empty()) {
const std::size_t take = std::min(count, carry_.size());
std::memcpy(out, carry_.data(), take);
carry_.erase(carry_.begin(), carry_.begin() + static_cast<std::ptrdiff_t>(take));
written += take;
}
while (written < count) {
const std::uint64_t remaining_samples = total_samples_ - produced_bytes_ / frame_bytes;
if (remaining_samples == 0) break;
const std::size_t want =
static_cast<std::size_t>(std::min<std::uint64_t>(kBlockFrames, remaining_samples));
const std::size_t got = engine_.read(block_.data(), want, error);
if (got == 0) break;
produced_bytes_ += static_cast<std::uint64_t>(got) * frame_bytes;
std::size_t produced = 0;
const std::uint8_t* source = nullptr;
if (int24_) {
joc_decode::pack_int24(block_.data(), got * channels_, packed_.data());
produced = got * channels_ * 3u;
source = packed_.data();
} else {
produced = got * channels_ * sizeof(float);
source = reinterpret_cast<const std::uint8_t*>(block_.data());
}
std::size_t skip = 0;
if (skip_bytes_ != 0) {
skip = std::min(skip_bytes_, produced);
skip_bytes_ -= skip;
}
const std::size_t available = produced - skip;
const std::size_t take = std::min(count - written, available);
std::memcpy(out + written, source + skip, take);
written += take;
if (take < available) {
carry_.assign(source + skip + take, source + produced);
}
}
return written;
}
} // namespace joc_mpv
+58
View File
@@ -0,0 +1,58 @@
#pragma once
#include <cstdint>
#include <mutex>
#include <string>
#include <vector>
#include "joc_decode.h"
namespace joc_mpv {
// Rendered audio as a seekable byte stream: the HTTP server asks for a byte
// range of the WAV data chunk, this maps it to a sample index, repositions the
// engine when the request does not continue where the last one stopped, and
// returns the requested bytes.
class Source {
public:
Source();
~Source();
Source(const Source&) = delete;
Source& operator=(const Source&) = delete;
bool open(const std::string& path, const joc_decode::Settings& settings, double duration_seconds,
std::string* error);
void close();
unsigned channels() const { return channels_; }
unsigned bits_per_sample() const { return int24_ ? 24u : 32u; }
unsigned bytes_per_frame() const { return channels_ * (bits_per_sample() / 8u); }
std::uint64_t total_samples() const { return total_samples_; }
std::uint64_t data_bytes() const { return total_samples_ * bytes_per_frame(); }
double duration_seconds() const { return duration_; }
// Fills up to count bytes of the data chunk starting at data_byte_offset.
std::size_t read(std::uint64_t data_byte_offset, std::uint8_t* out, std::size_t count,
std::string* error);
private:
std::mutex mutex_;
joc_decode::Engine engine_;
bool open_ = false;
bool int24_ = false;
unsigned channels_ = 0;
double duration_ = 0.0;
std::uint64_t total_samples_ = 0;
// Bytes the renderer has produced since the last reposition, counted from
// the start of the data chunk. Tracking bytes rather than samples keeps a
// request that starts inside a frame from forcing a reposition on every
// following read.
std::uint64_t produced_bytes_ = 0;
// Bytes produced by the renderer that the caller did not ask for yet.
std::vector<std::uint8_t> carry_;
std::size_t skip_bytes_ = 0;
std::vector<float> block_;
std::vector<std::uint8_t> packed_;
};
} // namespace joc_mpv
+150
View File
@@ -0,0 +1,150 @@
#include "config.h"
#include <cstdlib>
#include <cstring>
#include <map>
#include <sstream>
namespace joc_mpv {
namespace {
std::string trim(const std::string& value) {
std::size_t first = 0;
std::size_t last = value.size();
while (first < last && (value[first] == ' ' || value[first] == '\t')) ++first;
while (last > first && (value[last - 1] == ' ' || value[last - 1] == '\t')) --last;
return value.substr(first, last - first);
}
std::string unquote(const std::string& value) {
if (value.size() >= 2 && ((value.front() == '"' && value.back() == '"') ||
(value.front() == '\'' && value.back() == '\''))) {
return value.substr(1, value.size() - 2);
}
return value;
}
bool truthy(const std::string& value) {
return value == "1" || value == "yes" || value == "true" || value == "on";
}
// The layout names the renderer accepts, in the order its reference lists them.
const char* const kLayouts[] = {"2.0", "3.1", "5.1", "7.1", "5.1.2",
"5.1.4", "7.1.2", "7.1.4", "9.1.4", "9.1.6"};
} // namespace
const char* layout_list() {
return "2.0, 3.1, 5.1, 7.1, 5.1.2, 5.1.4, 7.1.2, 7.1.4, 9.1.4, 9.1.6";
}
bool valid_layout(const std::string& layout) {
for (const char* name : kLayouts) {
if (layout == name) return true;
}
return false;
}
Config parse_config(const std::string& script_opts, std::string* warnings) {
Config config;
std::map<std::string, std::string> options;
std::size_t start = 0;
while (start <= script_opts.size()) {
std::size_t comma = script_opts.find(',', start);
if (comma == std::string::npos) comma = script_opts.size();
const std::string item = trim(script_opts.substr(start, comma - start));
const std::size_t equals = item.find('=');
if (equals != std::string::npos) {
options[trim(item.substr(0, equals))] = unquote(trim(item.substr(equals + 1)));
}
if (comma == script_opts.size()) break;
start = comma + 1;
}
auto unsupported = [warnings](const std::string& key) {
if (warnings != nullptr) {
if (!warnings->empty()) warnings->append("; ");
warnings->append("unknown option " + key);
}
};
for (const auto& entry : options) {
const std::string& key = entry.first;
const std::string& value = entry.second;
if (key == "joc-enabled") {
config.enabled = truthy(value);
} else if (key == "joc-output") {
if (value == "binaural" || value == "2ch" || value == "0") {
config.output = 0;
} else if (value == "speaker" || value == "1") {
config.output = 1;
} else {
unsupported(key + "=" + value);
}
} else if (key == "joc-layout") {
if (valid_layout(value)) {
config.layout = value;
} else {
unsupported(key + "=" + value);
}
} else if (key == "joc-hrtf-source") {
if (value == "sofa") {
config.hrtf_source = 0;
} else if (value == "rosella" || value == "personalized") {
config.hrtf_source = 1;
} else {
unsupported(key + "=" + value);
}
} else if (key == "joc-hrtf") {
config.hrtf_file = value;
} else if (key == "joc-mode") {
if (value == "near") config.binaural_mode = 1;
else if (value == "far") config.binaural_mode = 2;
else if (value == "mid") config.binaural_mode = 3;
else unsupported(key + "=" + value);
} else if (key == "joc-gain-db") {
config.gain_db = std::atof(value.c_str());
} else if (key == "joc-tail") {
config.tail_seconds = std::atof(value.c_str());
} else if (key == "joc-int24") {
config.force_int24 = truthy(value);
} else if (key == "joc-object-delay") {
config.object_delay_samples = static_cast<unsigned>(std::strtoul(value.c_str(), nullptr, 10));
} else if (key == "joc-threads") {
config.native_threads = static_cast<unsigned>(std::strtoul(value.c_str(), nullptr, 10));
} else if (key == "joc-ffmpeg") {
config.ffmpeg = value;
} else if (key == "joc-core") {
config.core_dll = value;
} else if (key == "joc-wasapi") {
if (value == "auto" || value == "yes" || value == "no") config.wasapi = value;
else unsupported(key + "=" + value);
} else if (key == "joc-exclusive") {
config.exclusive = truthy(value);
} else if (key == "joc-verbose") {
config.verbose = truthy(value);
} else if (key == "joc-attach") {
config.attach = truthy(value);
} else if (key == "joc-log") {
config.log_path = value;
} else if (key == "joc-mute-until-ready") {
config.mute_until_ready = truthy(value);
} else if (key == "joc-hrtf-cache") {
if (value == "auto" || value == "memory" || value == "disk" || value == "none") {
config.hrtf_cache = value;
} else {
unsupported(key + "=" + value);
}
} else if (key == "joc-hrtf-cache-dir") {
config.hrtf_cache_dir = value;
} else if (key == "joc-chunk") {
const double seconds = std::atof(value.c_str());
config.chunk_seconds = (seconds >= 0.25 && seconds <= 10.0) ? seconds : 2.0;
} else {
unsupported(key);
}
}
return config;
}
} // namespace joc_mpv
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include <string>
namespace joc_mpv {
// Everything the plugin can be told through mpv's own configuration file:
// script-opts keys are "joc-<name>=<value>" (see config/mpv.conf.example).
struct Config {
bool enabled = true;
// 0 = binaural (2 channels), 1 = speaker layout (N channels).
int output = 0;
std::string layout = "7.1";
// 0 = SOFA, 1 = Rosella personalized headphone model.
int hrtf_source = 0;
std::string hrtf_file; // empty: <plugin dir>\\HRTF\\binaural.<ext>
// 1 = near, 2 = far, 3 = mid (the renderer's own default).
int binaural_mode = 3;
double gain_db = 0.0;
double tail_seconds = 5.0;
bool force_int24 = false;
unsigned object_delay_samples = 1473;
unsigned native_threads = 0;
std::string ffmpeg = "ffmpeg";
std::string core_dll; // empty: <plugin dir>\\joc_core.dll
// auto: leave mpv's audio output alone; yes: force the WASAPI AO.
std::string wasapi = "auto";
bool exclusive = false;
bool verbose = false;
// no = serve the rendered stream without adding it to the player; used to
// capture exactly what the plugin would deliver, and for debugging.
bool attach = true;
// Silence the file's own audio track until the rendered one is selected, so
// the opening moments are not the plain bed. Only candidate inputs are
// muted, and only for as long as the probe takes.
bool mute_until_ready = true;
// SOFA compilation cache: auto (disk under the mpv config directory, memory
// if that is unavailable), memory, disk, none.
std::string hrtf_cache = "auto";
std::string hrtf_cache_dir;
// Log file path; empty means <mpv config dir>\joc_decoder.log.
std::string log_path;
// Samples requested per HTTP response, in seconds of audio. A bounded
// response makes mpv come back with a fresh range request after a seek
// instead of reading through everything in between.
double chunk_seconds = 2.0;
};
// Parses mpv's script-opts value ("joc-output=binaural,joc-hrtf=..."); unknown
// keys are ignored so an mpv.conf written for a newer build still loads.
Config parse_config(const std::string& script_opts, std::string* warnings);
const char* layout_list();
bool valid_layout(const std::string& layout);
} // namespace joc_mpv
+222
View File
@@ -0,0 +1,222 @@
#include "http_server.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
namespace joc_mpv {
namespace {
bool winsock_ready() {
static const bool ready = [] {
WSADATA data{};
return WSAStartup(MAKEWORD(2, 2), &data) == 0;
}();
return ready;
}
std::string lower(std::string text) {
for (char& ch : text) {
if (ch >= 'A' && ch <= 'Z') ch = static_cast<char>(ch - 'A' + 'a');
}
return text;
}
const char* status_text(int status) {
switch (status) {
case 200: return "OK";
case 206: return "Partial Content";
case 400: return "Bad Request";
case 404: return "Not Found";
case 416: return "Range Not Satisfiable";
default: return "Internal Server Error";
}
}
bool send_all(SOCKET socket, const char* data, std::size_t size) {
while (size > 0) {
const int chunk = static_cast<int>(std::min<std::size_t>(size, 1u << 20));
const int sent = ::send(socket, data, chunk, 0);
if (sent <= 0) return false;
data += sent;
size -= static_cast<std::size_t>(sent);
}
return true;
}
} // namespace
bool ResponseWriter::write(const void* data, std::size_t size) {
if (!ok_) return false;
char header[32];
const int header_length = std::snprintf(header, sizeof(header), "%zx\r\n", size);
if (!send_all(static_cast<SOCKET>(socket_), header, static_cast<std::size_t>(header_length)) ||
!send_all(static_cast<SOCKET>(socket_), static_cast<const char*>(data), size) ||
!send_all(static_cast<SOCKET>(socket_), "\r\n", 2)) {
ok_ = false;
return false;
}
return true;
}
HttpServer::~HttpServer() { stop(); }
bool HttpServer::start(HttpHandler handler, unsigned short* port, std::string* error) {
if (running_) return true;
if (!winsock_ready()) {
if (error != nullptr) *error = "Winsock failed to initialize";
return false;
}
handler_ = std::move(handler);
const SOCKET listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listener == INVALID_SOCKET) {
if (error != nullptr) *error = "cannot create the audio socket";
return false;
}
BOOL reuse = TRUE;
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&reuse),
sizeof(reuse));
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
address.sin_port = 0;
if (::bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0 ||
::listen(listener, 8) != 0) {
closesocket(listener);
if (error != nullptr) *error = "cannot bind the loopback audio port";
return false;
}
sockaddr_in bound{};
int length = sizeof(bound);
if (getsockname(listener, reinterpret_cast<sockaddr*>(&bound), &length) == 0 && port != nullptr) {
*port = ntohs(bound.sin_port);
}
listener_ = static_cast<std::uintptr_t>(listener);
running_ = true;
thread_ = std::thread(&HttpServer::accept_loop, this);
return true;
}
void HttpServer::stop() {
if (!running_) return;
running_ = false;
const SOCKET listener = static_cast<SOCKET>(listener_);
listener_ = ~static_cast<std::uintptr_t>(0);
closesocket(listener);
if (thread_.joinable()) thread_.join();
// Connection threads end when their socket fails or the source is closed;
// joining them keeps the handler and the source alive until then.
for (std::thread& worker : workers_) {
if (worker.joinable()) worker.join();
}
workers_.clear();
handler_ = nullptr;
}
void HttpServer::accept_loop() {
const SOCKET listener = static_cast<SOCKET>(listener_);
while (running_) {
const SOCKET client = ::accept(listener, nullptr, nullptr);
if (client == INVALID_SOCKET) {
if (!running_) break;
continue;
}
DWORD timeout = 5000;
setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeout),
sizeof(timeout));
setsockopt(client, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&timeout),
sizeof(timeout));
workers_.emplace_back(&HttpServer::serve, this, static_cast<std::uintptr_t>(client));
}
}
void HttpServer::serve(std::uintptr_t client_value) {
const SOCKET client = static_cast<SOCKET>(client_value);
std::string request;
char buffer[2048];
while (request.find("\r\n\r\n") == std::string::npos) {
const int got = ::recv(client, buffer, sizeof(buffer), 0);
if (got <= 0) {
closesocket(client);
return;
}
request.append(buffer, static_cast<std::size_t>(got));
if (request.size() > 16384) {
closesocket(client);
return;
}
}
HttpRequest parsed;
std::size_t line_end = request.find("\r\n");
if (line_end != std::string::npos) {
const std::string line = request.substr(0, line_end);
const std::size_t first = line.find(' ');
const std::size_t second = (first == std::string::npos) ? std::string::npos
: line.find(' ', first + 1);
if (first != std::string::npos && second != std::string::npos) {
parsed.method = line.substr(0, first);
parsed.target = line.substr(first + 1, second - first - 1);
}
std::size_t position = line_end + 2;
while (position < request.size()) {
const std::size_t end = request.find("\r\n", position);
if (end == std::string::npos) break;
const std::string header_line = request.substr(position, end - position);
position = end + 2;
if (header_line.empty()) break;
const std::size_t colon = header_line.find(':');
if (colon == std::string::npos) continue;
const std::string name = lower(header_line.substr(0, colon));
std::string value = header_line.substr(colon + 1);
while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) {
value.erase(0, 1);
}
if (name != "range" || value.compare(0, 6, "bytes=") != 0) continue;
value.erase(0, 6);
const std::size_t dash = value.find('-');
if (dash == std::string::npos) continue;
const std::string first_text = value.substr(0, dash);
const std::string last_text = value.substr(dash + 1);
if (first_text.empty()) continue; // suffix ranges are not used by mpv
parsed.has_range = true;
parsed.range_start = std::strtoull(first_text.c_str(), nullptr, 10);
if (!last_text.empty()) {
parsed.has_range_end = true;
parsed.range_end = std::strtoull(last_text.c_str(), nullptr, 10);
}
}
}
HttpResponse response;
if (handler_) handler_(parsed, &response);
else response.status = 404;
std::string head;
head += "HTTP/1.1 " + std::to_string(response.status) + " " + status_text(response.status) +
"\r\n";
head += response.headers;
if (response.stream) {
head += "Transfer-Encoding: chunked\r\n";
} else {
head += "Content-Length: " + std::to_string(response.body.size()) + "\r\n";
}
head += "Connection: close\r\n\r\n";
if (send_all(client, head.data(), head.size())) {
if (response.stream) {
ResponseWriter writer(static_cast<std::uintptr_t>(client));
response.stream(writer);
send_all(client, "0\r\n\r\n", 5);
} else {
send_all(client, response.body.data(), response.body.size());
}
}
closesocket(client);
}
} // namespace joc_mpv
+66
View File
@@ -0,0 +1,66 @@
#pragma once
#include <cstdint>
#include <functional>
#include <string>
#include <thread>
#include <vector>
namespace joc_mpv {
struct HttpRequest {
std::string method;
std::string target;
bool has_range = false;
std::uint64_t range_start = 0;
std::uint64_t range_end = 0; // inclusive
bool has_range_end = false;
};
// Writer handed to a streaming response: every write() becomes one HTTP chunk.
class ResponseWriter {
public:
explicit ResponseWriter(std::uintptr_t socket) : socket_(socket) {}
bool write(const void* data, std::size_t size);
bool ok() const { return ok_; }
private:
std::uintptr_t socket_;
bool ok_ = true;
};
struct HttpResponse {
int status = 200;
std::string headers; // one "Name: value\r\n" per line
std::string body; // used when stream is empty
// Set for a chunked response: the server sends the headers, then calls this
// with a writer that frames the data, then terminates the chunked body.
std::function<void(ResponseWriter&)> stream;
};
using HttpHandler = std::function<void(const HttpRequest&, HttpResponse*)>;
// Minimal HTTP/1.1 server on 127.0.0.1 serving one resource with byte ranges.
// A seekable, continuously streaming audio source is what lets mpv's own
// demuxer, cache, A/V sync, WASAPI output and seeking keep working unmodified.
class HttpServer {
public:
HttpServer() = default;
~HttpServer();
HttpServer(const HttpServer&) = delete;
HttpServer& operator=(const HttpServer&) = delete;
bool start(HttpHandler handler, unsigned short* port, std::string* error);
void stop();
private:
void accept_loop();
void serve(std::uintptr_t client_socket);
HttpHandler handler_;
std::uintptr_t listener_ = ~static_cast<std::uintptr_t>(0);
std::thread thread_;
std::vector<std::thread> workers_;
bool running_ = false;
};
} // namespace joc_mpv
+116
View File
@@ -0,0 +1,116 @@
#include "wav.h"
#include <cstring>
namespace joc_mpv {
namespace {
constexpr std::uint32_t kFl = 0x00000001u;
constexpr std::uint32_t kFr = 0x00000002u;
constexpr std::uint32_t kFc = 0x00000004u;
constexpr std::uint32_t kLfe = 0x00000008u;
constexpr std::uint32_t kBl = 0x00000010u;
constexpr std::uint32_t kBr = 0x00000020u;
constexpr std::uint32_t kSl = 0x00000200u;
constexpr std::uint32_t kSr = 0x00000400u;
constexpr std::uint32_t kTfl = 0x00001000u;
constexpr std::uint32_t kTfr = 0x00004000u;
constexpr std::uint32_t kTbl = 0x00008000u;
constexpr std::uint32_t kTbr = 0x00020000u;
void put_u16(std::string* out, std::uint16_t value) {
char bytes[2];
std::memcpy(bytes, &value, 2);
out->append(bytes, 2);
}
void put_u32(std::string* out, std::uint32_t value) {
char bytes[4];
std::memcpy(bytes, &value, 4);
out->append(bytes, 4);
}
void put_u64(std::string* out, std::uint64_t value) {
char bytes[8];
std::memcpy(bytes, &value, 8);
out->append(bytes, 8);
}
// KSDATAFORMAT_SUBTYPE_IEEE_FLOAT / PCM, as written by every WAV writer.
void put_subformat(std::string* out, bool is_float) {
put_u32(out, is_float ? 3u : 1u);
put_u16(out, 0x0000);
put_u16(out, 0x0010);
const unsigned char tail[8] = {0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71};
out->append(reinterpret_cast<const char*>(tail), 8);
}
void put_fmt(std::string* out, unsigned channels, unsigned bits, std::uint32_t mask) {
const std::uint32_t rate = 48000;
const std::uint32_t block_align = channels * (bits / 8u);
out->append("fmt ", 4);
put_u32(out, 40);
put_u16(out, 0xFFFE); // WAVE_FORMAT_EXTENSIBLE
put_u16(out, static_cast<std::uint16_t>(channels));
put_u32(out, rate);
put_u32(out, rate * block_align);
put_u16(out, static_cast<std::uint16_t>(block_align));
put_u16(out, static_cast<std::uint16_t>(bits));
put_u16(out, 22); // cbSize
put_u16(out, static_cast<std::uint16_t>(bits));
put_u32(out, mask);
put_subformat(out, bits == 32);
}
} // namespace
std::uint32_t channel_mask(const std::string& layout, unsigned channels) {
if (layout == "2.0") return kFl | kFr;
if (layout == "3.1") return kFl | kFr | kFc | kLfe;
if (layout == "5.1") return kFl | kFr | kFc | kLfe | kBl | kBr;
if (layout == "7.1") return kFl | kFr | kFc | kLfe | kBl | kBr | kSl | kSr;
if (layout == "5.1.2") return kFl | kFr | kFc | kLfe | kBl | kBr | kTfl | kTfr;
if (layout == "5.1.4") {
return kFl | kFr | kFc | kLfe | kBl | kBr | kTfl | kTfr | kTbl | kTbr;
}
if (layout == "7.1.2") {
return kFl | kFr | kFc | kLfe | kBl | kBr | kSl | kSr | kTfl | kTfr;
}
if (layout == "7.1.4") {
return kFl | kFr | kFc | kLfe | kBl | kBr | kSl | kSr | kTfl | kTfr | kTbl | kTbr;
}
// 2-channel binaural output is plain stereo.
if (channels == 2) return kFl | kFr;
return 0;
}
std::string wav_header(unsigned channels, unsigned bits_per_sample, std::uint32_t mask,
std::uint64_t data_bytes) {
std::string out;
const bool rf64 = (data_bytes + 128u) > 0xFFFFFFFFull;
if (!rf64) {
out.append("RIFF", 4);
put_u32(&out, static_cast<std::uint32_t>(data_bytes + 60u));
out.append("WAVE", 4);
put_fmt(&out, channels, bits_per_sample, mask);
out.append("data", 4);
put_u32(&out, static_cast<std::uint32_t>(data_bytes));
return out;
}
// RF64: the 64-bit sizes live in ds64 and the 32-bit fields are all ones.
out.append("RF64", 4);
put_u32(&out, 0xFFFFFFFFu);
out.append("WAVE", 4);
out.append("ds64", 4);
put_u32(&out, 28);
put_u64(&out, data_bytes + 96u); // file size - 8
put_u64(&out, data_bytes);
put_u64(&out, channels == 0 ? 0 : data_bytes / (channels * (bits_per_sample / 8u)));
put_u32(&out, 0); // no table entries
put_fmt(&out, channels, bits_per_sample, mask);
out.append("data", 4);
put_u32(&out, 0xFFFFFFFFu);
return out;
}
} // namespace joc_mpv
+19
View File
@@ -0,0 +1,19 @@
#pragma once
#include <cstdint>
#include <string>
namespace joc_mpv {
// Channel mask for a layout the renderer can produce. The renderer emits its
// channels in the standard WAVE order for that layout, so a WAVE_FORMAT_EXTENSIBLE
// mask tells mpv exactly which speaker each channel belongs to. Layouts wider
// than 7.1 return 0 (no mask): they cannot reach a WASAPI endpoint anyway.
std::uint32_t channel_mask(const std::string& layout, unsigned channels);
// 68-byte WAVE_FORMAT_EXTENSIBLE header, or a 104-byte RF64 header when the data
// chunk would not fit a 32-bit size.
std::string wav_header(unsigned channels, unsigned bits_per_sample, std::uint32_t mask,
std::uint64_t data_bytes);
} // namespace joc_mpv
+90
View File
@@ -0,0 +1,90 @@
// Paths handed to the Win32 file APIs.
//
// Windows refuses a path of MAX_PATH characters or more to any call that does not
// carry the \\?\ prefix. The prefix is a property of the path, not of the process:
// a component cannot inherit it from the host's manifest, so whoever calls the API
// has to add it. A file that plays from the desktop therefore stops being found
// once its folder tree is deep enough, which is what this header exists to prevent.
//
// Everything in this component that hands a path to Win32 -- or puts one on an
// ffmpeg command line, which is the same call made by the child process -- goes
// through to_wide_extended(). What is deliberately not routed through it is the
// path the component keeps for itself: the one it logs, and the one it uses as the
// container-probe cache key. Those stay in their plain form, so a log line reads
// like a path a user can paste into Explorer.
#pragma once
#include <windows.h>
#include <string>
namespace joc_path {
// UTF-8 -> UTF-16, for the W APIs. Every path crosses into the OS through here:
// the narrow CRT would convert it through the ANSI code page, which is what breaks
// names like "Les Fêtes d'Hébé".
inline std::wstring to_wide(const std::string& utf8) {
if (utf8.empty()) return {};
const int needed = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
static_cast<int>(utf8.size()), nullptr, 0);
if (needed <= 0) return {};
std::wstring out(static_cast<std::size_t>(needed), L'\0');
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), static_cast<int>(utf8.size()), out.data(),
needed);
return out;
}
// The same path in the form the Win32 file APIs need. Three kinds of path are left
// exactly as they came in, and each of them would be broken by a prefix:
//
// * one that already carries \\?\, which makes this idempotent;
// * one that is not fully qualified -- a relative path, or the ffmpeg setting
// when it is a bare executable name that PATH resolves. \\?\ is undefined for
// those;
// * one with a "." or ".." segment, because \\?\ switches off the normalization
// that would resolve it.
//
// The separators are settled first for the same reason: once the prefix is on,
// nothing turns a forward slash into a backslash any more, and both of the checks
// above have to see the path the way the file system will.
inline std::wstring to_wide_extended(const std::wstring& path) {
if (path.empty()) return path;
if (path.compare(0, 4, L"\\\\?\\") == 0) return path;
std::wstring plain = path;
for (wchar_t& character : plain) {
if (character == L'/') character = L'\\';
}
const bool unc = plain.size() >= 2 && plain[0] == L'\\' && plain[1] == L'\\';
const bool drive = plain.size() >= 3 && plain[1] == L':' && plain[2] == L'\\';
if (!unc && !drive) return path;
if (plain.find(L"\\.\\") != std::wstring::npos ||
plain.find(L"\\..\\") != std::wstring::npos) {
return path;
}
// A UNC path drops its two leading separators; everything else is copied whole.
std::wstring out = unc ? L"\\\\?\\UNC\\" : L"\\\\?\\";
out.append(plain, unc ? 2 : 0, std::wstring::npos);
return out;
}
inline std::wstring to_wide_extended(const std::string& utf8) {
return to_wide_extended(to_wide(utf8));
}
// UTF-16 -> UTF-8, the direction the component reports paths in.
inline std::string to_utf8(const std::wstring& wide) {
if (wide.empty()) return {};
const int needed = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(),
static_cast<int>(wide.size()), nullptr, 0, nullptr,
nullptr);
if (needed <= 0) return {};
std::string out(static_cast<std::string::size_type>(needed), '\0');
WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()), out.data(),
needed, nullptr, nullptr);
return out;
}
} // namespace joc_path