diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 5033d39154..83ff724d5d 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -352,8 +352,8 @@ the UI thread. | View | `set_view` | tab (Design included), 3D view (Prepare, preview, assemble), camera (the Design view's on the Design tab), preview layers (by number or height), color scheme as the legend's combo picks it, legend rows and time estimate, window size | | | `screenshot` | window, the 3D view shown (the Design view on the Design tab), topmost dialog or one widget: a downscaled image and a full-size PNG | | | `get_preview` | a sliced plate's summary, time and grams per feature type, per-layer Z, height, time and grams (paged), grams per object instance, and the Preview's legend state and colour ranges | -| Recording | `start_recording` | record the main window with its modal dialogs, or the 3D view shown, into an MJPEG `.mkv`, with the current tool call as a caption and the pointer highlighted when asked for | -| | `stop_recording` | capture the last state, end the recording and report its file once written: length, frames, drops, the mean UI time of a capture, size and why it ended | +| Recording | `start_recording` | record the main window with its modal dialogs, or the 3D view shown, into an MJPEG `.mkv`, with the current tool call as a caption and the pointer highlighted when asked for, and with `encode` an MP4 of it once stopped | +| | `stop_recording` | capture the last state, end the recording and report its file once written: length, frames, drops, the mean UI time of a capture, size and why it ended; the job of the encode `start_recording` asked for | | | `encode_recording` | encode a recording into an H.265 or H.264 MP4 with the system ffmpeg; cancellable | | GUI | `ui_snapshot` | widgets, rows of lists, trees and tables, popups, menus, GL toolbar items, gizmos, the Prepare view's plates and plate icons, and ImGui items, with refs | | | `ui_click` | activate a ref or locator, click a row's cell or a plate icon, or click a point of a 3D canvas or custom-drawn widget; list the menu it opens, or run one of its items | @@ -1687,7 +1687,7 @@ block is scaled to `max_dim` on the long edge (default 1280, clamped to 256–20 `start_recording` records what OrcaSlicer shows into a video while an agent, a script or a person works, and `encode_recording` turns it into an MP4 to attach to an issue. Recording has to stay light, since it runs while the app works: frames are kept as JPEG in a Matroska file (MJPEG), and the H.265 -encode, which costs far more, is a later call. There is no audio. `McpRecorder` holds at most one +encode, which costs far more, comes after it. There is no audio. `McpRecorder` holds at most one recording; `get_state.recording` shows it while it runs. **Capture.** The UI thread captures a frame per tick of a one-shot `wxTimer`, which fires inside @@ -1748,6 +1748,16 @@ the UI thread, and a step after the script sees a closed file. At exit `stop()` file, then drops what is still queued and leaves the sink to its threads, which own its state. A recording counts as active until its file is closed, for the one-at-a-time rule and for encodes. +**Encoding up front.** `start_recording` takes the Start Recording command's encoding keys (`encode`, +`encode_preset`, `codec`, `crf`, `speed`, `profile`), checked by `apply_recording_overrides()` with its +defaults, the Balanced preset, and refuses `encode` without an ffmpeg before anything records. The +recording keeps `encode_recording`'s arguments (`RecordingOptions::encode`), and the `stop_recording` +that reports it, once its file is closed, starts the encode with `McpService::start_encode()`: a job of +its own, outside the journal (a replayed `start_recording` asks for it again), whose envelope the report +carries as `encode`, so the agent waits for the MP4 by that job's id. A recording that ended on its own +is encoded when the next `stop_recording` reports it; one nothing reports, a client's that ended with +the endpoint, is not encoded. An agent can still encode any recording later with `encode_recording`. + **From the app.** The Speed Dial commands `take_screenshot`, `start_recording` and `stop_recording`, which the Help menu also has, give a person screenshots and recordings without an agent: a PNG of the main window, and a recording of it for up to an hour. Both go in the person's Downloads folder unless they chose another. @@ -1760,7 +1770,9 @@ AppConfig's `recording` section (`RecordingSettings`). The command's parameter o one recording, and with `silent` starts at once without the dialog and remembers nothing; a silent start that would encode without an ffmpeg is refused rather than recording unencoded. The encode is `encode_recording` itself, run by `McpService::encode_when_closed()` as an unjournaled job once the -recording's file is closed (`McpRecorder::wait_closed()`), so it can be cancelled like any encode. +recording's file is closed (`McpRecorder::wait_closed()`), so it can be cancelled like any encode. No reply +names the job, which only exists once the file is closed: an agent finds it in `get_state.jobs` and waits +for it by its id, as the command's description says. Start Recording starts the service without its endpoint when the server is off, as the Run Script dialog does. The person's recording has its own owner (`kPersonOwner`), so neither a script's end nor the endpoint closing ends it. Whatever ends it tells the person where it went, in a notification whose button diff --git a/src/slic3r/GUI/Mcp/McpRecorder.cpp b/src/slic3r/GUI/Mcp/McpRecorder.cpp index bfc6efd9ab..2e17138332 100644 --- a/src/slic3r/GUI/Mcp/McpRecorder.cpp +++ b/src/slic3r/GUI/Mcp/McpRecorder.cpp @@ -722,7 +722,7 @@ json McpRecorder::report(Recording& rec) const return out; } -json McpRecorder::stop_and_report(std::chrono::milliseconds timeout) +json McpRecorder::stop_and_report(std::chrono::milliseconds timeout, json& encode) { std::shared_ptr rec; { @@ -738,6 +738,7 @@ json McpRecorder::stop_and_report(std::chrono::milliseconds timeout) std::lock_guard lock(m_mutex); rec->reported = true; } + encode = rec->options.encode; return report(*rec); } diff --git a/src/slic3r/GUI/Mcp/McpRecorder.hpp b/src/slic3r/GUI/Mcp/McpRecorder.hpp index fcde7c7b67..425cfa5434 100644 --- a/src/slic3r/GUI/Mcp/McpRecorder.hpp +++ b/src/slic3r/GUI/Mcp/McpRecorder.hpp @@ -53,6 +53,9 @@ struct RecordingOptions bool pointer = false; // the pointer highlighted, its clicks rippling boost::filesystem::path path; std::string owner; // the job of the script that started it, "" for a client, kPersonOwner + // encode_recording's arguments, path included, for the stop_recording that reports this recording to run; + // null for none. + nlohmann::json encode; // Runs on the UI thread once the recording ends, while its file is still being closed, with the reason it // was ended for ("" when the file ended it: a write error or the size limit). Never after a failed start. std::function ended; @@ -97,8 +100,9 @@ public: // for its file to be closed. Returns the path of a file still being written after that wait. std::optional end_owned_by(const std::string& owner, const std::string& reason, bool wait); // stop_recording: ends the running recording and waits for its file, or takes the result of the last - // one that ended on its own, once. Null when there is none. - nlohmann::json stop_and_report(std::chrono::milliseconds timeout); + // one that ended on its own, once. Null when there is none. `encode` gets the recording's + // RecordingOptions::encode. + nlohmann::json stop_and_report(std::chrono::milliseconds timeout, nlohmann::json& encode); // get_state's recording: {path, target, seconds, frames} while one runs, else null. nlohmann::json state() const; // A recording is being written or finalized. diff --git a/src/slic3r/GUI/Mcp/McpService.cpp b/src/slic3r/GUI/Mcp/McpService.cpp index c0233c50f5..adaeb04427 100644 --- a/src/slic3r/GUI/Mcp/McpService.cpp +++ b/src/slic3r/GUI/Mcp/McpService.cpp @@ -147,8 +147,8 @@ const char* kInstructions = "- Paths are absolute. Outputs never overwrite an existing file unless overwrite is true.\n" "- screenshot returns a downscaled image plus the full-size PNG path; target \"canvas\" is the 3D view.\n" "- start_recording / stop_recording record a video (MJPEG .mkv), with the tool calls as captions and the pointer " - "highlighted when captions and pointer ask for them; " - "encode_recording turns it into an H.265 MP4 with the system ffmpeg.\n" + "highlighted when captions and pointer ask for them; with encode, stop_recording then encodes it to an MP4 with " + "the system ffmpeg as a job to wait for, and encode_recording encodes any recording later.\n" "- export_script saves this session's calls as a replayable script; run_script replays one."; } // namespace @@ -658,6 +658,17 @@ bool McpService::encode_when_closed(json args, std::functioncall(def, args); +} + bool McpService::discard_authorized(const std::set& lineage) const { std::lock_guard lock(m_run_state_mutex); diff --git a/src/slic3r/GUI/Mcp/McpService.hpp b/src/slic3r/GUI/Mcp/McpService.hpp index 7a9e78cc4a..3a84787234 100644 --- a/src/slic3r/GUI/Mcp/McpService.hpp +++ b/src/slic3r/GUI/Mcp/McpService.hpp @@ -152,6 +152,10 @@ public: // is cancelled like any encode (cancel {job}, stop()), and `done` is not called once the service stops. // False when the service is not started or is stopping. Any thread. bool encode_when_closed(nlohmann::json args, std::function done); + // Starts encode_recording with `args` as an unjournaled job of its own and returns at once: the job's + // envelope, or the error that refused it. For a recording's encode that stop_recording starts, which a + // replay of the recording asks for again. Any thread. + ToolResult start_encode(const nlohmann::json& args); private: friend struct McpServiceDeleter; diff --git a/src/slic3r/GUI/Mcp/McpToolsRecord.cpp b/src/slic3r/GUI/Mcp/McpToolsRecord.cpp index 7c970fe039..2df4c6ac96 100644 --- a/src/slic3r/GUI/Mcp/McpToolsRecord.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsRecord.cpp @@ -6,6 +6,7 @@ #include "McpService.hpp" #include "McpTools.hpp" #include "McpTypes.hpp" +#include "RecordingSettings.hpp" #include "VideoEncode.hpp" #include "slic3r/GUI/I18N.hpp" @@ -86,6 +87,14 @@ int process_id() #endif } +std::vector encode_preset_keys() +{ + std::vector keys; + for (const EncodePreset& p : encode_presets()) + keys.emplace_back(p.key); + return keys; +} + } // namespace void register_record_tools(McpService& service) @@ -99,7 +108,8 @@ void register_record_tools(McpService& service) "the tool call acting on the app shows as a caption at the bottom (secret setting values never show); with pointer, " "the pointer is highlighted, its clicks rippling. Capture takes at most about a third of the UI thread, so " "the frame rate drops where capturing is slow. One recording at a time: one a script starts ends with the script, a " - "client's when the server is turned off. encode_recording makes an MP4 of it.", + "client's when the server is turned off. With encode, the stop_recording that reports it also encodes it to an MP4 " + "beside it, as the Start Recording command does; encode_recording makes an MP4 of any recording later.", object_schema({{"target", enum_prop({"window", "canvas"}, "window (default): the main window and its dialogs; canvas: the 3D view shown.")}, {"fps", int_prop(1, 30, "Frames per second at most (default 10).")}, {"max_dim", int_prop(320, 3840, "Long edge of the video in pixels (default 1920).")}, @@ -107,8 +117,17 @@ void register_record_tools(McpService& service) {"max_seconds", int_prop(1, 3600, "The recording ends on its own after this long (default 600).")}, {"captions", prop("boolean", "Caption the tool call acting on the app (default false).")}, {"pointer", prop("boolean", "Highlight the pointer and show its clicks (default false).")}, + {"encode", prop("boolean", "Encode it to an MP4 once stopped; needs an ffmpeg (default false).")}, + {"encode_preset", enum_prop(encode_preset_keys(), "With encode: the settings the fields below change " + "(default balanced: h265, crf 28, medium, main).")}, + {"codec", enum_prop({"h265", "h264"}, "With encode: the codec (default the preset's).")}, + {"crf", int_prop(0, 51, "With encode: constant rate factor, lower is better and larger (default the preset's).")}, + {"speed", enum_prop(encoder_speeds(), "With encode: slower makes a smaller file (default the preset's).")}, + {"profile", enum_prop({"high", "main", "baseline", "main10"}, + "With encode: h264 high, main or baseline; h265 main or main10 (default the preset's, else " + "the codec's first).")}, {"save_path", prop("string", "Absolute .mkv path; default the session's output folder.")}, - {"overwrite", prop("boolean", "Replace an existing save_path.")}}), + {"overwrite", prop("boolean", "Replace an existing save_path, and with encode its MP4.")}}), [&service](const json& args, ToolContext& ctx) { RecordingOptions o; o.target = arg_string(args, "target", "window"); @@ -118,6 +137,17 @@ void register_record_tools(McpService& service) o.max_seconds = arg_int(args, "max_seconds", 600); o.captions = arg_bool(args, "captions", false); o.pointer = arg_bool(args, "pointer", false); + // The encode as the Start Recording command takes it: its keys, defaults and checks. + json encode_args = json::object(); + for (const char* key : {"encode", "encode_preset", "codec", "crf", "speed", "profile"}) + if (args.contains(key)) + encode_args[key] = args[key]; + RecordingSettings settings; + bool silent = false; + if (const std::string err = apply_recording_overrides(settings, encode_args, silent); !err.empty()) + throw ToolFailure(err); + if (std::string err; settings.encode && !find_ffmpeg(err)) + throw ToolFailure("Cannot encode: " + err); if (args.contains("save_path")) { const std::string path = arg_string(args, "save_path"); if (!boost::algorithm::iends_with(path, ".mkv")) @@ -130,6 +160,11 @@ void register_record_tools(McpService& service) } else { o.path = timestamped_path(output_dir(), "recording", ".mkv", {".mp4"}); } + if (settings.encode) { + o.encode = encode_arguments(settings, path_to_utf8(o.path)); + if (arg_bool(args, "overwrite", false)) + o.encode["overwrite"] = true; + } // Like auto-answer rules: a script's recording ends with the script, a client's with the endpoint. const std::vector ancestry = service.jobs().ancestry(ctx.job_id()); o.owner = service.script_owner(ancestry); @@ -163,6 +198,11 @@ void register_record_tools(McpService& service) handed_over = true; // start() owns the reservation from here, success or not return service.recorder().start(o, owner); }); + if (settings.encode) + out["encode"] = {{"codec", settings.codec}, + {"crf", settings.crf}, + {"speed", settings.speed}, + {"profile", settings.profile}}; // The path used, so a replay records into its own output folder under the same name and its // encode finds it there. json recorded = args; @@ -175,7 +215,9 @@ void register_record_tools(McpService& service) "Stop the running recording and return its file once it is written: seconds, frames captured and " "written, frames dropped when encoding fell behind or skipped when the window could not be captured, " "the size, the mean UI-thread time a capture took (capture_ms), and why it ended. A recording that ended on its own (max_seconds, its script ended, a " - "write error) is reported once by the next stop_recording.", + "write error) is reported once by the next stop_recording. For a recording started with encode, it then " + "starts the MP4 encode and returns it under encode: a job, whose wait {for: \"job\"} returns " + "encode_recording's result.", object_schema({}), [&service](const json&, ToolContext& ctx) { // The last state too, even if the timer has not ticked since the last call. Without the // UI thread (a native dialog holds it), the recording ends with its last frame. @@ -186,9 +228,14 @@ void register_record_tools(McpService& service) }); } catch (const ToolFailure&) { } - const json report = service.recorder().stop_and_report(std::chrono::seconds(60)); + json encode; + json report = service.recorder().stop_and_report(std::chrono::seconds(60), encode); if (report.is_null()) throw ToolFailure("No recording is running"); + if (!encode.is_null()) { + const ToolResult r = service.start_encode(encode); + report["encode"] = r.is_error ? json{{"error", r.message}} : r.data; + } return ToolResult::ok(report); })); diff --git a/src/slic3r/GUI/NativeCommands.cpp b/src/slic3r/GUI/NativeCommands.cpp index dc90d1aed1..ae2ccf70ef 100644 --- a/src/slic3r/GUI/NativeCommands.cpp +++ b/src/slic3r/GUI/NativeCommands.cpp @@ -508,7 +508,9 @@ void describe_commands(std::vector& commands) "param key) and answer it with dialog_respond \"Start recording\"; it remembers what it starts with. " "With silent, the recording starts at once and nothing is remembered; one that would encode is refused " "when no ffmpeg is found. The reply has the path and the settings used. Neither a script's end nor the " - "server turning off ends it. Agents record with start_recording instead.", + "server turning off ends it. With encode, the encode starts once the recording's file is closed, as an " + "encode_recording job in get_state.jobs: wait {for: \"job\"} with its id returns the MP4's path, or " + "an error. Agents record with start_recording instead.", CommandParamType::Text, "JSON object, all optional: quality (30-95), captions (bool), pointer (bool), encode (bool), encode_preset (small, " "balanced, quality, compatible; applied before the fields), codec (h265, h264), crf (0-51), speed (ultrafast ... " @@ -516,7 +518,9 @@ void describe_commands(std::vector& commands) "directory), silent (bool)"}, {"stop_recording", "Stop the running recording, whoever started it, without waiting for its file, and show the person a " "notification naming it; the reply has its path. A later stop_recording reports it as ended " - "stopped_in_app. Agents stop their own recordings with stop_recording, which waits and reports."}, + "stopped_in_app. A recording Start Recording made with encode is then encoded: find its " + "encode_recording job in get_state.jobs. Agents stop their own recordings with stop_recording, which " + "waits and reports."}, {"open_preferences", "Open the Preferences dialog on a tab, scrolled to one preference when given (shown on its own tab). Its " "controls are named after their preference keys: ui_input {\"target\": {\"name\": key, \"within\": " "\"Preferences\"}} changes one through the dialog; get_settings scope preferences reads them.", diff --git a/tools/mcp/README.md b/tools/mcp/README.md index e89e5c6314..958bc6e275 100644 --- a/tools/mcp/README.md +++ b/tools/mcp/README.md @@ -122,7 +122,8 @@ filament change, a 3MF round trip, and `clear`. Preferences dialog opened and closed, a slice. It stops the recording (frames, length, size) and encodes it to H.265, then has a nested script start a recording of the 3D view that it never stops, checks the script's end closed it, and encodes that to H.264. Short recordings check that a recording has no overlays -unless `captions` or `pointer` turns one on. The encodes need an ffmpeg with libx265 and libx264 +unless `captions` or `pointer` turns one on, and that one started with `encode` is encoded as a job once +`stop_recording` reports it. The encodes need an ffmpeg with libx265 and libx264 (`ORCA_FFMPEG`, or `ffmpeg` on `PATH`) and are optional without one. Look at the videos, or at frames `ffmpeg -i session.mkv -vf fps=1 frame%02d.png` extracts, for the caption, the pointer and the dialog. diff --git a/tools/mcp/tests/recording.json b/tools/mcp/tests/recording.json index db71c01593..abe680a953 100644 --- a/tools/mcp/tests/recording.json +++ b/tools/mcp/tests/recording.json @@ -60,6 +60,17 @@ {"tool": "stop_recording", "expect": {"/ended": {"eq": "stopped"}}}, {"tool": "start_recording", "args": {"save_path": "${out_dir}/plain.mkv", "overwrite": true, "captions": true}, "expect": {"/captions": {"eq": true}, "/pointer": {"eq": false}}}, - {"tool": "stop_recording", "expect": {"/ended": {"eq": "stopped"}}} + {"tool": "stop_recording", "expect": {"/ended": {"eq": "stopped"}}}, + + // Encoding asked for up front (an ffmpeg with libx264): the stop that reports the recording starts the encode + // as a job of its own, which wait idle waits for. + {"tool": "start_recording", "args": {"save_path": "${out_dir}/encoded.mkv", "overwrite": true, "encode": true, + "encode_preset": "compatible", "crf": 30}, "optional": true, + "expect": {"/encode/codec": {"eq": "h264"}, "/encode/crf": {"eq": 30}, "/encode/profile": {"eq": "high"}}}, + {"tool": "stop_recording", "optional": true, + "expect": {"/path": {"regex": "encoded\\.mkv$"}, "/encode/status": {"eq": "running"}, "/encode/job": {"exists": true}}}, + {"tool": "wait", "args": {"for": "idle", "timeout_s": 50}, "optional": true, "expect": {"/satisfied": {"eq": true}}}, + {"tool": "get_state", "optional": true, + "expect": {"/jobs/0/tool": {"eq": "encode_recording"}, "/jobs/0/state": {"eq": "done"}}} ] }