Sync source edition with VCC Plus 3.7.0 build 63

This commit is contained in:
Brian Holman committed 2026-11-14 01:43:46 -07:00
1 parent c652a5276d
commit b2ecec4d87
86 files changed
+10519 -472

No files matched your search

@@ -85,6 +85,29 @@ static NSArray<NSDictionary *> *MCPBuildDiagnosticTools() {
@"annotations":@{@"readOnlyHint":@YES,@"openWorldHint":@NO}}];
}
static NSArray<NSDictionary *> *MCPPlaytestVideoTools() {
NSDictionary *identifier = @{ @"type":@"string", @"minLength":@1, @"maxLength":@64 };
NSDictionary *(^tool)(NSString *, NSString *, NSDictionary *, NSArray *, BOOL) =
^NSDictionary *(NSString *name, NSString *description, NSDictionary *fields, NSArray *required, BOOL readOnly) {
return @{ @"name":name, @"description":description,
@"inputSchema":@{ @"type":@"object", @"properties":fields, @"required":required, @"additionalProperties":@NO },
@"annotations":@{ @"readOnlyHint":@(readOnly), @"openWorldHint":@NO } };
};
return @[
tool(@"start_playtest_video", @"Start a bounded MP4 recording of an owned disposable playtest's actual CoCo picture and optional generated CoCo audio. Does not advance execution: use ordinary playtest_input afterward. No microphone, Mac windows, personal emulator audio or capture UI cues are recorded. Maximum 3600 emulated fields (60 seconds), 64 MiB per clip, four clips and 256 MiB retained per run. Reuse an identical request_id on retry. Recordings end at their field/size limit with explicit truncation status; stop and retrieve the completed clip before restarting.",
@{ @"run_id":identifier, @"request_id":identifier, @"include_audio":@{ @"type":@"boolean", @"default":@YES },
@"max_fields":@{ @"type":@"integer", @"minimum":@1, @"maximum":@3600, @"default":@1800 } },
@[@"run_id", @"request_id"], NO),
tool(@"stop_playtest_video", @"Finish the current owned playtest recording without advancing the guest. Returns completed MP4 identity, byte count, SHA-256, actual field interval and truncation status. Retrying the identical request_id returns the same receipt. Remains available when ordinary mutation requests are exhausted; working files are retained if finalization fails.",
@{ @"run_id":identifier, @"request_id":identifier }, @[@"run_id", @"request_id"], NO),
tool(@"read_playtest_video", @"Read a completed MP4 belonging to this owned playtest in bounded base64 chunks. Assemble the chunks in offset order and verify the complete byte_count and SHA-256 from the receipt. Accepts only a clip_id returned by this run, never a host file path. Does not advance or change the guest.",
@{ @"run_id":identifier, @"clip_id":identifier,
@"offset":@{ @"type":@"integer", @"minimum":@0, @"maximum":@67108864, @"default":@0 },
@"limit":@{ @"type":@"integer", @"minimum":@1, @"maximum":@65536, @"default":@65536 } },
@[@"run_id", @"clip_id"], YES)
];
}
static NSArray<NSDictionary *> *MCPPlaytestAudioTools() {
return @[@{@"name":@"capture_playtest_audio", @"description":@"Advance an owned disposable guest for 1 to 120 emulated fields and return its direct audio as PCM16 stereo WAV. Leaves the guest paused; verified stops can shorten the interval. Uses no microphone or personal emulator audio. Reuse request_id on retry to return the same clip without execution. Maximum 16 clips and 4 MiB retained WAV per run across boots; a maximum-clip allowance must remain before capture. Receipts include actual field interval, boot/run/artifact identity, sample count and SHA-256.",
@"inputSchema":@{@"type":@"object", @"properties":@{
+22 -1
View File
@@ -114,7 +114,7 @@ NSDictionary *hostCall(NSDictionary *grant, bool loopback, NSString *tool, NSDic
Descriptor peer(socket(address->sa_family, SOCK_STREAM, 0));
const bool playtestCall = [@[@"start_playtest", @"playtest_input", @"playtest_debug", @"capture_playtest",
@"restart_playtest", @"stop_playtest", @"get_debug_snapshot", @"capture_playtest_graphics",
@"exchange_playtest_media"] containsObject:tool];
@"exchange_playtest_media", @"start_playtest_video", @"stop_playtest_video"] containsObject:tool];
const auto deadline = Clock::now() + std::chrono::seconds(playtestCall ? 55 : 5);
if (peer.fd < 0 || fcntl(peer.fd, F_SETFL, O_NONBLOCK) < 0) return @{@"error":@"host_unavailable"};
if (connect(peer.fd, address, address->sa_len) != 0) {
@@ -381,6 +381,23 @@ NSDictionary *handle(id message, NSDictionary *grant, bool loopback, NSArray *to
}
NSMutableDictionary *data = [reply[@"result"] mutableCopy];
NSMutableArray *content = [NSMutableArray array];
if ([name isEqual:@"read_playtest_video"]) {
NSString *encoded = data[@"video_chunk_base64"], *hash = data[@"sha256"];
if (!string(encoded) || encoded.length > 87384 || !string(hash) || hash.length != 64 ||
[hash rangeOfCharacterFromSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdef"] invertedSet]].location != NSNotFound ||
![data[@"mime_type"] isEqual:@"video/mp4"] || ![data[@"clip_id"] isEqual:args[@"clip_id"]] ||
!integer(data[@"offset"]) || !integer(data[@"next_offset"]) || !integer(data[@"byte_count"]) ||
![data[@"eof"] isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)data[@"eof"]) != CFBooleanGetTypeID())
return toolError(rid, @"invalid_playtest_video");
NSData *chunk = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
const long long offset = [data[@"offset"] longLongValue], next = [data[@"next_offset"] longLongValue], total = [data[@"byte_count"] longLongValue];
const long long requestedOffset = args[@"offset"] ? [args[@"offset"] longLongValue] : 0;
const NSUInteger limit = args[@"limit"] ? [args[@"limit"] unsignedIntegerValue] : 65536;
if (!chunk || chunk.length > limit || chunk.length > 65536 || offset != requestedOffset || offset < 0 ||
total < 1 || total > 67108864 || offset > total || next != offset + (long long)chunk.length || next > total ||
[data[@"eof"] boolValue] != (next == total) || (!chunk.length && next < total))
return toolError(rid, @"invalid_playtest_video");
}
if ([name isEqual:@"capture_playtest_audio"]) {
NSString *encoded = data[@"audio_wav_base64"];
if (!string(encoded) || !object(data[@"audio"])) return toolError(rid, @"invalid_playtest_audio");
@@ -492,6 +509,10 @@ int main(int argc, char **argv) {
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 7 &&
[grant[@"playtest"] isEqual:@YES] && [grant[@"playtestAudio"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestAudioTools()];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 12 &&
[grant[@"playtest"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() &&
[grant[@"playtestVideo"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtestVideo"]) == CFBooleanGetTypeID())
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestVideoTools()];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 10 && [grant[@"playtest"] isEqual:@YES] &&
CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() &&
[grant[@"playtestCallContext"] isEqual:@YES] &&
+52
View File
@@ -93,6 +93,8 @@ def check(helper):
result = {"result": active["playtest_graphics"]}
if request["tool"] == "capture_playtest_audio" and "playtest_audio" in active:
result = {"result": active["playtest_audio"]}
if request["tool"] in ("start_playtest_video", "stop_playtest_video", "read_playtest_video") and "playtest_video" in active:
result = {"result": active["playtest_video"]}
if request["tool"] == "get_build_log" and "build_log" in active:
result = {"result": active["build_log"]}
if request["tool"] == "get_debug_snapshot" and "debug_snapshot" in active:
@@ -788,6 +790,56 @@ def check(helper):
assert refused["isError"] and not any(x["type"] == "audio" for x in refused["content"])
del active["playtest_audio"]
video_tools = {"start_playtest_video", "stop_playtest_video", "read_playtest_video"}
for kind, toolset, play, video in (("cmoc", 11, True, True), ("assembly", 12, True, True),
("cmoc", 12, False, True), ("cmoc", 12, 1, True),
("cmoc", 12, True, False), ("cmoc", 12, True, 1),
("cmoc", 12, True, "yes"), ("cmoc", 12, True, True)):
write_grant(kind=kind, toolset=toolset, playtest=play, playtestVideo=video, token=active["token"])
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
catalog = {t["name"]: t for t in c.request("tools/list")["result"]["tools"]}
enabled = kind == "cmoc" and toolset >= 12 and play is True and video is True
assert video_tools.intersection(catalog) == (video_tools if enabled else set())
if not enabled:
continue
assert catalog["start_playtest_video"]["annotations"]["readOnlyHint"] is False
assert catalog["stop_playtest_video"]["annotations"]["readOnlyHint"] is False
assert catalog["read_playtest_video"]["annotations"]["readOnlyHint"] is True
for tool in video_tools:
assert catalog[tool]["inputSchema"]["additionalProperties"] is False
active["playtest_video"] = {"run_id":"owned", "video_recording":{"status":"recording"}}
for args in ({"run_id":"owned", "request_id":"begin"},
{"run_id":"owned", "request_id":"begin", "include_audio":False, "max_fields":3600}):
assert c.call("start_playtest_video", **args)["result"]["structuredContent"] == active["playtest_video"]
assert c.call("stop_playtest_video", run_id="owned", request_id="end")["result"]["structuredContent"] == active["playtest_video"]
count = len(active["requests"])
for update in ({"max_fields":0}, {"max_fields":3601}, {"max_fields":True}, {"max_fields":1.5},
{"include_audio":1}, {"include_audio":"yes"}, {"path":"/tmp/private"}):
args = {"run_id":"owned", "request_id":"bad", **update}
assert c.call("start_playtest_video", **args)["result"]["isError"], update
assert c.call("stop_playtest_video",run_id="owned",request_id="bad",path="/tmp/private")["result"]["isError"]
for update in ({"offset":-1}, {"offset":True}, {"offset":67108865}, {"limit":0},
{"limit":65537}, {"limit":True}, {"path":"/tmp/private"}):
assert c.call("read_playtest_video",run_id="owned",clip_id="clip",**update)["result"]["isError"], update
assert count == len(active["requests"]), "Invalid video requests must never reach the host"
payload = b"\x00\x00\x00\x18ftypmp42" + bytes(range(256)) * 255
chunk = dict(run_id="owned", clip_id="clip", video_chunk_base64=base64.b64encode(payload).decode(),
offset=0,next_offset=len(payload),byte_count=len(payload),eof=True,
sha256=hashlib.sha256(payload).hexdigest(),mime_type="video/mp4")
active["playtest_video"] = chunk
result = c.call("read_playtest_video",run_id="owned",clip_id="clip")["result"]
assert result["structuredContent"] == chunk
assert json.loads(result["content"][0]["text"]) == chunk
for update in ({"video_chunk_base64":"!"}, {"next_offset":len(payload)+1}, {"byte_count":67108865},
{"offset":1}, {"eof":False}, {"sha256":"x"*64}, {"clip_id":"foreign"},
{"mime_type":"audio/wav"}, {"video_chunk_base64":"", "next_offset":0}):
active["playtest_video"] = {**chunk, **update}
assert c.call("read_playtest_video",run_id="owned",clip_id="clip")["result"]["isError"], update
active["playtest_video"] = {**chunk, "video_chunk_base64":"", "offset":len(payload), "next_offset":len(payload)}
assert c.call("read_playtest_video",run_id="owned",clip_id="clip",offset=len(payload))["result"]["structuredContent"]["eof"] is True
del active["playtest_video"]
write_grant(version=2, kind="archive", token=active["token"], canPropose=True, toolset=3)
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
@@ -0,0 +1,60 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
import CoreGraphics
/// Only linked into the disposable helper. These waits never run in the Mac
/// application's main actor or machine controller. The codec implementation is
/// exactly the same bounded writer used by the native capture controls.
@objc(VCCPlaytestVideoWriter)
final class VCCPlaytestVideoWriter: NSObject {
private let encoder: CoCoVideoEncoder
private let directory: URL
private let includeAudio: Bool
private var sampleOffset: Int64 = 0
@objc init(directory: URL, includeAudio: Bool) throws {
self.directory = directory; self.includeAudio = includeAudio
encoder = try CoCoVideoEncoder(workingURL: directory.appendingPathComponent("Working.mov"))
super.init()
}
private final class Reply<T>: @unchecked Sendable {
let semaphore = DispatchSemaphore(value: 0)
private let lock = NSLock()
private var result: Result<T, Error>?
func complete(_ result: Result<T, Error>) { lock.lock(); self.result = result; lock.unlock(); semaphore.signal() }
func wait() throws -> T {
guard semaphore.wait(timeout: .now() + 20) == .success else { throw CoCoRecordingError.message("The disposable video writer timed out.") }
lock.lock(); defer { lock.unlock() }
guard let result else { throw CoCoRecordingError.message("The disposable video writer returned no result.") }
return try result.get()
}
}
@objc func appendPixels(_ pixels: Data, area: CGRect, samples: Data) throws {
guard samples.count % 8 == 0, samples.count <= 16_384 * 8 else { throw CoCoRecordingError.message("Invalid disposable video audio interval.") }
let frame = CoCoVideoFrame(pixels: pixels, area: area,
audio: includeAudio ? samples : Data(count: samples.count), sampleOffset: sampleOffset)
encoder.append([frame]); sampleOffset += Int64(samples.count / 8)
let reply = Reply<Void>()
encoder.whenDrained { reply.complete($0) }
try reply.wait()
}
@objc func finish() throws -> URL {
let reply = Reply<URL>()
encoder.finish { reply.complete($0) }
let working = try reply.wait()
let output = directory.appendingPathComponent("Clip.mp4")
let exported = Reply<URL>()
Task.detached {
do { try await CoCoVideoEncoder.exportMP4(from: working, to: output); exported.complete(.success(output)) }
catch { exported.complete(.failure(error)) }
}
let result = try exported.wait()
// Conversion verifies playable tracks/duration before removing only our
// known working file. Failures retain that file for explicit recovery.
try FileManager.default.removeItem(at: working)
return result
}
}
+112 -6
View File
@@ -11,9 +11,16 @@
#include <string>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <cstdint>
// The class is implemented in Swift and shares CoCoVideoEncoder with the app.
@interface VCCPlaytestVideoWriter : NSObject
- (instancetype)initWithDirectory:(NSURL *)directory includeAudio:(BOOL)includeAudio error:(NSError **)error;
- (BOOL)appendPixels:(NSData *)pixels area:(CGRect)area samples:(NSData *)samples error:(NSError **)error;
- (NSURL *)finishAndReturnError:(NSError **)error;
@end
using namespace VCC::Mac;
namespace {
constexpr size_t wireLimit = 1024 * 1024;
@@ -21,6 +28,7 @@ constexpr uint64_t fieldBudget = 216000;
constexpr size_t maximumDiskBytes = 512 * 1024;
constexpr unsigned audioFieldLimit = 120;
constexpr size_t audioSampleFrameLimit = 131072;
constexpr uint64_t videoByteLimit = 64 * 1024 * 1024;
void little16(std::vector<uint8_t>& bytes, uint16_t value) {
bytes.push_back(value & 255); bytes.push_back(value >> 8);
}
@@ -274,6 +282,55 @@ class Playtest {
void armStop() { armEvidence(stops, stopModule); }
void armInspection() { armEvidence({}, {}); }
uint64_t consumed = 0, fieldClock = 0, bootNumber = 0, mediaGeneration = 0;
VCCPlaytestVideoWriter *videoWriter = nil;
NSMutableDictionary *videoInfo = nil;
NSURL *videoDirectory = nil;
unsigned videoMaximumFields = 0;
uint64_t videoFirstField = 0, videoSamples = 0;
void finishVideo(NSString *reason) {
if (!videoWriter) return;
NSError *error = nil;
NSURL *output = nil;
if (videoSamples) output = [videoWriter finishAndReturnError:&error];
videoWriter = nil;
videoInfo[@"field_end"] = @(fieldClock);
videoInfo[@"fields_recorded"] = @(fieldClock - videoFirstField);
videoInfo[@"sample_frames"] = @(videoSamples);
videoInfo[@"truncated"] = @(![reason isEqual:@"stopped"] && ![reason isEqual:@"run_stopped"]);
videoInfo[@"reason"] = reason;
videoInfo[@"status"] = @"failed"; videoInfo[@"completed"] = @NO;
if (!output) { videoInfo[@"error"] = error.localizedDescription ?: @"No emulated audio/video interval was recorded."; return; }
NSData *data = [NSData dataWithContentsOfURL:output options:NSDataReadingMappedIfSafe error:&error];
if (!data || data.length == 0 || data.length > videoByteLimit) {
videoInfo[@"error"] = error.localizedDescription ?: @"playtest_video_byte_limit"; return;
}
std::vector<uint8_t> bytes(static_cast<const uint8_t *>(data.bytes), static_cast<const uint8_t *>(data.bytes) + data.length);
videoInfo[@"status"] = @"complete"; videoInfo[@"completed"] = @YES;
videoInfo[@"byte_count"] = @(data.length); videoInfo[@"sha256"] = sha256(bytes);
videoInfo[@"mime_type"] = @"video/mp4"; videoInfo[@"filename"] = @"Clip.mp4";
}
void recordVideo(const std::vector<StereoSample>& samples) {
if (!videoWriter || samples.empty()) return;
const auto snapshot = machine->snapshot();
const auto frame = snapshot.frame;
if (!frame || frame->pixels.size() != Frame::width * Frame::height) {
finishVideo(@"picture_unavailable"); return;
}
const auto area = frame->activeArea;
NSError *error = nil;
const BOOL ok = [videoWriter appendPixels:[NSData dataWithBytes:frame->pixels.data() length:frame->pixels.size() * sizeof(uint32_t)]
area:CGRectMake(area.x, area.y, area.width, area.height)
samples:[NSData dataWithBytes:samples.data() length:samples.size() * sizeof(StereoSample)] error:&error];
if (!ok) {
videoWriter = nil; videoInfo[@"status"] = @"failed"; videoInfo[@"completed"] = @NO;
videoInfo[@"error"] = error.localizedDescription ?: @"playtest_video_writer_failed"; return;
}
videoSamples += samples.size();
videoInfo[@"field_end"] = @(fieldClock); videoInfo[@"fields_recorded"] = @(fieldClock - videoFirstField);
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:[videoDirectory URLByAppendingPathComponent:@"Working.mov"].path error:nil];
if ([attributes fileSize] >= videoByteLimit - 1024 * 1024) finishVideo(@"byte_limit");
else if (fieldClock - videoFirstField >= videoMaximumFields) finishVideo(@"field_limit");
}
Processor processor = Processor::MC6809;
NSString *originalDiskHash = nil, *currentMediaID = nil;
NSString *diskHash() const {
@@ -332,8 +389,9 @@ class Playtest {
if (consumed + n > fieldBudget) throw std::runtime_error("playtest_field_limit");
for (unsigned i = 0; i < n && machine->snapshot().state == RunState::Running; ++i) {
const auto before = machine->snapshot().frames;
machine->advance(); machine->takeAudio(); ++consumed;
machine->advance(); ++consumed;
fieldClock += machine->snapshot().frames - before;
auto samples = machine->takeAudio(); recordVideo(samples);
}
}
void boot() {
@@ -354,7 +412,7 @@ class Playtest {
auto s = machine->snapshot();
const bool hd6309 = s.configuration.processor == Processor::HD6309;
const auto *image = floppy->image(0);
return @{ @"cpu": hd6309 ? @"6309" : @"6809", @"processor": hd6309 ? @"HD6309" : @"MC6809",
NSMutableDictionary *out = [@{ @"cpu": hd6309 ? @"6309" : @"6809", @"processor": hd6309 ? @"HD6309" : @"MC6809",
@"execution_mode": hd6309 ? (s.cpu.IsNative6309 ? @"native" : @"emulation") : @"not_applicable",
@"md_register": hd6309 ? (id)@(s.cpu.MD) : NSNull.null, @"ram_kb": @512,
@"fields": @(fieldClock), @"field_clock": @(fieldClock), @"boot": @(bootNumber), @"machine_frame": @(s.frames),
@@ -366,7 +424,9 @@ class Playtest {
@"disk_present": @(image != nullptr), @"media_id": currentMediaID ?: (id)NSNull.null,
@"media_generation": @(mediaGeneration), @"floppy_busy": @(floppy->snapshot().busy),
@"disk_dirty": @(image && image->dirty()), @"disk_reads": @(floppy->readEvents(0)),
@"disk_writes": @(floppy->writeEvents(0)), @"isolated": @YES, @"input":inputMetadata(s) };
@"disk_writes": @(floppy->writeEvents(0)), @"isolated": @YES, @"input":inputMetadata(s) } mutableCopy];
if (videoInfo) out[@"video_recording"] = [videoInfo copy];
return out;
}
NSDictionary *capture() const {
NSMutableDictionary *out = [status() mutableCopy];
@@ -396,6 +456,7 @@ class Playtest {
auto next = machine->takeAudio();
if (next.size() > audioSampleFrameLimit - samples.size()) throw std::runtime_error("playtest_audio_limit");
samples.insert(samples.end(), next.begin(), next.end());
recordVideo(next);
};
// Discard audio from earlier input/steps. A capture owns only this
// explicit interval, including any normal leave-breakpoint CPU slice.
@@ -452,6 +513,19 @@ public:
for (NSDictionary *item in declared) {
if (![item isKindOfClass:NSDictionary.class] || ![item[@"id"] isKindOfClass:NSString.class]) throw std::invalid_argument("invalid_modules");
DebugBankedModule module; module.identifier = [item[@"id"] UTF8String];
id overlayGroup = item[@"overlay_group"], overlayOwner = item[@"overlay_owner"];
if (overlayGroup || overlayOwner) {
if (![overlayGroup isKindOfClass:NSString.class] || ![overlayOwner isKindOfClass:NSString.class] ||
![overlayGroup length] || ![overlayOwner length] ||
[overlayGroup lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 128 ||
[overlayOwner lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 128)
throw std::invalid_argument("invalid_overlay_identity");
const char *groupText = [overlayGroup UTF8String], *ownerText = [overlayOwner UTF8String];
if (!groupText || !ownerText || std::strlen(groupText) != [overlayGroup lengthOfBytesUsingEncoding:NSUTF8StringEncoding] ||
std::strlen(ownerText) != [overlayOwner lengthOfBytesUsingEncoding:NSUTF8StringEncoding])
throw std::invalid_argument("invalid_overlay_identity");
module.overlayGroup = groupText; module.overlayOwner = ownerText;
}
NSArray *pages = item[@"pages"], *guards = item[@"guards"];
if (![pages isKindOfClass:NSArray.class] || pages.count == 0 || pages.count > 8 ||
![guards isKindOfClass:NSArray.class] || guards.count == 0 || guards.count > 8192) throw std::invalid_argument("invalid_modules");
@@ -543,6 +617,32 @@ public:
return exportMedia();
}
if ([op isEqual:@"exchange_media"]) return exchangeMedia(r);
if ([op isEqual:@"video_start"]) {
if (r.count != 5 || ![r[@"clip_id"] isKindOfClass:NSString.class] ||
![r[@"directory"] isKindOfClass:NSString.class] || !r[@"include_audio"] ||
CFGetTypeID((__bridge CFTypeRef)r[@"include_audio"]) != CFBooleanGetTypeID()) throw std::invalid_argument("invalid_arguments");
if (videoWriter) throw std::runtime_error("playtest_video_active");
NSUUID *identifier = [[NSUUID alloc] initWithUUIDString:r[@"clip_id"]];
NSURL *directory = [NSURL fileURLWithPath:r[@"directory"] isDirectory:YES];
if (!identifier || ![directory.lastPathComponent isEqual:identifier.UUIDString] ||
![NSFileManager.defaultManager fileExistsAtPath:directory.path]) throw std::invalid_argument("invalid_arguments");
videoMaximumFields = number(r[@"max_fields"], 1, 3600);
NSError *error = nil;
videoWriter = [[VCCPlaytestVideoWriter alloc] initWithDirectory:directory includeAudio:[r[@"include_audio"] boolValue] error:&error];
if (!videoWriter) throw std::runtime_error((error.localizedDescription ?: @"playtest_video_start_failed").UTF8String);
videoDirectory = directory; videoFirstField = fieldClock; videoSamples = 0;
machine->takeAudio();
videoInfo = [@{@"clip_id":identifier.UUIDString, @"status":@"recording", @"include_audio":r[@"include_audio"],
@"max_fields":@(videoMaximumFields), @"field_start":@(fieldClock), @"field_end":@(fieldClock),
@"fields_recorded":@0, @"completed":@NO, @"truncated":@NO, @"boot":@(bootNumber),
@"ui_cues_included":@NO, @"microphone_included":@NO, @"host_audio_included":@NO} mutableCopy];
return status();
}
if ([op isEqual:@"video_stop"]) {
if (r.count != 1 || !videoInfo) throw std::runtime_error("playtest_video_unavailable");
finishVideo(@"stopped");
NSMutableDictionary *out = [status() mutableCopy]; out[@"video"] = [videoInfo copy]; return out;
}
if ([op isEqual:@"input"]) {
if (r.count != 2) throw std::invalid_argument("invalid_arguments");
unsigned total = 0;
@@ -563,6 +663,7 @@ public:
applied = machine->resumeWithInput(step.keys, step.joysticks);
const auto advanced = machine->snapshot().frames - before.frames;
fieldClock += advanced; consumed += advanced;
auto samples = machine->takeAudio(); recordVideo(samples);
if (advanced > step.fields) throw std::runtime_error("playtest_input_timing");
} else {
machine->setKeyboard(step.keys);
@@ -621,15 +722,16 @@ public:
return out;
}
if ([op isEqual:@"restart"]) {
if (videoWriter) throw std::runtime_error("playtest_video_active: stop the recording before restarting");
if (floppy->snapshot().busy) throw std::runtime_error("disk_busy");
boot(); return status();
}
if ([op isEqual:@"continue"]) { armInspection(); machine->resume(); return status(); }
if ([op isEqual:@"continue"]) { armInspection(); const auto before = machine->snapshot().frames; machine->resume(); fieldClock += machine->snapshot().frames - before; auto samples = machine->takeAudio(); recordVideo(samples); return status(); }
if ([op isEqual:@"pause"]) { machine->releaseInputs(); machine->pause(); return status(); }
if ([op isEqual:@"step"]) {
if (machine->snapshot().state != RunState::Paused) throw std::runtime_error("playtest_not_stopped");
const auto before = machine->snapshot().frames;
machine->debuggerStep(); fieldClock += machine->snapshot().frames - before; return status();
machine->debuggerStep(); fieldClock += machine->snapshot().frames - before; auto samples = machine->takeAudio(); recordVideo(samples); return status();
}
if ([op isEqual:@"stop_at"]) {
if (modules.empty() && flatGuards.empty()) throw std::runtime_error("unverified_stop");
@@ -643,7 +745,8 @@ public:
}
armEvidence({nextPoint}, nextModule);
stops = {nextPoint}; stopModule = nextModule;
machine->resume(); return status();
const auto before = machine->snapshot().frames; machine->resume(); fieldClock += machine->snapshot().frames - before;
auto samples = machine->takeAudio(); recordVideo(samples); return status();
}
if ([op isEqual:@"debug"]) {
if (machine->snapshot().state != RunState::Paused) throw std::runtime_error("playtest_not_stopped");
@@ -658,6 +761,7 @@ public:
out[@"registers"] = registers;
out[@"mapping_fingerprint"] = [NSString stringWithFormat:@"%llu",(unsigned long long)machine->snapshot().debuggerMappingFingerprint];
out[@"program_revision"] = @(machine->snapshot().debuggerProgramRevision);
out[@"residency_fingerprint"] = [NSString stringWithFormat:@"%llu",(unsigned long long)machine->snapshot().debuggerResidencyFingerprint];
out[@"attached"] = @(machine->snapshot().debuggerDevelopmentAttached);
out[@"paused"] = @YES;
out[@"logical_memory"] = [[NSData dataWithBytes:d.memory.data() length:d.memory.size()] base64EncodedStringWithOptions:0];
@@ -684,7 +788,9 @@ public:
}
if ([op isEqual:@"stop"]) {
machine->releaseInputs(); machine->pause();
finishVideo(@"run_stopped");
NSMutableDictionary *out = [status() mutableCopy];
if (videoInfo) out[@"video"] = [videoInfo copy];
if (const auto *image = floppy->image(0)) {
const auto& disk = image->bytes();
out[@"disk_base64"] = [[NSData dataWithBytes:disk.data() length:disk.size()] base64EncodedStringWithOptions:0];