davinci-resolve-mcp 4.18.1 → 4.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,87 @@
2
2
 
3
3
  Release history for the DaVinci Resolve MCP Server. The latest release is summarized in the root README; older entries live here to keep the README focused.
4
4
 
5
+ ## What's New in v4.18.3 — A subtitle clipInfo no longer takes Resolve down
6
+
7
+ On Studio 21.1.2.10, `AppendToTimeline` with a clipInfo for an imported SRT
8
+ aborts Resolve. The clipInfo builders now refuse that payload before the call.
9
+
10
+ ### Fixed
11
+
12
+ - **A subtitle clipInfo is refused on Resolve 21.1+** (#335, thanks
13
+ @blacksky3810). `media_pool append_to_timeline` and the other clipInfo
14
+ builders return `SUBTITLE_APPEND_CRASH` instead of forwarding the call.
15
+ On Studio 21.1.2.10 that call aborts Resolve (`Sm2MpObject.cpp:546`). The
16
+ plain `clip_ids` form is unchanged: it does not crash, and on that build it
17
+ also places nothing. Builds older than 21.1 still forward the clipInfo;
18
+ that route was reported working on Studio 21.0.4.5 (#169). An unreadable
19
+ version is refused too.
20
+ - **An allowed media root of `/` contains its files** (#334, thanks
21
+ @Dev-next-gen). The path check built the prefix as `root + separator`, so
22
+ `/` became `//` and a Windows drive root doubled its separator. Every clip
23
+ was then reported outside the allowed roots.
24
+
25
+ ### Documentation
26
+
27
+ - The SRT-import `api_truth` entry now records the 21.1.2 crash and the
28
+ silent plain-form no-op, and the limitations report was regenerated.
29
+
30
+ ### Validation
31
+
32
+ - Focused unit tests: the 21.1.2 clipInfo never reaches `AppendToTimeline`,
33
+ an unreadable version is refused, 21.0.4.5 still forwards, a video clipInfo
34
+ still forwards, and the granular builder returns the same code.
35
+ - Static checks: API parity, limitations and read/write drift guards, agent
36
+ rules, undefined names, duplicate definitions, action-list drift, panel
37
+ docs, tool counts, and release-surface drift.
38
+ - Live Resolve on this machine is Studio 19.1.3.7. The refusal applies at
39
+ 21.1 and above, so it was not exercised against the open project. The
40
+ 21.1.2 crash was not reproduced here.
41
+ - Control-panel guide reviewed. No panel navigation or visible UI changed,
42
+ so screenshots were not regenerated.
43
+
44
+ ## What's New in v4.18.2 — The rest of the `$` replacement bugs
45
+
46
+ v4.18.1 fixed `replace()` calls that put user text in with an interpolated
47
+ template string. Its guard only looked for that one form, so calls whose
48
+ replacement was a variable, a function call or a conditional were missed.
49
+
50
+ ### Fixed
51
+
52
+ - **Splitting, trimming, adding a transition, or adding a clip to a track that
53
+ already has clips no longer corrupts the track when a clip name contains
54
+ `$`** (#333, thanks @Dev-next-gen). The rewritten clip went into the track
55
+ as a replacement string, so `$&` or `` $` `` in a name copied other clips into
56
+ the track and duplicated them.
57
+ - **`media_ops` `relink_manifest` keeps a `$` in a target path prefix as
58
+ typed.** Mapping `/old/vol` to `/new/Spot $$ 30s $&` produced
59
+ `/new/Spot $ 30s /old/vol/...`, a path that does not exist.
60
+ - The same form, now fixed, was also in `assemble_timeline` (the timeline's
61
+ pool block, which holds its name, when the media extents are rewritten),
62
+ in the subtitle preset writer (the preset section XML), and in the agent-rule
63
+ generator (generated doc sections). The other changed calls only insert hex,
64
+ IDs or numbers; they now use replacer functions too, so a single rule holds
65
+ everywhere.
66
+
67
+ ### Changed
68
+
69
+ - The guard test now splits every `replace()` / `replaceAll()` call in
70
+ `resolve-advanced` and `scripts/` into its arguments, and fails unless the
71
+ replacement is a function or a literal with no `$` in it. Literals whose
72
+ `$`-sequences are backreferences (`$1`, `'\\$&'`) are allowed. The
73
+ `editorial` source-alias rules and the `media_ops` rename rules, where `$1`
74
+ is part of the feature, are listed by name. Run against the v4.18.1 sources,
75
+ it reports 25 call sites, including all six that #333 fixed.
76
+
77
+ ### Validation
78
+
79
+ - Advanced Node suite on Node 20 with a fresh `npm ci`: 1,227 tests, 0 failed.
80
+ Python suite: 4,295 tests; the only failures are the 4 `source_media_guard`
81
+ path checks that always fail in a scratch worktree. With #333's fix
82
+ reverted, its two tests fail. The new relink test
83
+ fails on the v4.18.1 code with the wrong path shown above.
84
+ - Offline file writers only. No Resolve API behaviour changed.
85
+
5
86
  ## What's New in v4.18.1 — Names with `$` or `\` are written as typed
6
87
 
7
88
  ### Fixed
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  English | [简体中文](README.zh-CN.md)
4
4
 
5
- [![Version](https://img.shields.io/badge/version-4.18.1-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
5
+ [![Version](https://img.shields.io/badge/version-4.18.3-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
6
6
  [![npm](https://img.shields.io/npm/v/davinci-resolve-mcp.svg?label=npm&color=CB3837)](https://www.npmjs.com/package/davinci-resolve-mcp)
7
7
  [![API Coverage](https://img.shields.io/badge/API%20Coverage-100%25-brightgreen.svg)](docs/reference/api-coverage.md)
8
8
  [![Tools](https://img.shields.io/badge/MCP%20Tools-37%20(390%20full)-blue.svg)](#server-modes)
package/README.zh-CN.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [English](README.md) | 简体中文
4
4
 
5
- [![Version](https://img.shields.io/badge/version-4.18.1-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
5
+ [![Version](https://img.shields.io/badge/version-4.18.3-blue.svg)](https://github.com/samuelgursky/davinci-resolve-mcp/releases)
6
6
  [![npm](https://img.shields.io/npm/v/davinci-resolve-mcp.svg?label=npm&color=CB3837)](https://www.npmjs.com/package/davinci-resolve-mcp)
7
7
  [![API Coverage](https://img.shields.io/badge/API%20Coverage-100%25-brightgreen.svg)](docs/reference/api-coverage.md)
8
8
  [![Tools](https://img.shields.io/badge/MCP%20Tools-37%20(390%20full)-blue.svg)](#服务器模式)
@@ -12,7 +12,7 @@
12
12
  [![Python](https://img.shields.io/badge/python-3.10+-green.svg)](https://www.python.org/downloads/)
13
13
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)
14
14
 
15
- > 本翻译对应 v4.18.1 版 README。如与英文原版有出入,以 [英文原版](README.md) 为准。
15
+ > 本翻译对应 v4.18.3 版 README。如与英文原版有出入,以 [英文原版](README.md) 为准。
16
16
 
17
17
  一个 Model Context Protocol (MCP) 服务器,让 AI 助手通过官方脚本 API 控制 DaVinci Resolve Studio(达芬奇)。它提供完整的 API 覆盖,外加带护栏的工作流助手,涵盖剪辑、媒体池整理、渲染设置、审阅标记、调色、Fusion、Fairlight、项目生命周期任务、扩展开发,以及不碰源媒体的媒体分析。
18
18
 
package/docs/SKILL.md CHANGED
@@ -2300,12 +2300,19 @@ media_pool(action="import_bounded_media", params={
2300
2300
  # reported 301 frames). Treat that as an observed configuration-specific result,
2301
2301
  # not a guarantee for every Resolve version or media type.
2302
2302
  media_pool(action="media_pool_boundary_report", params={"selected": True, "depth": 2})
2303
- # Positioned append (MediaPool.AppendToTimeline([{clipInfo}, ...])) — e.g. rebuild a subtitle row after delete_clips
2303
+ # Positioned append (MediaPool.AppendToTimeline([{clipInfo}, ...]))
2304
2304
  media_pool(action="append_to_timeline", params={"clip_infos": [
2305
2305
  {"clip_id": "<uuid>", "start_frame": 0, "end_frame": 100, "record_frame": 1200, "track_index": 4}
2306
2306
  ]})
2307
2307
  ```
2308
2308
 
2309
+ A clipInfo whose MediaPoolItem Type is `Subtitle` is refused on Resolve 21.1
2310
+ and above, and when the connected version cannot be read, with
2311
+ `SUBTITLE_APPEND_CRASH`. On Studio 21.1.2.10 that call aborts Resolve
2312
+ (`Sm2MpObject.cpp:546`, issue #335). The plain `clip_ids` form does not crash,
2313
+ and on that build it also places nothing. Builds older than 21.1 still forward
2314
+ the clipInfo; that route was reported working on Studio 21.0.4.5 (issue #169).
2315
+
2309
2316
  When Resolve answers `AppendToTimeline` with None/False/[], either form fails
2310
2317
  with `APPEND_TO_TIMELINE_FAILED`, not `success` with `count: 0`, and keeps
2311
2318
  `verified_operation` (the current timeline's item count before and after) on
@@ -12,7 +12,7 @@ that none exists).
12
12
 
13
13
  **Verified on:** DaVinci Resolve Studio 21.0.2
14
14
 
15
- **Totals:** 43 missing capabilities, 61 bugs / unreliable behaviors.
15
+ **Totals:** 43 missing capabilities, 62 bugs / unreliable behaviors.
16
16
 
17
17
  The authoritative source is the runtime-queryable `api_truth` ledger
18
18
  (`resolve_control api_truth "<query>"`); this document is generated from
@@ -181,8 +181,8 @@ equivalent, blocking full automation.
181
181
  ### Speech recognition engine selection and SRT import
182
182
 
183
183
  - **Object:** `Timeline`
184
- - **Behavior:** Timeline.CreateSubtitlesFromAudio(autoCaptionSettings) always uses the built-in Resolve speech recognition engine. There is no API parameter to select an alternative provider (e.g. whisper-cli, Google Speech, AWS Transcribe). The language selection via resolve.AUTO_CAPTION_LANGUAGE_* is the only customization; the engine itself cannot be changed. There is no dedicated subtitle import method. However, MediaPool.ImportMedia(srt) + AppendToTimeline was reported working on Studio 21.0.4.5 (issue #169). Whether that route carries word timing for animated presets on 21.1 has not been verified; SRT contains only cue timing.
185
- - **Workaround / current handling:** Use Resolve's engine for CreateSubtitlesFromAudio. For external SRT, test ImportMedia + AppendToTimeline on the exact installed build or import through the UI. Use project_db write_captions for explicit word timings with Resolve fully quit; do not assume SRT supplies them.
184
+ - **Behavior:** Timeline.CreateSubtitlesFromAudio(autoCaptionSettings) always uses the built-in Resolve speech recognition engine. There is no API parameter to select an alternative provider (e.g. whisper-cli, Google Speech, AWS Transcribe). The language selection via resolve.AUTO_CAPTION_LANGUAGE_* is the only customization; the engine itself cannot be changed. There is no dedicated subtitle import method. MediaPool.ImportMedia(srt) + AppendToTimeline was reported working on Studio 21.0.4.5 (issue #169). On Studio 21.1.2.10 the clipInfo form of that append aborts Resolve and the plain form places nothing (issue #335). Whether either route carries word timing for animated presets has not been verified; SRT contains only cue timing.
185
+ - **Workaround / current handling:** Use Resolve's engine for CreateSubtitlesFromAudio. For external SRT on 21.1.2, import through the UI. clipInfo append of a subtitle item is refused on 21.1+ (see MediaPool.AppendToTimeline subtitle clipInfo). Use project_db write_captions for explicit word timings with Resolve fully quit; do not assume SRT supplies them.
186
186
  - **Tags:** missing-method, subtitle, transcription, speech-recognition, asr
187
187
 
188
188
  ### Media Pool folder rename
@@ -573,6 +573,15 @@ values, or automation-hostile modal prompts.
573
573
  - **Reference:** [issue #123](https://github.com/samuelgursky/davinci-resolve-mcp/issues/123)
574
574
  - **Tags:** render, subtitle, silent-failure, unverified-cause, deliver
575
575
 
576
+ ### MediaPool.AppendToTimeline (subtitle clipInfo)
577
+
578
+ - **Object:** `MediaPool`
579
+ - **Signature:** `([{clipInfo}]) -> [TimelineItem]`
580
+ - **Behavior:** On Studio 21.1.2.10 (Windows), AppendToTimeline with a clipInfo dict for an imported SRT MediaPoolItem (Type Subtitle) aborts Resolve: assertion at Sm2MpObject.cpp:546, reproduced 2/2. The call hangs, then the process is gone. The plain list form AppendToTimeline([item]) does not crash and places nothing. ImportMedia(srt) + AppendToTimeline was reported working on Studio 21.0.4.5 (issue #169). Which clipInfo field triggers the abort was not isolated. Builds 21.1.0 and 21.1.1 were not measured.
581
+ - **Workaround / current handling:** media_pool append_to_timeline, the granular append_to_timeline, and the other clipInfo builders refuse a Type=Subtitle item on Resolve 21.1 and above, and when the connected version cannot be read, with SUBTITLE_APPEND_CRASH, before AppendToTimeline is called. On a build older than 21.1 the call is still forwarded. Import the SRT through the UI on 21.1.2.
582
+ - **Reference:** [issue #335](https://github.com/samuelgursky/davinci-resolve-mcp/issues/335)
583
+ - **Tags:** crash, subtitle, timeline, silent-failure
584
+
576
585
  ### hasattr() / getattr() on Resolve API objects (attribute fabrication)
577
586
 
578
587
  - **Object:** `(all Resolve scripting objects)`
package/install.py CHANGED
@@ -37,7 +37,7 @@ from src.utils.update_check import (
37
37
 
38
38
  # ─── Version ──────────────────────────────────────────────────────────────────
39
39
 
40
- VERSION = "4.18.1"
40
+ VERSION = "4.18.3"
41
41
  # Only hard floor: mcp[cli] requires Python 3.10+. There is no upper bound —
42
42
  # Resolve's scripting bridge loads into newer interpreters on recent builds
43
43
  # (Python 3.14 verified against Resolve Studio 20.3.2). Older Resolve builds
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "davinci-resolve-mcp",
3
- "version": "4.18.1",
3
+ "version": "4.18.3",
4
4
  "description": "NPM bootstrapper for the DaVinci Resolve MCP Server.",
5
5
  "license": "MIT",
6
6
  "author": "Samuel Gursky <samgursky@gmail.com>",
@@ -42,7 +42,7 @@ export async function applyLut(ref, opts = {}) {
42
42
  const xml = ref.content != null ? ref.content : await fs.readFile(ref.drxPath, 'utf8');
43
43
  const bodyHex = extractBodyHex(xml);
44
44
  const newBodyHex = await injectNodeLut(bodyHex, nodeIndex, { lutPath: opts.lutPath, slotMeta });
45
- const newXml = xml.replace(BODY_RE, `<Body>${newBodyHex}</Body>`);
45
+ const newXml = xml.replace(BODY_RE, () => `<Body>${newBodyHex}</Body>`);
46
46
 
47
47
  // ROUND-TRIP ASSERT: decode the patched grade and confirm the LUT ref survives.
48
48
  const parsed = await drxParser().parseDRXContent(newXml);
@@ -107,7 +107,7 @@ export function relinkManifest(offlinePaths, pathMap = [], opts = {}) {
107
107
  continue;
108
108
  }
109
109
  const m = matches[0];
110
- const target = src.replace(m.from, m.to);
110
+ const target = src.replace(m.from, () => m.to);
111
111
  if (opts.checkExists === false || fs.existsSync(target)) relinkable.push({ from: src, to: target, verified: opts.checkExists !== false });
112
112
  else stillOffline.push({ from: src, to: target, reason: 'target does not exist' });
113
113
  }
@@ -61,15 +61,15 @@ export async function editSubtitleTimeline({ source, output, track = 1, inputs =
61
61
  .filter(m => m.decoded.templateId === template_id);
62
62
  if (matches.length !== 1) throw new Error('Native title reference must contain exactly one matching composition');
63
63
  const scaffold = before ?? holder(await fs.readFile(new URL('../assets/lollipop-track.xml', import.meta.url), 'utf8'));
64
- chosen = { ...matches[0], text: scaffold.text.replace(scaffold.hex, matches[0].hex) };
64
+ chosen = { ...matches[0], text: scaffold.text.replace(scaffold.hex, () => matches[0].hex) };
65
65
  }
66
66
  if (!chosen) throw new Error('No animation preset: supply a native preset_reference DRT or apply Word Highlight through the live Effects UI');
67
67
  const patched = Object.keys(parsed.inputs).length
68
68
  ? setPresetInputs(Buffer.from(chosen.hex, 'hex'), parsed.inputs) : Buffer.from(chosen.hex, 'hex');
69
- const section = freshIds(chosen.text.replace(chosen.hex, patched.toString('hex')));
69
+ const section = freshIds(chosen.text.replace(chosen.hex, () => patched.toString('hex')));
70
70
  let text;
71
- if (before) text = target.text.replace(before.text, section);
72
- else if (/<FusionCompHolderItems\s*\/>/.test(target.text)) text = target.text.replace(/<FusionCompHolderItems\s*\/>/, section);
71
+ if (before) text = target.text.replace(before.text, () => section);
72
+ else if (/<FusionCompHolderItems\s*\/>/.test(target.text)) text = target.text.replace(/<FusionCompHolderItems\s*\/>/, () => section);
73
73
  else throw new Error('Unsupported track: missing FusionCompHolderItems field');
74
74
  const xml = exported.xml.slice(0, target.offset) + text + exported.xml.slice(target.offset + target.text.length);
75
75
  // Resolve remaps timeline identity on import. Keep cross-entry sequence
@@ -142,7 +142,7 @@ export async function editCaptionTimeline({ source, output, track = 1, add = [],
142
142
  const elements = final.map((c) => {
143
143
  const s = stagedById.get(c.id);
144
144
  if (!s) return byId.get(c.id).text;
145
- let text = s.fresh ? template.text.replace(template.dbId, randomUUID()) : s.base.text;
145
+ let text = s.fresh ? template.text.replace(template.dbId, () => randomUUID()) : s.base.text;
146
146
  if (s.fresh) text = text.replace(/<(MarkersBA|RenderCacheBA|ImportExportMetadataBA)>[\s\S]*?<\/\1>/g, '<$1/>');
147
147
  text = setTag(text, 'FieldsBlob', s.blob.toString('hex'));
148
148
  text = setTag(text, 'Name', xmlEscape(` ${s.caption.text}`));
@@ -475,7 +475,7 @@ export const drtTool = {
475
475
  const seqRef = dict.entries.find((e) => e.key === 'SeqRef');
476
476
  if (seqRef && remap.has(String(seqRef.value))) {
477
477
  seqRef.value = remap.get(String(seqRef.value));
478
- tlNew = tlNew.replace(fbM[0], `${fbM[1]}${encodeKeyedDict({ hdr: dict.hdr, entries: dict.entries }).toString('hex')}${fbM[3]}`);
478
+ tlNew = tlNew.replace(fbM[0], () => `${fbM[1]}${encodeKeyedDict({ hdr: dict.hdr, entries: dict.entries }).toString('hex')}${fbM[3]}`);
479
479
  }
480
480
  }
481
481
  for (const [n, xml] of Object.entries(containers)) {
@@ -844,7 +844,7 @@ export const drxTool = {
844
844
  });
845
845
  // Splice the new Body into the ORIGINAL envelope (byte-lossless outside the
846
846
  // position varints — labels, keyframes, OFX, still metadata all pass through).
847
- const out = xml.replace(m[0], `<Body>${r.bodyHex}</Body>`);
847
+ const out = xml.replace(m[0], () => `<Body>${r.bodyHex}</Body>`);
848
848
  // Guard: the rewrite must not change the node count (silent-corruption check).
849
849
  const reparsed = await drxParser().parseDRXContent(out);
850
850
  if ((reparsed.nodes || []).length !== r.nodeCount) {
@@ -3,8 +3,9 @@
3
3
  // way into the XML (#332: `R2 $& $'` as a timeline name made MpFolder.xml
4
4
  // unparseable; `Spot $$ 30s` came out as `Spot $ 30s`). Interpolated
5
5
  // replacements are therefore passed as functions, which insert their result
6
- // literally. This file guards that rule and checks the writers that carry user
7
- // text.
6
+ // literally. This file guards that rule for every replace() call (#333 found
7
+ // forms the first guard missed: a variable, a call or a conditional as the
8
+ // replacement) and checks the writers that carry user text.
8
9
 
9
10
  const test = require('node:test');
10
11
  const assert = require('node:assert');
@@ -16,12 +17,15 @@ const { createEmptyProject } = require('../author-project');
16
17
  const { placeSubtitles } = require('../place-subtitles');
17
18
  const { placeGenerator } = require('../place-generator');
18
19
  const { placeFusionTitle } = require('../place-fusion-title');
20
+ const { splitClip, trimClip, trimClipHead } = require('../splice-clips');
21
+ const { placeTransition } = require('../place-transition');
19
22
 
20
23
  const ROOT = path.resolve(__dirname, '..', '..', '..');
21
24
  const TRICKY = "Spot $$ 30s $& $' $` end";
22
25
 
23
26
  function sourceFiles(dir) {
24
27
  const out = [];
28
+ if (!fs.existsSync(dir)) return out;
25
29
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
26
30
  if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
27
31
  const full = path.join(dir, entry.name);
@@ -31,38 +35,134 @@ function sourceFiles(dir) {
31
35
  return out;
32
36
  }
33
37
 
34
- // `.replace(<string or regex literal>, `...${...}...`)` on one line. A template
35
- // that uses a $-backreference ($1, $&, $<name>) needs the string form and is allowed.
36
- const STRING_REPLACEMENT = /\.replace\(\s*(?:'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|\/(?:[^/\\\n]|\\.)+\/[a-z]*)\s*,\s*`((?:[^`\\]|\\.)*)`/g;
38
+ // A small scanner, enough to split each replace() call into its arguments: it
39
+ // skips strings, templates, regex literals and comments, and matches brackets.
40
+ const REGEX_CAN_FOLLOW = '(,=:[!&|?{};+-*%<>~^';
41
+ function prevSignificant(s, i) {
42
+ let j = i - 1;
43
+ while (j >= 0 && /\s/.test(s[j])) j -= 1;
44
+ return j >= 0 ? s[j] : '';
45
+ }
46
+ function skipString(s, i) {
47
+ const q = s[i];
48
+ i += 1;
49
+ while (s[i] !== q) i += s[i] === '\\' ? 2 : 1;
50
+ return i + 1;
51
+ }
52
+ function skipTemplate(s, i) {
53
+ i += 1;
54
+ while (s[i] !== '`') {
55
+ if (s[i] === '\\') i += 2;
56
+ else if (s.startsWith('${', i)) i = skipBracketed(s, i + 1);
57
+ else i += 1;
58
+ }
59
+ return i + 1;
60
+ }
61
+ function skipRegex(s, i) {
62
+ let inClass = false;
63
+ for (i += 1; ; i += 1) {
64
+ const c = s[i];
65
+ if (c === '\\') { i += 1; continue; }
66
+ if (c === '\n' || c === undefined) return -1;
67
+ if (c === '[') inClass = true;
68
+ else if (c === ']') inClass = false;
69
+ else if (c === '/' && !inClass) break;
70
+ }
71
+ i += 1;
72
+ while (/[a-z]/.test(s[i] || '')) i += 1;
73
+ return i;
74
+ }
75
+ // Skip a string, template, comment or regex literal at i; return the index after
76
+ // it, or -1 when none starts there.
77
+ function skipAtom(s, i) {
78
+ const c = s[i];
79
+ if (c === "'" || c === '"') return skipString(s, i);
80
+ if (c === '`') return skipTemplate(s, i);
81
+ if (c === '/' && s[i + 1] === '/') return s.indexOf('\n', i);
82
+ if (c === '/' && s[i + 1] === '*') return s.indexOf('*/', i) + 2;
83
+ if (c === '/' && REGEX_CAN_FOLLOW.includes(prevSignificant(s, i))) return skipRegex(s, i);
84
+ return -1;
85
+ }
86
+ function skipBracketed(s, i) {
87
+ let depth = 0;
88
+ while (i < s.length) {
89
+ const next = skipAtom(s, i);
90
+ if (next > i) { i = next; continue; }
91
+ if ('([{'.includes(s[i])) depth += 1;
92
+ else if (')]}'.includes(s[i]) && --depth === 0) return i + 1;
93
+ i += 1;
94
+ }
95
+ return s.length;
96
+ }
97
+ function callArguments(s, open) {
98
+ const close = skipBracketed(s, open) - 1;
99
+ const args = [];
100
+ let start = open + 1;
101
+ for (let i = start; i < close; ) {
102
+ const next = skipAtom(s, i);
103
+ if (next > i) { i = next; continue; }
104
+ if ('([{'.includes(s[i])) { i = skipBracketed(s, i); continue; }
105
+ if (s[i] === ',') { args.push(s.slice(start, i).trim()); start = i + 1; }
106
+ i += 1;
107
+ }
108
+ args.push(s.slice(start, close).trim());
109
+ return args;
110
+ }
111
+
37
112
  const BACKREF = /\$(?:[0-9&'`]|<[A-Za-z_]\w*>)/;
113
+ // Replacements that are rules a caller writes, where $1 and $& are the feature.
114
+ const INTENDED = new Set([
115
+ 'server/editorial.mjs: a.replace',
116
+ "server/media-ops.mjs: rule.replace ?? ''",
117
+ ]);
38
118
 
39
- function offenders(text) {
119
+ // The replacement of every .replace()/.replaceAll() call must be a function, or a
120
+ // literal with no $ in it. A literal whose $-sequences are backreferences ($1,
121
+ // $&) is deliberate and allowed; anything else (a variable, a call, an
122
+ // interpolated template) may carry a $ and is reported.
123
+ function offenders(text, file = '') {
40
124
  const found = [];
41
- for (const m of text.matchAll(STRING_REPLACEMENT)) {
42
- const template = m[1];
43
- if (!template.includes('${')) continue;
44
- if (BACKREF.test(template.replace(/\$\{[^}]*\}/g, ''))) continue;
45
- found.push(m[0].slice(0, 120));
125
+ for (const m of text.matchAll(/\.(?:replace|replaceAll)\(/g)) {
126
+ const args = callArguments(text, m.index + m[0].length - 1);
127
+ if (args.length < 2) continue;
128
+ const rep = args[1];
129
+ if (/^(async\s+)?(\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>|^function\b/.test(rep)) continue;
130
+ const literal = /^(['"`])[\s\S]*\1$/.test(rep);
131
+ if (literal && !rep.includes('$')) continue;
132
+ if (literal && BACKREF.test(rep.replace(/\$\{[^}]*\}/g, ''))) continue;
133
+ if (INTENDED.has(`${file}: ${rep}`)) continue;
134
+ found.push(`${file}: .replace(${args[0].slice(0, 40)}, ${rep.slice(0, 60)})`);
46
135
  }
47
136
  return found;
48
137
  }
49
138
 
50
- test('no interpolated replace() replacement is passed as a string', () => {
51
- const files = [...sourceFiles(path.join(ROOT, 'server')), ...sourceFiles(path.join(ROOT, 'vendor'))];
139
+ test('every replace() replacement is a function or a $-free literal', () => {
140
+ const dirs = ['server', 'vendor', 'bin', '../scripts', '../bin'].map((d) => path.join(ROOT, d));
141
+ const files = dirs.flatMap(sourceFiles);
52
142
  assert.ok(files.length > 50, `scanned ${files.length} files`);
53
- const bad = [];
54
- for (const file of files) {
55
- for (const hit of offenders(fs.readFileSync(file, 'utf8'))) bad.push(`${path.relative(ROOT, file)}: ${hit}`);
56
- }
57
- assert.deepStrictEqual(bad, [], 'pass the replacement as () => `...` so $-sequences stay literal');
143
+ const bad = files.flatMap((file) => offenders(fs.readFileSync(file, 'utf8'), path.relative(ROOT, file).split(path.sep).join('/')));
144
+ assert.deepStrictEqual(bad, [], 'pass the replacement as () => ... so $-sequences in it stay literal');
58
145
  });
59
146
 
60
- test('the guard catches the #332 form and allows the safe ones', () => {
61
- assert.strictEqual(offenders("x.replace('</MediaVec>', `${el}\\n</MediaVec>`)").length, 1);
62
- assert.strictEqual(offenders('x.replace(/<Name>[^<]*<\\/Name>/, `<Name>${n}</Name>`)').length, 1);
63
- assert.strictEqual(offenders("x.replace('</MediaVec>', () => `${el}\\n</MediaVec>`)").length, 0);
64
- assert.strictEqual(offenders('x.replace(/(<a>)<b\\/>/, `$1<b>${hex}</b>`)').length, 0);
65
- assert.strictEqual(offenders("x.replace('a', 'b')").length, 0);
147
+ test('the guard catches each string form and allows the safe ones', () => {
148
+ const caught = [
149
+ "x.replace('</MediaVec>', `${el}\\n</MediaVec>`)", // #332
150
+ 'x.replace(/<Name>[^<]*<\\/Name>/, `<Name>${n}</Name>`)',
151
+ 'out.replace(c, nc)', // #333
152
+ 'items.replace(target, setClipDuration(target, d))',
153
+ 'x.replace(/<Items>[\\s\\S]*?<\\/Items>/, body ? `<Items>${body}</Items>` : "<Items/>")',
154
+ 'x.replaceAll(a, b)',
155
+ ];
156
+ for (const code of caught) assert.strictEqual(offenders(code).length, 1, code);
157
+ const allowed = [
158
+ "x.replace('</MediaVec>', () => `${el}\\n</MediaVec>`)",
159
+ 'x.replace(/(<a>)<b\\/>/, `$1<b>${hex}</b>`)',
160
+ "x.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')",
161
+ "x.replace('a', 'b')",
162
+ 'x.replace(re, (m, g) => g.toUpperCase())',
163
+ "x.replace(re, function (m) { return m + ', '; })",
164
+ ];
165
+ for (const code of allowed) assert.strictEqual(offenders(code).length, 0, code);
66
166
  });
67
167
 
68
168
  async function sequenceXml(buffer) {
@@ -93,3 +193,34 @@ test('placeFusionTitle keeps $-sequences in the clip name', async () => {
93
193
  const res = await placeFusionTitle(buffer, { trackIndex: 2, startFrame, durationFrames: 24, name: TRICKY });
94
194
  assert.ok((await sequenceXml(res.buffer)).includes(`<Name>${escapeXml(TRICKY)}</Name>`));
95
195
  });
196
+
197
+ // A second clip on a track goes through the populated-track branch of
198
+ // setItemsInner, and splitClip/placeTransition rewrite the clip in place. A
199
+ // string replacement there copies the matched <Items> block ($&) and the text
200
+ // around it ($`, $') into the track, duplicating clips.
201
+ const nameCount = (xml) => xml.split(`<Name>${escapeXml(TRICKY)}</Name>`).length - 1;
202
+
203
+ async function titledTrack() {
204
+ const { buffer, startFrame } = await createEmptyProject({ timelineName: 'Track' });
205
+ const first = await placeFusionTitle(buffer, { trackIndex: 2, startFrame, durationFrames: 24, name: TRICKY });
206
+ const second = await placeFusionTitle(first.buffer, { trackIndex: 2, startFrame: startFrame + 24, durationFrames: 24, name: 'Next' });
207
+ return { buffer: second.buffer, startFrame };
208
+ }
209
+
210
+ test('a clip added to a populated track leaves the clip already there intact', async () => {
211
+ const xml = await sequenceXml((await titledTrack()).buffer);
212
+ assert.strictEqual(nameCount(xml), 1);
213
+ assert.strictEqual(xml.split('<Name>Next</Name>').length - 1, 1);
214
+ });
215
+
216
+ test('splitClip, trimClip, trimClipHead and placeTransition keep $-sequences in the clip name', async () => {
217
+ const { buffer, startFrame } = await titledTrack();
218
+ for (const trim of [trimClip, trimClipHead]) {
219
+ const res = await trim(buffer, { track: 2, clipIndex: 0, newDuration: 12, frames: 6, ripple: true });
220
+ assert.strictEqual(nameCount(await sequenceXml(res.buffer)), 1);
221
+ }
222
+ const split = await splitClip(buffer, { track: 2, at: startFrame + 12 });
223
+ assert.strictEqual(nameCount(await sequenceXml(split.buffer)), 2);
224
+ const res = await placeTransition(buffer, { track: 2, atFrame: startFrame + 24 });
225
+ assert.strictEqual(nameCount(await sequenceXml(res.buffer)), 1);
226
+ });
@@ -438,7 +438,7 @@ async function assembleTimeline(spec = {}) {
438
438
  const me = Buffer.alloc(16);
439
439
  me.writeDoubleLE(originFrame / 24, 0);
440
440
  me.writeDoubleLE((maxEnd - originFrame) / 24, 8);
441
- mpF = mpF.replace(tlBlock, tlBlock.replace(meM[0], `<MediaExtents>${me.toString('hex')}</MediaExtents>`));
441
+ mpF = mpF.replace(tlBlock, () => tlBlock.replace(meM[0], () => `<MediaExtents>${me.toString('hex')}</MediaExtents>`));
442
442
  zipF.file(mpP, mpF);
443
443
  buffer = await zipF.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
444
444
  }
@@ -105,7 +105,7 @@ function replaceBodyForClip(seqXml, targetDbId, newBodyHex) {
105
105
  if (bodyAt < 0) return null;
106
106
  let newClipRange = clipRange.replace(
107
107
  bodyRe,
108
- `<Body>${newBodyHex}</Body>`,
108
+ () => `<Body>${newBodyHex}</Body>`,
109
109
  );
110
110
 
111
111
  // 4. Mark the owning version as corrected. Resolve keeps a per-version
@@ -96,7 +96,7 @@ async function placeCompound(drpInput, opts = {}) {
96
96
  if (!seqRef) throw new Error('placeCompound: embedded blob has no SeqRef entry — schema drift, refusing to author a crasher');
97
97
  seqRef.value = innerContainerId;
98
98
  const patched = encodeKeyedDict({ hdr: dict.hdr, entries: dict.entries }).toString('hex');
99
- pool = pool.replace(fbM[0], `${fbM[1]}${patched}${fbM[3]}`);
99
+ pool = pool.replace(fbM[0], () => `${fbM[1]}${patched}${fbM[3]}`);
100
100
  }
101
101
  pool = pool.replace(/<Name>[^<]*<\/Name>/, () => `<Name>${escapeXml(name)}</Name>`);
102
102
  // MediaExtents = [startSec, durationSec] LE doubles; inner starts at 0.
@@ -103,7 +103,7 @@ async function placeFusionTitle(drpInput, opts = {}) {
103
103
  if (Object.values(titleInputs).some((v) => v !== undefined && v !== null)) {
104
104
  const m = clip.match(/<CompositionBA>([0-9a-fA-F]*)<\/CompositionBA>/);
105
105
  if (!m || !m[1]) throw new Error('placeFusionTitle: template has no CompositionBA to style');
106
- clip = clip.replace(m[0], `<CompositionBA>${setTitleInputs(m[1], titleInputs)}</CompositionBA>`);
106
+ clip = clip.replace(m[0], () => `<CompositionBA>${setTitleInputs(m[1], titleInputs)}</CompositionBA>`);
107
107
  }
108
108
 
109
109
  // Locate VideoTrackVec and split into track elements.
@@ -137,7 +137,7 @@ async function placeTransition(drpInput, opts = {}) {
137
137
  const transitionDbId = (trans.match(/<Sm2TiTransition DbId="([^"]+)"/) || [])[1] || null;
138
138
 
139
139
  // Insert the transition <Element> immediately after the left clip's <Element> in <Items>.
140
- const newItems = items.replace(clips[leftIdx], `${clips[leftIdx]}${trans}`);
140
+ const newItems = items.replace(clips[leftIdx], () => `${clips[leftIdx]}${trans}`);
141
141
  tracks[track - 1] = setItemsInner(tracks[track - 1], newItems);
142
142
 
143
143
  const xml = replaceTrackVec(seqXml, trackType, vec, tracks);
@@ -91,7 +91,7 @@ function setItemsInner(trackElement, inner) {
91
91
  if (/<Items\s*\/>/.test(trackElement)) {
92
92
  return body ? trackElement.replace(/<Items\s*\/>/, () => `<Items>${body}</Items>`) : trackElement;
93
93
  }
94
- return trackElement.replace(/<Items>[\s\S]*?<\/Items>/, body ? `<Items>${body}</Items>` : '<Items/>');
94
+ return trackElement.replace(/<Items>[\s\S]*?<\/Items>/, () => (body ? `<Items>${body}</Items>` : '<Items/>'));
95
95
  }
96
96
 
97
97
  function insertClipIntoTrack(trackElement, clipElement) {
@@ -57,8 +57,8 @@ function clipIn(clipXml) {
57
57
  }
58
58
  function setClipIn(clipXml, framePos) {
59
59
  const enc = `<In>${encodeSourceIn(framePos)}</In>`;
60
- if (/<In\s*\/>/.test(clipXml)) return clipXml.replace(/<In\s*\/>/, enc);
61
- if (/<In>[^<]*<\/In>/.test(clipXml)) return clipXml.replace(/<In>[^<]*<\/In>/, enc);
60
+ if (/<In\s*\/>/.test(clipXml)) return clipXml.replace(/<In\s*\/>/, () => enc);
61
+ if (/<In>[^<]*<\/In>/.test(clipXml)) return clipXml.replace(/<In>[^<]*<\/In>/, () => enc);
62
62
  return clipXml; // no In element to set
63
63
  }
64
64
  // A FROZEN clip carries an EMPTY <In/> (harvested live from an EDL M2 000.0
@@ -77,7 +77,7 @@ function mapClipsOnTrack(trackElement, fn) {
77
77
  let out = inner;
78
78
  for (const c of splitClipElements(inner)) {
79
79
  const nc = fn(c);
80
- if (nc !== c) out = out.replace(c, nc);
80
+ if (nc !== c) out = out.replace(c, () => nc);
81
81
  }
82
82
  return setItemsInner(trackElement, out);
83
83
  }
@@ -263,7 +263,7 @@ async function trimClip(drpInput, opts = {}) {
263
263
  const tStart = clipStart(target);
264
264
  const trimmedClipDbId = clipDbId(target);
265
265
 
266
- let track = setItemsInner(tracks[trackIdx - 1], items.replace(target, setClipDuration(target, newDuration)));
266
+ let track = setItemsInner(tracks[trackIdx - 1], items.replace(target, () => setClipDuration(target, newDuration)));
267
267
  if (ripple && oldDuration !== null && tStart !== null) {
268
268
  const delta = newDuration - oldDuration;
269
269
  const tEnd = tStart + oldDuration;
@@ -335,7 +335,7 @@ async function trimClipHead(drpInput, opts = {}) {
335
335
  edited = setClipDuration(edited, newDur);
336
336
  edited = setClipStart(edited, newStart);
337
337
 
338
- let track = setItemsInner(tracks[trackIdx - 1], items.replace(target, edited));
338
+ let track = setItemsInner(tracks[trackIdx - 1], items.replace(target, () => edited));
339
339
  if (ripple) {
340
340
  track = mapClipsOnTrack(track, (c) => {
341
341
  const s = clipStart(c);
@@ -399,7 +399,7 @@ async function splitClip(drpInput, opts = {}) {
399
399
  right = setClipDuration(right, rightDur);
400
400
  right = setClipIn(right, leftIn + leftDur); // source continues where left ended
401
401
 
402
- const track = setItemsInner(tracks[trackIdx - 1], items.replace(target, `${left}${right}`));
402
+ const track = setItemsInner(tracks[trackIdx - 1], items.replace(target, () => `${left}${right}`));
403
403
  tracks[trackIdx - 1] = track;
404
404
 
405
405
  const xml = replaceTrackVec(seqXml, trackType, vtv, tracks);
@@ -70,7 +70,7 @@ function restampVersions(xmlStr, src, target) {
70
70
  return xmlStr
71
71
  .split(`DbAppVer="${src.dbAppVer}"`).join(`DbAppVer="${target.dbAppVer}"`)
72
72
  .split(`DbPrjVer="${src.dbPrjVer}"`).join(`DbPrjVer="${target.dbPrjVer}"`)
73
- .replace(PROJECT_VERSION_RE, `<ProjectVersion>${target.dbPrjVer}</ProjectVersion>`);
73
+ .replace(PROJECT_VERSION_RE, () => `<ProjectVersion>${target.dbPrjVer}</ProjectVersion>`);
74
74
  }
75
75
 
76
76
  /**
@@ -88,7 +88,7 @@ function expandSynonyms(text, synonyms) {
88
88
  const regex = new RegExp(`\\b${alt}\\b`, 'gi');
89
89
  if (regex.test(expanded)) {
90
90
  // Don't replace, just note the canonical form
91
- expanded = expanded.replace(regex, canonical);
91
+ expanded = expanded.replace(regex, () => canonical);
92
92
  }
93
93
  }
94
94
  }
@@ -20,6 +20,7 @@ for path in (SRC_DIR, PROJECT_DIR):
20
20
  from mcp.server.fastmcp import FastMCP
21
21
  from mcp.types import ToolAnnotations
22
22
  from src.utils.mcp_error_flag import ErrorFlaggingFastMCP
23
+ from src.utils import subtitle_append_guard
23
24
 
24
25
  from src.utils.app_control import (
25
26
  get_app_state,
@@ -92,7 +93,7 @@ if not logging.getLogger().handlers:
92
93
  handlers=[logging.StreamHandler()],
93
94
  )
94
95
 
95
- VERSION = "4.18.1"
96
+ VERSION = "4.18.3"
96
97
  logger = logging.getLogger("davinci-resolve-mcp")
97
98
  logger.info(f"Starting DaVinci Resolve MCP Server v{VERSION}")
98
99
  logger.info(f"Detected platform: {get_platform()}")
@@ -679,6 +680,23 @@ def _normalize_record_frame(ci, index, timeline_start_frame=None):
679
680
  return start + rf, None
680
681
 
681
682
 
683
+ def _resolve_version_string():
684
+ """Connected Resolve version, or None. Called only for a subtitle clipInfo."""
685
+ try:
686
+ resolve = get_resolve()
687
+ except Exception:
688
+ return None
689
+ if resolve is None:
690
+ return None
691
+ getter = getattr(resolve, "GetVersionString", None)
692
+ if not callable(getter):
693
+ return None
694
+ try:
695
+ return getter()
696
+ except Exception:
697
+ return None
698
+
699
+
682
700
  def _build_append_clip_info_dict(root, ci, index, timeline_start_frame=None):
683
701
  """Build one MediaPool.AppendToTimeline clipInfo map (6 keys per docs line 221).
684
702
 
@@ -716,6 +734,16 @@ def _build_append_clip_info_dict(root, ci, index, timeline_start_frame=None):
716
734
  mt = ci.get("mediaType", ci.get("media_type"))
717
735
  if mt is not None:
718
736
  out["mediaType"] = mt
737
+ if subtitle_append_guard.is_subtitle_item(mp_item):
738
+ message = subtitle_append_guard.refusal_message(
739
+ out, _resolve_version_string(), index=index,
740
+ )
741
+ if message:
742
+ return None, {
743
+ "error": message,
744
+ "code": "SUBTITLE_APPEND_CRASH",
745
+ "retryable": False,
746
+ }
719
747
  return out, None
720
748
 
721
749
 
@@ -195,6 +195,9 @@ def append_to_timeline(
195
195
  relative to the current timeline start frame by default; pass
196
196
  record_frame_mode="absolute" for raw Resolve recordFrame values.
197
197
  Returns timeline_item_id per appended item.
198
+ A MediaPoolItem whose Type is Subtitle is refused on Resolve 21.1+
199
+ with code SUBTITLE_APPEND_CRASH. On Studio 21.1.2.10 that clipInfo
200
+ aborts Resolve (issue #335).
198
201
  """
199
202
  project, mp, err = _get_mp()
200
203
  if err:
package/src/server.py CHANGED
@@ -11,7 +11,7 @@ Usage:
11
11
  python src/server.py --full # Start the 377-tool granular server instead
12
12
  """
13
13
 
14
- VERSION = "4.18.1"
14
+ VERSION = "4.18.3"
15
15
 
16
16
  import base64
17
17
  import os
@@ -63,6 +63,7 @@ from src.utils.resolve211_edits import validate_edit_options, validate_transitio
63
63
  from src.utils.cdl import normalize_cdl_payload
64
64
  from src.utils.media_paths import media_exists as _media_exists
65
65
  from src.utils import archive_guard
66
+ from src.utils import subtitle_append_guard
66
67
  from src.utils import typed_api_search
67
68
  from src.utils import lut_files
68
69
  from src.utils import resolve_writes as _resolve_writes
@@ -3912,6 +3913,68 @@ def _timeline_start_frame(tl) -> Optional[int]:
3912
3913
  return None
3913
3914
 
3914
3915
 
3916
+ def _connected_resolve_version():
3917
+ """The connected Resolve version string, or None when it cannot be read.
3918
+
3919
+ Only called once a payload is already known to contain a subtitle clipInfo,
3920
+ so a missing connection is not an excuse to launch Resolve from a test.
3921
+ """
3922
+ try:
3923
+ resolve = get_resolve()
3924
+ except Exception:
3925
+ return None
3926
+ if resolve is None:
3927
+ return None
3928
+ getter = getattr(resolve, "GetVersionString", None)
3929
+ if not callable(getter):
3930
+ return None
3931
+ try:
3932
+ return getter()
3933
+ except Exception:
3934
+ return None
3935
+
3936
+
3937
+ def _payload_has_subtitle_clipinfo(payload) -> bool:
3938
+ rows = [payload] if isinstance(payload, dict) else payload
3939
+ if not isinstance(rows, list):
3940
+ return False
3941
+ for row in rows:
3942
+ if isinstance(row, dict) and subtitle_append_guard.is_subtitle_item(row.get("mediaPoolItem")):
3943
+ return True
3944
+ return False
3945
+
3946
+
3947
+ def _subtitle_append_block(payload, index=None):
3948
+ """Structured refusal for a subtitle clipInfo that would abort Resolve 21.1.
3949
+
3950
+ None when the payload may be forwarded. Clip objects, the plain
3951
+ AppendToTimeline([item]) form, are not clipInfos and are not refused.
3952
+ The version is read only after a subtitle clipInfo is present, so a
3953
+ normal append does not touch the Resolve connection from here.
3954
+ """
3955
+ if not _payload_has_subtitle_clipinfo(payload):
3956
+ return None
3957
+ message = subtitle_append_guard.refusal_message(
3958
+ payload, _connected_resolve_version(), index=index,
3959
+ )
3960
+ if not message:
3961
+ return None
3962
+ return _err(
3963
+ message,
3964
+ code="SUBTITLE_APPEND_CRASH",
3965
+ category="unsupported",
3966
+ retryable=False,
3967
+ reason=subtitle_append_guard.MEASURED,
3968
+ remediation=(
3969
+ "Do not send a clipInfo for a subtitle MediaPoolItem on Resolve 21.1. "
3970
+ "On Studio 21.1.2.10 that call aborts Resolve. The plain clip_ids form "
3971
+ "does not crash, and on that build it also places nothing. Import the "
3972
+ "SRT in the Resolve UI, or use project_db write_captions with Resolve "
3973
+ "fully quit."
3974
+ ),
3975
+ )
3976
+
3977
+
3915
3978
  def _build_append_clip_info_dict(
3916
3979
  root,
3917
3980
  ci: Dict[str, Any],
@@ -3965,6 +4028,9 @@ def _build_append_clip_info_dict(
3965
4028
  mt = ci.get("mediaType", ci.get("media_type"))
3966
4029
  if mt is not None:
3967
4030
  out["mediaType"] = mt
4031
+ blocked = _subtitle_append_block(out, index=index)
4032
+ if blocked:
4033
+ return None, blocked
3968
4034
  return out, None
3969
4035
 
3970
4036
 
@@ -4512,14 +4578,18 @@ def _append_clip_info_from_timeline_item(
4512
4578
  if src_end_excl is None or src_end_excl <= src_start:
4513
4579
  return None, _err("invalid source range")
4514
4580
  record = int(record_frame) if record_frame is not None else t_start + int(record_frame_offset)
4515
- return {
4581
+ info = {
4516
4582
  "mediaPoolItem": mpi,
4517
4583
  "startFrame": src_start,
4518
4584
  "endFrame": src_end_excl,
4519
4585
  "recordFrame": record,
4520
4586
  "trackIndex": int(target_track_index),
4521
4587
  "mediaType": int(media_type),
4522
- }, None
4588
+ }
4589
+ blocked = _subtitle_append_block(info)
4590
+ if blocked:
4591
+ return None, blocked
4592
+ return info, None
4523
4593
 
4524
4594
 
4525
4595
  def _find_appended_timeline_item_summary(
@@ -15603,6 +15673,9 @@ def _compare_timeline_append_readback(before, observed, expected_count: int):
15603
15673
 
15604
15674
 
15605
15675
  def _append_to_timeline_with_verification(proj, mp, append_payload, requested: Dict[str, Any], expected_count: int):
15676
+ blocked = _subtitle_append_block(append_payload)
15677
+ if blocked:
15678
+ return None, None, None, blocked
15606
15679
  raw_result = {"value": None}
15607
15680
  before = _timeline_append_readback_snapshot(proj)
15608
15681
 
@@ -15622,7 +15695,7 @@ def _append_to_timeline_with_verification(proj, mp, append_payload, requested: D
15622
15695
  intent=requested,
15623
15696
  label="media_pool.append_to_timeline",
15624
15697
  )
15625
- return raw_result["value"], verification, before
15698
+ return raw_result["value"], verification, before, None
15626
15699
 
15627
15700
 
15628
15701
  def _append_to_timeline_verified_operation(requested: Dict[str, Any], verification: Dict[str, Any], before):
@@ -23261,6 +23334,10 @@ def media_pool(action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str
23261
23334
  record_frame is relative to the current timeline start frame by default;
23262
23335
  pass record_frame_mode="absolute" for raw Resolve recordFrame values.
23263
23336
  Returns timeline_item_id per item.
23337
+ A MediaPoolItem whose Type is Subtitle is refused on Resolve 21.1+
23338
+ (and when the version cannot be read) with SUBTITLE_APPEND_CRASH,
23339
+ before AppendToTimeline. On Studio 21.1.2.10 that clipInfo aborts
23340
+ Resolve (issue #335). Builds older than 21.1 are still forwarded.
23264
23341
  Either form: Resolve answering None/False/[] is APPEND_TO_TIMELINE_FAILED,
23265
23342
  with verified_operation (the timeline readback) kept on the error;
23266
23343
  retryable only when the readback shows nothing was appended.
@@ -23523,13 +23600,15 @@ def media_pool(action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str
23523
23600
  "clip_info_count": len(raw),
23524
23601
  "expected_count": len(built),
23525
23602
  }
23526
- result, verification, before = _append_to_timeline_with_verification(
23603
+ result, verification, before, blocked = _append_to_timeline_with_verification(
23527
23604
  proj,
23528
23605
  mp,
23529
23606
  built,
23530
23607
  requested,
23531
23608
  len(built),
23532
23609
  )
23610
+ if blocked:
23611
+ return blocked
23533
23612
  if not result:
23534
23613
  return _append_to_timeline_failed(
23535
23614
  "Failed to append clip_infos to timeline", result, requested, verification, before,
@@ -23561,13 +23640,15 @@ def media_pool(action: str, params: Optional[Dict[str, Any]] = None) -> Dict[str
23561
23640
  "resolved_clip_count": len(clips),
23562
23641
  "expected_count": len(clips),
23563
23642
  }
23564
- result, verification, before = _append_to_timeline_with_verification(
23643
+ result, verification, before, blocked = _append_to_timeline_with_verification(
23565
23644
  proj,
23566
23645
  mp,
23567
23646
  clips,
23568
23647
  requested,
23569
23648
  len(clips),
23570
23649
  )
23650
+ if blocked:
23651
+ return blocked
23571
23652
  if not result:
23572
23653
  return _append_to_timeline_failed(
23573
23654
  "Failed to append clip_ids to timeline", result, requested, verification, before,
@@ -1758,19 +1758,48 @@ API_TRUTH: List[Dict[str, Any]] = [
1758
1758
  "The language selection via resolve.AUTO_CAPTION_LANGUAGE_* "
1759
1759
  "is the only customization; the engine itself cannot be "
1760
1760
  "changed. There is no dedicated subtitle import method. "
1761
- "However, MediaPool.ImportMedia(srt) + AppendToTimeline was "
1762
- "reported working on Studio 21.0.4.5 (issue #169). Whether "
1763
- "that route carries word timing for animated presets on "
1764
- "21.1 has not been verified; SRT contains only cue timing.",
1761
+ "MediaPool.ImportMedia(srt) + AppendToTimeline was reported "
1762
+ "working on Studio 21.0.4.5 (issue #169). On Studio 21.1.2.10 "
1763
+ "the clipInfo form of that append aborts Resolve and the plain "
1764
+ "form places nothing (issue #335). Whether either route carries "
1765
+ "word timing for animated presets has not been verified; SRT "
1766
+ "contains only cue timing.",
1765
1767
  "recommended": "Use Resolve's engine for CreateSubtitlesFromAudio. "
1766
- "For external SRT, test ImportMedia + AppendToTimeline "
1767
- "on the exact installed build or import through the UI. "
1768
+ "For external SRT on 21.1.2, import through the UI. "
1769
+ "clipInfo append of a subtitle item is refused on 21.1+ "
1770
+ "(see MediaPool.AppendToTimeline subtitle clipInfo). "
1768
1771
  "Use project_db write_captions for explicit word timings "
1769
1772
  "with Resolve fully quit; do not assume SRT supplies them.",
1770
1773
  "tags": ["missing-method", "subtitle", "transcription",
1771
1774
  "speech-recognition", "asr"],
1772
1775
  "submit": "missing",
1773
1776
  },
1777
+ {
1778
+ "symbol": "MediaPool.AppendToTimeline (subtitle clipInfo)",
1779
+ "object": "MediaPool",
1780
+ "signature": "([{clipInfo}]) -> [TimelineItem]",
1781
+ "reality": "On Studio 21.1.2.10 (Windows), AppendToTimeline with a "
1782
+ "clipInfo dict for an imported SRT MediaPoolItem (Type "
1783
+ "Subtitle) aborts Resolve: assertion at Sm2MpObject.cpp:546, "
1784
+ "reproduced 2/2. The call hangs, then the process is gone. "
1785
+ "The plain list form AppendToTimeline([item]) does not crash "
1786
+ "and places nothing. ImportMedia(srt) + AppendToTimeline was "
1787
+ "reported working on Studio 21.0.4.5 (issue #169). Which "
1788
+ "clipInfo field triggers the abort was not isolated. Builds "
1789
+ "21.1.0 and 21.1.1 were not measured.",
1790
+ "recommended": "media_pool append_to_timeline, the granular "
1791
+ "append_to_timeline, and the other clipInfo builders "
1792
+ "refuse a Type=Subtitle item on Resolve 21.1 and above, "
1793
+ "and when the connected version cannot be read, with "
1794
+ "SUBTITLE_APPEND_CRASH, before AppendToTimeline is called. "
1795
+ "On a build older than 21.1 the call is still forwarded. "
1796
+ "Import the SRT through the UI on 21.1.2.",
1797
+ "tags": ["crash", "subtitle", "timeline", "silent-failure"],
1798
+ "submit": "bug",
1799
+ "issue": 335,
1800
+ "mitigation": ["subtitle_append_guard"],
1801
+ "verified_on": "Reported on DaVinci Resolve Studio 21.1.2.10 (Windows); not re-measured here",
1802
+ },
1774
1803
  {
1775
1804
  "symbol": "Media Pool folder rename",
1776
1805
  "object": "MediaPool",
@@ -238,6 +238,10 @@ def _probe_pool_clip_marker_roundtrip(ctx):
238
238
 
239
239
  @probe("pool.append_to_timeline", "media_pool", timeout=60, needs=("clip", "timeline"), destructive=True)
240
240
  def _probe_pool_append_to_timeline(ctx):
241
+ from src.utils.subtitle_append_guard import is_subtitle_item
242
+ if is_subtitle_item(ctx.clip):
243
+ return ("refused: a subtitle clipInfo aborts Resolve 21.1.2 "
244
+ "(Sm2MpObject.cpp:546, issue #335)")
241
245
  pool = ctx.project.GetMediaPool()
242
246
  before = ctx.timeline.GetEndFrame()
243
247
  frames = int(ctx.clip.GetClipProperty("Frames") or 0)
@@ -122,7 +122,7 @@ class PathPolicy:
122
122
 
123
123
  @staticmethod
124
124
  def _under(path: str, roots: Tuple[str, ...]) -> bool:
125
- return any(path == root or path.startswith(root + os.sep) for root in roots)
125
+ return any(path == root or path.startswith(os.path.join(root, "")) for root in roots)
126
126
 
127
127
  def input_file(self, raw: Any) -> str:
128
128
  if not isinstance(raw, str) or not raw:
@@ -0,0 +1,91 @@
1
+ """Refuse a subtitle clipInfo before AppendToTimeline can abort Resolve.
2
+
3
+ On Studio 21.1.2.10 (Windows), ``MediaPool.AppendToTimeline`` with a clipInfo
4
+ dict whose ``mediaPoolItem`` has ``GetClipProperty("Type") == "Subtitle"``
5
+ aborts the process: assertion at ``Sm2MpObject.cpp:546``, reproduced twice
6
+ (issue #335). The plain list form, ``AppendToTimeline([item])``, does not
7
+ crash, and on that build it also places nothing.
8
+
9
+ ``ImportMedia`` plus ``AppendToTimeline`` was reported working on Studio
10
+ 21.0.4.5 (issue #169). Builds 21.1.0 and 21.1.1 were not measured. Every
11
+ 21.1 build is refused, and so is a subtitle clipInfo when the connected
12
+ version cannot be read: forwarding the call is what takes Resolve down.
13
+ """
14
+
15
+ from typing import Any, Optional
16
+
17
+ from src.utils.resolve_versions import at_least
18
+
19
+ #: First build line on which the clipInfo form is refused.
20
+ FLOOR = "21.1"
21
+
22
+ MEASURED = (
23
+ "Reported on DaVinci Resolve Studio 21.1.2.10 (Windows), reproduced 2/2: "
24
+ "MediaPool.AppendToTimeline with a clipInfo for a Type=Subtitle MediaPoolItem "
25
+ "aborts Resolve (Sm2MpObject.cpp:546). The plain clip list does not crash and "
26
+ "places nothing. ImportMedia + AppendToTimeline was reported working on Studio "
27
+ "21.0.4.5 (issue #169). 21.1.0 and 21.1.1 were not measured."
28
+ )
29
+
30
+
31
+ def is_subtitle_item(item: Any) -> bool:
32
+ """True when the MediaPoolItem reports Type Subtitle.
33
+
34
+ A missing getter, a failed read, or a non-string (Resolve returns False
35
+ for an unknown property) is not a subtitle. Only an explicit type match
36
+ refuses the call.
37
+ """
38
+ getter = getattr(item, "GetClipProperty", None)
39
+ if not callable(getter):
40
+ return False
41
+ try:
42
+ value = getter("Type")
43
+ except Exception:
44
+ return False
45
+ if not isinstance(value, str):
46
+ return False
47
+ return value.strip().casefold() == "subtitle"
48
+
49
+
50
+ def refuses(version: Any) -> bool:
51
+ """True when this version must not receive a subtitle clipInfo.
52
+
53
+ ``None`` from :func:`at_least` means the version did not parse. That is
54
+ refused too.
55
+ """
56
+ affected = at_least(version, FLOOR)
57
+ return affected is None or affected
58
+
59
+
60
+ def refusal_message(payload: Any, version: Any, index: Optional[int] = None) -> Optional[str]:
61
+ """The refusal text, or None when the payload may be forwarded.
62
+
63
+ ``payload`` is one clipInfo dict or a list of them. Clip objects, the
64
+ plain ``AppendToTimeline([item])`` form, are not clipInfos and are left
65
+ alone.
66
+ """
67
+ rows = [payload] if isinstance(payload, dict) else payload
68
+ if not isinstance(rows, list):
69
+ return None
70
+ hits = []
71
+ for i, row in enumerate(rows):
72
+ if not isinstance(row, dict):
73
+ continue
74
+ item = row.get("mediaPoolItem")
75
+ if item is not None and is_subtitle_item(item):
76
+ hits.append(i)
77
+ if not hits or not refuses(version):
78
+ return None
79
+ shown = hits[0] if index is None else index
80
+ if at_least(version, FLOOR) is None:
81
+ return (
82
+ f"clip_infos[{shown}] is a subtitle MediaPoolItem, and the connected "
83
+ "Resolve version could not be read. AppendToTimeline with a clipInfo "
84
+ "for that item aborts Resolve Studio 21.1.2.10 (Sm2MpObject.cpp:546, "
85
+ "issue #335), so the call is refused."
86
+ )
87
+ return (
88
+ f"clip_infos[{shown}] is a subtitle MediaPoolItem. On Resolve {version}, "
89
+ "AppendToTimeline with a clipInfo for that item is refused: on Studio "
90
+ "21.1.2.10 it aborts Resolve (Sm2MpObject.cpp:546, issue #335)."
91
+ )